I have read some entries regarding this question like in here or here, but I haven't been able to make my code work. It should be very simple.
I need to append items from a while loop, after a small transformation, to an empty list. My code is as follows:
folder='/path/to/directories/'
ls $folder | while read dir ; do
if [[ $dir =~ ANF-* ]]; then
names=()
ls $folder/$dir/FASTQS | while read file ; do
name=$(echo $file | cut -d "_" -f 1-3 )
echo $name
names+=("$name")
done
echo ${names[*]} #Also tried echo ${names[@]}
fi
done
The first 'echo' works so it gets through the conditional and into the second loop.
I have also tried using 'declare -a' to create the empty array.
If I try to append $file to the list it does not work either.
I think the problem is the appending action because if I create an array that is not empty I got the array's items in the second 'echo'.
Thanks a lot in advance. RX
ls(the output of which is notoriously brittle), you should use globs:for dir in "$folder"/*; do, which solves both the setting-variable-in-a-subprocess problem and is robust with respect to filenames.ANF-*as a regular expression meansANF,ANF-,ANF--,ANF---etc., which probably isn't what you meant. If you meant "starts withANF-, you should have used^ANF-.*(.*for "any number of any character"), or just^ANF-because=~checks submatches; or[[ $dir == ANF-* ]](shell patterns instead of regex).for file in "$folder"/ANF-*/FASTQS/*; do, and depending on what the filenames look like, you could probably use parameter expansion to get the parts you want.