Code:
for dir in *; do \ls -1dQ $dir; done
Actually, the problem isn't the
for loop. That's just fine:
globbing patterns expand last in the parsing order, after word-splitting is finished, so using them in
for loops is no problem. In fact, it's recommended!
How can I find and deal with file names containing newlines, spaces or both?
The trouble here comes later on, when you try to expand the
$dir variable. Now the unquoted variable gets split into individual "words", and
ls gets handed a series of non-file names to try to parse.
The secret is to
always ensure that your variables are double-quoted.
Code:
$ mkdir theNbomr; cd theNbomr; mkdir "Please explain"; mkdir "the downside of for loops"; mkdir "in this"; mkdir context.
$ for dir in *; do \ls -1dQ "$dir"; done
"context."
"in this"
"Please explain"
"the downside of for loops"
There are only a very few times when you'll ever want to leave quotes off, and that's only when you
need the values to be word-split (and even then there are usually
better techniques available). Beware also what I said about globbing too. If any of the filenames should happen to form valid globbing patterns themselves, they will also expand.
http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes
The danger of
for loops is in trying to use them to process the contents of files or command output. Then it becomes very hard to properly word-split the content so that it can be safely parsed one line or section at a time. That's when the
while+read loop should be used.
Don't Read Lines With For
How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?
A large number of scripting problems come down to not clearly understanding the command parsing order, what gets done before or after what. Learn that, and half of your troubles will go away.
http://mywiki.wooledge.org/BashParser
http://wiki.bash-hackers.org/syntax/grammar/parser_exec