32. if 语句内的 AND、OR、!
您可以使用-a或-o计算多个表达式。
AND 使用 -a 进行比较
-a在条件表达式中进行 and 比较
if [ "expression1" -a "expression2" ]
then
statement1
statement2
..
fi
表达式可以是数字比较或字符串比较。 以下示例演示了 and 数字比较:
$ cat and-comparision-numeric.sh
total=${1}
if [ $total -ge 50 -a $total -le 100 ]
then
echo "total between 50 and 100"
fi
if [ $total -ge 1 -a $total -le 49 ]
then
echo "total between 1 and 49"
fi
$ ./and-comparision-numeric.sh 10
total between 1 and 49
以下示例演示了 and 字符串比较:
$ cat and-comparision-string.sh
state=${1}
capital=${2}
if [ $state == "CA" -a "$capital" == "sacramento" ]
then
echo "Yes. California capital is sacramento."
fi
if [ $state == "CA" -a "$capital" != "sacramento" ]
then
echo "No. California capital is not $capital"
fi
$ ./and-comparision1.sh CA "los angeles"
No. California capital is not los angeles
OR 使用 -o 进行比较
-o在条件表达式内进行 or 比较。
$ cat or-comparision.sh
input=${1}
if [ "$input" == "apple" -o "$input" == "orange" ]
then
echo "Yes. $input is a fruit."
fi
$ ./or-comparision.sh orange
Yes. orange is a fruit.
-o可以与数字表达式一起使用,就像-a一样。
逻辑非 !
!表达式是一个 逻辑非 。 我们在前面演示了! –s,但是!可用于反转任何表达式的结果,例如:
$ cat not-comparision.sh
input=${1}
if [ ! "$input" == "apple" ]
then
echo "No. $input is not a fruit."
fi
$ ./not-comparision.sh chicken
No. chicken is not a fruit.