Reputation: 31
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
Upvotes: 0
Views: 425
Reputation: 21955
Bash version 4.0 adds a new globbing option called globstar
which treats the pattern **
differently when it's set.
#!/bin/bash
shopt -s globstar
for file in folder/** # with '**' bash recurses all the directories
do
echo "$file"
done
Upvotes: 1
Reputation: 530920
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
Upvotes: 3