Unix-relational-operators

提供:Dev Guides
移動先:案内検索

Unix/Linux-シェル関係演算子の例

Bourne Shellは、数値に固有の次の関係演算子をサポートしています。 これらの演算子は、値が数値でない限り、文字列値に対して機能しません。

変数 a が10を保持し、変数 b が20を保持すると仮定します-

Operator Description Example
-eq Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a -eq $b ] is not true.
-ne Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true. [ $a -ne $b ] is true.
-gt Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. [ $a -gt $b ] is not true.
-lt Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. [ $a -lt $b ] is true.
-ge Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -ge $b ] is not true.
-le Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -le $b ] is true.

すべての条件式は、周囲にスペースがある角括弧内に配置する必要があることを理解することが非常に重要です。 たとえば、 [$ a ⇐ $ b] は正しいのに対し、 [$ a ⇐ $ b] は正しくありません。

これは、すべての関係演算子を使用する例です-

#!/bin/sh

a=10
b=20

if [ $a -eq $b ]
then
   echo "$a -eq $b : a is equal to b"
else
   echo "$a -eq $b: a is not equal to b"
fi

if [ $a -ne $b ]
then
   echo "$a -ne $b: a is not equal to b"
else
   echo "$a -ne $b : a is equal to b"
fi

if [ $a -gt $b ]
then
   echo "$a -gt $b: a is greater than b"
else
   echo "$a -gt $b: a is not greater than b"
fi

if [ $a -lt $b ]
then
   echo "$a -lt $b: a is less than b"
else
   echo "$a -lt $b: a is not less than b"
fi

if [ $a -ge $b ]
then
   echo "$a -ge $b: a is greater or  equal to b"
else
   echo "$a -ge $b: a is not greater or equal to b"
fi

if [ $a -le $b ]
then
   echo "$a -le $b: a is less or  equal to b"
else
   echo "$a -le $b: a is not less or equal to b"
fi

上記のスクリプトは、次の結果を生成します-

10 -eq 20: a is not equal to b
10 -ne 20: a is not equal to b
10 -gt 20: a is not greater than b
10 -lt 20: a is less than b
10 -ge 20: a is not greater or equal to b
10 -le 20: a is less or  equal to b

関係演算子での作業中に、次の点を考慮する必要があります-

  • 演算子と式の間にはスペースが必要です。 たとえば、2+ 2は正しくありません。 2+と書く必要があります。 2。
  • if …​ then …​ else …​ fi ステートメントは、次の章で説明されている意思決定ステートメントです。