
というディレクトリがあり/tmp/main
、その中に 100 個の他のディレクトリがあるとします。
これらのディレクトリの各ディレクトリをループして、たとえば次のようなファイルを作成したいとします。touch test.txt
スクリプトに 1 番目、2 番目、3 番目などを処理するように指示するにはどうすればよいですか?
答え1
単純なループが機能します:
for dir in /tmp/main/*/; do
touch "$dir"/test.txt
done
/
パターンの末尾の は、パターン/tmp/main/*/
が何かに一致する場合、ディレクトリに一致することを保証します。
ではbash
、パターンが何にも一致しない場合はループがまったく実行されないように、ループの前にnullglob
でシェル オプションを設定する必要があります。を設定しないと、 でパターンが展開されていない状態でループが 1 回実行されます。 これを修正する別の方法は、 を呼び出す前に が実際にディレクトリであることを確認することです。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 \;