Perform an action in every sub-directory using Bash

前端 未结 9 595
迷失自我
迷失自我 2020-12-04 05:46

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?

9条回答
  •  萌比男神i
    2020-12-04 06:17

    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
    

提交回复
热议问题