[mdlug] Need help with bash array usage

Robert Meier list1c30fe42 at bellsouth.net
Wed Jul 9 02:05:59 EDT 2008


Jeff,

> Sample script and directories attached.
> I'm trying to find files with a specific filename extension,
> containing a specific string,
> in a directory tree where directory and file names may contain spaces,
> then put it into an array with one complete path per element.
> I can obtain a list with quoted paths and use command substitution
> to load it into the array but the assignment ignores the quotes
> and each element gets a space-delimited substring.
> I think it's a word-splitting problem but am not sure how to fix it.

I suspect it is a word-splitting problem.
The solution is to treat double quotes as the normal way to insert a
variable's contents into the command stream.

I've learned the habit of quoting all my variable string reads unless I
deliberately choose tokenization by spaces.  The extra quotes typed
are well worth avoiding the confusion aforenamed "bane".

	# quotes redundant but good habit for all reads
bash> matching_files="$(find "arraytest" -type f -iname '*.txt' \
      -exec grep -l "MATCH" "{}" \; )"
bash> x=0
bash> echo "$matching_files" | while read f # quote read, but not assignment
bash> do
bash>   echo "$x: $f"		            # quote string read
bash>   ((x++))				    # but not numeric read
bash> done


Hopefully helpful,
-- 
Bob

  "'Men have forgotten this truth,' said the fox.
   'But you must not forget it.
   You become responsible, forever, for what you have tamed.'"
     -- Antoine de Saint-Exupery

  "Aerodynamically, the bumble bee shouldn't be able to fly,
   but the bumble bee doesn't know it so it goes on flying anyway."
     -- Mary Kay Ash

  "The idea that an arbitrary naive human should be able to properly use a
   given tool without training or understanding is even more wrong for
   computing than it is for other tools (e.g. automobiles, airplanes, guns,
   power saws)."
	-- Doug Gwyn

  "A year spent in artificial intelligence,
   is enough to make one believe in God."
     -- Alan Perlis

  "Baseball is 90 percent mental; the other half is physical."
	    -- Yogi Berra




More information about the mdlug mailing list