Why this does not list anything? Thank you
FOLDER=()
ls /tmp/backup/ | while read DIR
do
FOLDER+=("$DIR")
done
echo ${FOLDER[1]}
Why this does not list anything? Thank you
FOLDER=()
ls /tmp/backup/ | while read DIR
do
FOLDER+=("$DIR")
done
echo ${FOLDER[1]}
Analysis
Your example is designed to fail. For example:
ls
.Use Shell Globs
Assuming that every entry in /tmp/backup is a directory, you can simply use shell globs to populate your array. If you may have files as well as directory entries, then you'll need to use find or use a shell test expression to ensure that the entry is actually a directory. For example:
As the others already mentioned one of the problems with the code above is modifying of a variable in a subshell. The other is using
+=
to populate the array. Unfortunately this just adds to zeroth element as a string, so thatFOLDERS[1]
stays undefined.To work around subshellissue (see Diego's answer), you can also do something like
while
gets executed in a child shell, and it cannot modify parent's variables, in this case,FOLDER
. You should try other ways. For example:(will print the second file in there)
NOTE: Yes, I understand the problems of this solution, spaces, use of
ls
, etc. I just wanted to point out the problem withwhile
. To complete the answer, yes, globbing should be used:And, by not dying of purism, the usual (at least in UNIXes) is NOT having spaces in filenames. It is bad for your health :)