如何在目錄內的所有目錄中運行循環

如何在目錄內的所有目錄中運行循環

假設我有一個名為 的目錄/tmp/main ,其中有 100 個其他目錄。

我想在這些目錄的每個目錄中運行一個循環,例如使用touch test.txt

我該如何告訴腳本處理第一個、第二個、第三個等等?

答案1

一個簡單的循環就可以工作:

for dir in /tmp/main/*/; do
    touch "$dir"/test.txt
done

/模式末尾的保證/tmp/main/*/如果模式匹配任何內容,它將匹配目錄。

在 中bash,您可能需要在循環之前設定nullglobshell 選項shopt -s nullglob,以確保如果模式與任何內容都不匹配,則循環根本不會運行。如果沒有nullglob設置,循環仍將運行一次,且模式在 中未展開$dir。解決這個問題的另一種方法是在呼叫之前確保它$dir實際上是一個目錄touch

for dir in /tmp/main/*/; do
    if [ -d "$dir" ]; then
        touch "$dir"/test.txt
    fi
done

或者,等價地,

for dir in /tmp/main/*/; do
    [ -d "$dir" ] && touch "$dir"/test.txt
done

答案2

您可以使用find

find /tmp/main -type d -exec touch {}/test.txt \;

如果您想要排除該/tmp/main資料夾在使用結果中傳回find

find /tmp/main ! -path /tmp/main -type d -exec touch {}/test.txt \;

或者

find /tmp/main -mindepth 1 -type d -exec touch {}/test.txt \;

相關內容