1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルスクリプト if文 書き方(6つの例)

Posted at

[ コマンド(test コマンド)

if の直後のリストには、[ が書かれることが多い。
これは、ifの文法とは関係なく、[ コマンドという独立したコマンド。
別名 test コマンド。
if文は、test コマンドの終了ステータスが真か偽によって条件分岐している。

if-example1
num=5
if [ ${num} -eq 5 ]; then
  echo "等しいです"
fi

[ コマンド(test コマンド)以外

終了ステータスが真か偽によって条件分岐ができるのであれば、test コマンド以外でも構わない。
例えば、cmp コマンドであれば、2つのファイルが一致しているか否かで終了ステータスが真(0)か偽(0以外)になるので、if文の条件分岐として利用ができる。
※-sオプションを付けて、不要なメッセージを出さない

if-example2
if cmp -s file1 file2; then
  echo "等しいです"
fi

あえて、[ コマンド(test コマンド)も使う

cmp コマンドを使用したとしても、その終了ステータスをあえて test コマンドでチェックする。

if-example3
if cmp -s file1 file2; [ $? -eq 0 ]; then
  echo "等しいです"
fi

否定演算を使う

! をパイプラインの先頭に書くことで、終了ステータスを反転させる。

if-example4
if ! cmp -s file1 file2; then
  echo "等しくありません"
fi

ifのリストにパイプを使う

パイプの右側の終了ステータスが条件判定に使用される。
※egrepコマンドの結果が出力されないように、標準出力を /dev/null にリダイレクト
※egrep -q オプションでも可

if-example5
if cat file1 | egrep -i 'file1' > /dev/null; then
  echo "file1が含まれています"
fi

&&リストや||リストを使う

if-example6
if cmp -s file1.txt file2.txt && cmp -s file1.txt file3.txt; then
  echo "すべて等しいです"
fi
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?