0

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
1
  • 2
    Don't you want ${directory}/*? Or perphaps (cd "$directory"; for thing in *; do echo $thing; done;). Commented Aug 10, 2016 at 13:52

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

By no loop, do you mean something like some_command */*? I'm assuming that the body of the inner loop is more complicated than a single built-in command, in which case this would have problems with large sets of matches.
1

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

1 Comment

The array is extraneous, and possibly a drain on memory; you can iterate over the pattern directly, which (I think) doesn't need to store the full match in memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.