このエントリーをはてなブックマークに追加


if文のサンプル・数値比較編

bashを利用しif .. then .. fi を利用したサンプルシェルスクリプトを以下に記します。


関連記事

数値比較方法

下表に記す文字列により、数値比較ができます。

-eq等しいかをチェック 数値 = 数値equal
-ne異なるかをチェック 数値 ≠ 数値not equal
-lt数値 < 数値をチェックless than
-le数値 ≦ 数値をチェックless than or equal
-gt数値 > 数値をチェックgreater than
-ge数値 ≧ 数値をチェックgreater than or equal

数値の比較条件が成り立つ場合、$?に0がセットされます。
数値の比較条件が成り立たない場合は、$?に1がセットされます。

この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


添付ファイル: filesample.sh 828件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2015-03-20 (金) 22:27:06