Clara Clara - 4 months ago 15
Bash Question

Nested for loop in bash not iterating properly?

I am new to scripting/programming/everything and can't seem to figure out this bash script/loop I am trying to iterate.

I have a directory called "folder", in which there are many subdirectories which each contain files that I would like to echo (for now)

I have this, but it doesn't seem to print the files within the subdirectories but instead prints the subdirectories themselves. How would I alter the script to make this work?

for directory in *;
do
for thing in $directory
do
echo $thing
done
done

Answer

The for loop itself doesn't traverse a file system; it only iterates over a sequence of strings. You need to iterate over the result of a pathname expansion for the second loop.

for directory in *;
do
    for thing in "$directory"/*
    do
        echo "$thing"
    done
done

You can do this with one loop with a more complex pattern:

for thing in */*; do
    echo "$thing"
done