On Thu, 27 May, 2010 at 10:09:02 -0500, David C. Rankin wrote:
On 05/27/2010 04:47 AM, Jon Clausen wrote:
Indeed... however:
Now I *have* tested, and somewhat surprisingly (to me at least) filenames with whitespace are not a problem:
Hmm...
Old dog, new trick! That's pretty cool:
09:55 alchemy:~/tmp> ( myarray=(*); for ((i=0;i<${#myarray[@]};i++)); do printf "myarray[%2d]: %s\n" ${i} "${myarray[${i}]}"; done ) myarray[ 0]: 2010 Narrative Update.txt myarray[ 1]: 80 myarray[ 2]: 90dcf370cbde.tif myarray[ 3]: Abstract-DarkGlow.emerald.zip
whoa... you didn't say anything about *using* the information afterwards... ;)
What I am uncomfortable with is the spaces issue, despite having proven it to myself, but as long as globbing holds, then there should be no reason this wouldn't be as safe as 'for i in *; do ...xyz...; done. In fact, it is probably preferred over my usual: SARRAY=( $(ls $SEARCHDIR) ), though I can't lay my hand on a rule telling me which is preferred.
I think the argument would be that using bash's globbing to create the list avoids spawning a subprocess to execute 'ls *'. So I guess there might be a teeny little performance gain? But OTOH using globbing like this makes no distinction between various 'object' types. So you get everything that the glob matches in your list: files, directories, links, fifos, the lot. So if one has to do 'file type' operations on the objects later, one would have to amend the code with some [ -f ${array[$i]} ] -ish tests, which might end up eating away whatever performance gain one got to begin with. Actually, come to think of it, the above could be the argument for using Per's suggestion to use 'find', rather than to rely on globbing?
With my usual method, setting IFS to newline is definitely required. What i like about (*) is that globbing handles all the spaces for you when loading the array. However, you would still need IFS set to newline (or religious quoting) for any subsequent processing of names with spaces later on in the script.
Yeah I think that about sums it up. And thinking a little about it, it makes sense that you need either IFS manipulation or quoting to avoid trouble: It's how variable expansion works in bash, regardless of how the content was assigned to the variable in the first place... and I guess array element expansion more or less *should* behave like any other 'variable'...
New trick added to toolbox :p
To mine too :) I didn't know about ${#array[@]} before, but your question kicked a couple of synapses into action: I'm in the process of porting a shell script to perl, and over there I regularly use $#array... hence the association. /jon -- YMMV -- To unsubscribe, e-mail: opensuse+unsubscribe@opensuse.org For additional commands, e-mail: opensuse+help@opensuse.org