I have a fundamental question about how bash works, and a related practical question.
Fundamental question: suppose I am in a directory that has three subdirectories: a, b, and c.
hen the code
for dir in $(ls)
do
echo $dir
done
spits out:
a b c
a b c
a b c
i.e, dir
always stores a list of all of the files/directories in my cwd
. My question is: why in the world would this be convenient? In my opinion it is far more useful and intuitive to have dir
store each element at a time, i.e I would want to have output
a
b
c
Also, as per one of the answers - it is wrong to use for dir in $(ls)
, but when I use for dir in $(ls -l)
I get even more copies of a b c
(more than there are directories/files in the cwd). Why is that?
My second question is practical: how do I loop over all the directories (not files!) in my cwd
that start with capital W? I started with
for dir in `ls -l W*`
but this fails because a) the reason in question 1 and b) because it doesn't exclude files. Suggestions appreciated.
$(ls)
, but when I wrote up the question I changed$(ls)
to$(ls -l)
because that seems to be how it's done everywhere I've looked. I assumed that the output would be the same and am surprised that it's not.ls -l
is different compared to justls
? The parameter changes its behaviour (typeman ls
for details):-l
gives you long output, including permissions, ownership, date etc. This is an even bigger no-no to parse, because its output can differ immensely depending on the implementation and yourlocale
.ls -l
is what you would use on the command line, but never in a script like this. If you have seen code that parses its output in your environment you should contact the author and ask for it to be fixed.$(ls)
case yields three rows ofa b c
, while the output of$(ls -l)
yields three rows each containing the desired output (a
, followed byb
, followed byc
). I figured the commands are ... similar? ... so should produce reasonably ... similar? ... output.