0

For example, in this for loop

for var in ?????
do
    dummy command
done

I would like to be able to loop through each directory in the one that I am currently in, but it will be an unknown list of directories so I can't write every single one into where the question marks are. Any help is appreciated.

Quasímodo
  • 18,865
  • 4
  • 36
  • 73

3 Answers3

2

At the very simplest, to satisfy your requirement to "loop through each directory in the one that i am currently in", just use a wildcard

for d in */
do
    dummy_command "$d"
done

If your command can't cope with the trailing slash that's part of $d, you can remove it by replacing "$d" with "${d%/}".

If your command can take multiple arguments you don't need a loop at all

dummy_command */

An example of dummy_command for testing might be simply echo.

Notice that in all cases, if there is no match to the */ pattern, it will get passed through as a literal asterisk and slash to your command. This is almost certainly not what you want.

For bash you can fix it by adding this line above your loop, but be aware it will apply from that point on

shopt -s nullglob    # Expand unmatched wildcards to "nothing"

...until you have a corresponding shopt -u nullglob or your script ends

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
0

Like this (list recursively dirs with spaces in file names):

shopt -s globstar
dummy_command **/*' '*/

or if you insist to use a for loop:

shopt -s globstar
for dir in **/*' '*/
    dummy_command "$dir"
done
0

If you want more control over things like min/max depth you can use find in a while loop:

while IFS= read -r dir; do
    echo "$dir"
done < <(find . -type d)

Then, just change your find options to suit whatever you need. Like if you are looking for directory names with spaces, you could do find . -type d -name '* *'

Jason
  • 101