BashシェルのInteger比較演算子を紹介します。
次の比較演算子を使用して、条件文でIntegerを比較できます。
| Integer comparison | Description | Example |
|---|---|---|
| -eq | is equal to | if [ "$a" -eq "$b" ] |
| -ne | is not equal to | if [ "$a" -ne "$b" ] |
| -gt | is greater than | if [ "$a" -gt "$b" ] |
| -ge | is greater than or equal to | if [ "$a" -ge "$b" ] |
| -lt | is less than | if [ "$a" -lt "$b" ] |
| -le | is less than or equal to | if [ "$a" -le "$b" ] |
| < | is less than | (("$a" < "$b")) |
| <= | is less than or equal to | (("$a" <= "$b")) |
| > | is greater than | (("$a" > "$b")) |
| >= | is greater than or equal to | (("$a" >= "$b")) |
Example 1
-eqと同じ形式の比較演算子でIntegerを比較する例です。
#!/bin/bash
a=10
b=10
if [ "$a" -eq "$b" ]
then
echo "a is equal to b"
fiOutput:
$ bash example.sh
a is equal to bExample 2
<と同じ形式の比較演算子でIntegerを比較する例です。
#!/bin/bash
c=10
d=20
if (( "$c" < "$d" ))
then
echo "c is less than d"
fiOutput:
$ bash example.sh
c is less than dRelated Posts
- Bash Shell - 文字列の出力方法(echo, printf)
- Bash Shell - 数値比較演算子
- Bash Shell - 変数が定義されているかどうかを確認する方法
- Bash Shell - スリープ関数、特定の時間を停止する
- Bash Shell - 文字列 切り出し(substring、split)
- Bash Shell - 日付、時刻を取得する
- Bash Shell - 文字列を連結する方法
- Bash Shell - ファイルの生成と文字列の追加
- Bash Shell - 文字列比較、文字列が含まれているかどうかを確認する
- Bash Shell - 条件文(if-else)
- Bash Shell - 数値演算(プラス、マイナス、乗算、除算)