Perform an action in every sub-directory using Bash

mikewilliamson picture mikewilliamson · Oct 22, 2010 · Viewed 191.5k times · Source

I am working on a script that needs to perform an action in every sub-directory of a specific folder.

What is the most efficient way to write that?

Answer

kanaka picture kanaka · Oct 22, 2010

A version that avoids creating a sub-process:

for D in *; do
    if [ -d "${D}" ]; then
        echo "${D}"   # your processing here
    fi
done

Or, if your action is a single command, this is more concise:

for D in *; do [ -d "${D}" ] && my_command; done

Or an even more concise version (thanks @enzotib). Note that in this version each value of D will have a trailing slash:

for D in */; do my_command; done