if - 条件に応じてコマンドを実行する

概要

if CONDITION; COMMANDS_TRUE ...;
[else if CONDITION2; COMMANDS_TRUE2 ...;]
[else; COMMANDS_FALSE ...;]
end

説明

if will execute the command CONDITION. If the condition's exit status is 0, the commands COMMANDS_TRUE will execute. If the exit status is not 0 and else is given, COMMANDS_FALSE will be executed.

条件の中で notand 、または or を使用できます。下の 2 番目の例を参照してください。

直前に終了したフォアグラウンドコマンドの終了ステータスには、常に $status 変数を使用してアクセスできます。

-h--help オプションはこのコマンドのヘルプを表示します。

使用例

以下のコードは、ファイル foo.txt が存在し、かつ通常のファイルであれば foo.txt exists を出力します。そうでなく、ファイル bar.txt が存在し通常のファイルであれば bar.txt exists を出力し、いずれも存在しない場合は foo.txt and bar.txt do not exist を出力します。

if test -f foo.txt
    echo foo.txt exists
else if test -f bar.txt
    echo bar.txt exists
else
    echo foo.txt and bar.txt do not exist
end

以下のコードは、foo.txt が通常のファイルであり、かつ読み取り可能な場合に "foo.txt exists and is readable" を出力します。

if test -f foo.txt
   and test -r foo.txt
   echo "foo.txt exists and is readable"
end

参照

if の有用性は、条件として使用されるコマンドに依存します。

fish には以下の便利なコマンドが同梱されています。