LoginSignup
11
11

More than 5 years have passed since last update.

シェルスクリプトのif文とtestコマンド基礎

Last updated at Posted at 2012-08-30

いつもなんとなく使ってて、あれどうだっけと検索して

if 文と test コマンド - UNIX & Linux コマンド・シェルスクリプト リファレンス

このページにたどり着いて「ああそうだった」となるので、自分でまとめておく。

条件判定にはよく"test"コマンドを使う。testは与えられた条件式の評価結果に応じて0もしくは1を返すコマンド。ファイル形式やパーミッションを判定に使うことができる(man test)が、単純にファイルの存在をみる-eオプションで例を書く。

$ test -e /etc/init.d/syslog-ng; echo $?
0
$ test -e /etc/init.d/hahahaha; echo $?
1

$?の中に直前のtestコマンドのステータスコードが入ってる。
そして、[と]はtestコマンドのaliasである。

$ [ -e /etc/init.d/syslog-ng ]; echo $?
0
$ [ -e /etc/init.d/hahahaha ]; echo $?
1

[と]はコマンドなのでスペースを空けないといけない。

$ [-e /etc/init.d/syslog-ng]; echo $?
-bash: [-e: コマンドが見つかりません
127

if文と組み合わせる

$ if true ; then echo "ok"; else echo "ng"; fi
ok
$ if false ; then echo "ok"; else echo "ng"; fi
ng

true/falseはそれぞれ終了ステータスとして0/1を返す"だけ"のコマンド。

$ if [ -e /etc/init.d/syslog-ng ] ; then echo "ok"; else echo "ng"; fi
ok
$ if [ -e /etc/init.d/hahaha ] ; then echo "ok"; else echo "ng"; fi
ng
11
11
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
11
11