シェルスクリプトその2 制御構文(if文,for文)

はじめに

前回に引き、今回は制御構文をまとめていきます。

if文

他のプログラムと違うところはif文の後ろにつける 条件式 ではなく、コマンド式 ってことです。 最初何行っているのかよくわから買ったのですが、以下の例だとわかりやすいです。

#!/bin/sh
# file名:test1.sh
# []でくくるとbashのコマンドとして評価 スペース注意
if [ true ]; then 
  echo 'true'
end
# test1.sh実行
$ sh test1.sh 
$ true

以下のサンプルコードですと、通常の条件式なら、false では出力されないです。 が、シェルスクリプトだと、あくまでもbash のコマンドとして認識され、出力されます。

#!/bin/sh
# file名:test2.sh
# これでも通る
if [ false ]; then
  echo 'false'
fi
# test2.sh実行
$ sh test2.sh
$ false
#!/bin/sh
# file名:test3.sh
if [ "$1" = "true"  ]; then
  echo 'true'
else
  echo 'false'
fi
# test3.sh実行
$ sh test3.sh 
$ false

$ sh test3.sh true
$ true

for文

for文はあまりハマりどころがなかったので軽くまとめておきます。

for 変数名 in リスト
do 
  # 処理記述
done
#!/bin/sh
# ./test/*.txtを削除するプログラム

for fname in $(find ./test/* -name '*.txt')
do
  rm -rf $fname
done