Shell编程-逻辑运算符

时间:2020-02-23 14:45:08  来源:igfitidea点击:

在本教程中,我们将学习Shell编程中的逻辑运算符。

我们使用逻辑运算符来测试多个条件。

以下是我们将要讨论的逻辑运算符。

运算符说明
-a逻辑与
-o逻辑或

在本教程中,我们将使用if语句。

逻辑与

如果两个操作数均为真,则逻辑AND--a运算符将为true。
否则为假。

逻辑AND运算符的真值表。

ABA -a B
falsefalsefalse
falsetruefalse
truefalsefalse
truetruetrue

在下面的示例中,我们将检查该数字是否为偶数且大于10。

为了检查数字是否为偶数,我们使用模运算符"%"。
因此,如果一个数字可被2整除并得到0的余数,则它是一个偶数,否则它是奇数。

#!/bin/sh

# take a number from the user
echo "Enter a number: "
read a

# check
if [ `expr $a % 2` == 0 -a $a -gt 10 ]
then
  echo "$a is even and greater than 10."
else
  echo "$a failed the test."
fi
$sh and.sh 
Enter a number: 
10
10 failed the test.

$sh and.sh 
Enter a number: 
20
20 is even and greater than 10.

逻辑或

如果任一操作数为true,则逻辑OR -o运算符将为true。
如果两个操作数都为假,则它将返回假。

逻辑或者运算符的真值表。

ABA -o B
falsefalsefalse
falsetruetrue
truefalsetrue
truetruetrue

在以下示例中,我们将检查输入的数字是否为奇数或者小于10。

#!/bin/sh

# take a number from the user
echo "Enter a number: "
read a

# check
if [ `expr $a % 2` != 0 -o $a -lt 10 ]
then
  echo "$a is either odd or less than 10."
else
  echo "$a failed the test."
fi
$sh or.sh 
Enter a number: 
10
10 failed the test.

$sh or.sh 
Enter a number: 
9
9 is either odd or less than 10.