Unix-boolean-operators

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

Unix/Linux-シェルブール演算子の例

次のブール演算子は、Bourne Shellでサポートされています。

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

Operator Description Example
! This is logical negation. This inverts a true condition into false and vice versa. [ ! false ] is true.
*-o * This is logical* OR*. If one of the operands is true, then the condition becomes true. [ $a -lt 20 -o $b -gt 100 ] is true.
*-a * This is logical* AND*. If both the operands are true, then the condition becomes true otherwise false. [ $a -lt 20 -a $b -gt 100 ] is false.

これは、すべてのブール演算子を使用する例です-

#!/bin/sh

a=10
b=20

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

if [ $a -lt 100 -a $b -gt 15 ]
then
   echo "$a -lt 100 -a $b -gt 15 : returns true"
else
   echo "$a -lt 100 -a $b -gt 15 : returns false"
fi

if [ $a -lt 100 -o $b -gt 100 ]
then
   echo "$a -lt 100 -o $b -gt 100 : returns true"
else
   echo "$a -lt 100 -o $b -gt 100 : returns false"
fi

if [ $a -lt 5 -o $b -gt 100 ]
then
   echo "$a -lt 100 -o $b -gt 100 : returns true"
else
   echo "$a -lt 100 -o $b -gt 100 : returns false"
fi

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

10 != 20 : a is not equal to b
10 -lt 100 -a 20 -gt 15 : returns true
10 -lt 100 -o 20 -gt 100 : returns true
10 -lt 5 -o 20 -gt 100 : returns false

演算子を使用しながら、次の点を考慮する必要があります-

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