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.

1
1

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.

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

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 '* *'

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.