if文のサンプル・数値比較編 †bashを利用しif .. then .. fi を利用したサンプルシェルスクリプトを以下に記します。 関連記事 †数値比較方法 †下表に記す文字列により、数値比較ができます。
数値の比較条件が成り立つ場合、$?に0がセットされます。 このeq, ne, lt, le, gt, geなどは、<>が使えなかった時代のFORTRAN言語の表記を踏襲したらしいです。 数値比較のサンプルシェルスクリプト †以下のサンプルシェルスクリプトは、2つの数値引数を比較します。 #!/bin/bash function usage { echo Usage: echo -e \\t`basename $0` num1 num2 exit 1 } if [ $# -ne 2 ]; then usage fi # -eq : equal if [ $1 -eq $2 ]; then echo "$1 = $2" fi # -ne : not equal if [ $1 -ne $2 ]; then echo "$1 != $2" fi # -lt : less than if [ $1 -lt $2 ]; then echo "$1 < $2" fi # -le : less than or equal if [ $1 -le $2 ]; then echo "$1 <= $2" fi # -gt : greater than if [ $1 -gt $2 ]; then echo "$1 > $2" fi # -ge : greater than or equal if [ $1 -ge $2 ]; then echo "$1 >= $2" fi サンプルシェルスクリプトの実行結果 †$ ./sample.sh 1 1 1 = 1 1 <= 1 1 >= 1 $ ./sample.sh 1 2 1 != 2 1 < 2 1 <= 2 $ ./sample.sh 2 1 2 != 1 2 > 1 2 >= 1 |