Shellのif文について
shell のif文で if test -f test.txtだのif [ -f test.txt ] など書き方があって、
意味を忘れがちになってしまうので、shellのif文について簡単なメモ書きでまとめます。
if文の前にtestコマンドについて
testコマンドとは、条件式の評価をして真偽値を返却してくれるコマンド。
ファイルの有無や文字列比較に用いることが多く、if文を書くときに必ず出てくると言っていいほどのコマンドです。
if文の基本形
#!/bin/sh
if test -f test.txt
then
echo 'test.txt'
elif test -f text.sh
then
echo 'test.sh'
else
echo 'nothing'
fi
- if文はifで始まりfiで終わります。
- そして、条件式のあとにthenをつけて、コマンドの実行文を書きます。
条件部を1行で
#!/bin/sh
if test -f test.txt; then
echo 'test.txt'
elif test -f text.sh; then
echo 'test.sh'
else
echo 'nothing'
fi
- 条件部の最後にセミコロンをつけて、1行で表現
testコマンドの省略
#!/bin/sh
if [ -f test.txt ]; then
echo 'test.txt'
elif [ -f text.sh ]; then
echo 'test.sh'
else
echo 'nothing'
fi
- testコマンドを省略した場合、[]で条件をくくる。
- []内部の空白は文法上必須だから注意