How do I loop through only directories in bash?
You can specify a slash at the end to match only directories:
for d in */ ; do
echo "$d"
done
You can test with -d
:
for f in *; do
if [ -d "$f" ]; then
# $f is a directory
fi
done
This is one of the file test operators.
Beware that choroba's solution, though elegant, can elicit unexpected behavior if no directories are available within the current directory. In this state, rather than skipping the for
loop, bash will run the loop exactly once where d
is equal to */
:
#!/usr/bin/env bash
for d in */; do
# Will print */ if no directories are available
echo "$d"
done
I recommend using the following to protect against this case:
#!/usr/bin/env bash
for f in *; do
if [ -d "$f" ]; then
# Will not run if no directories are available
echo "$f"
fi
done
This code will loop through all files in the current directory, check if f
is a directory, then echo f
if the condition returns true. If f
is equal to */
, echo "$f"
will not execute.