IF中的Bash或条件

时间:2015-08-27 15:48:36

标签: bash if-statement

为什么OR条件在以下bash脚本中不起作用?

read number
if [ "$number" != 1 -o "$number" != 2 ] ; then  echo not 1 or 2   fi
if [ "$number" == 1 -o "$number" == 2] ; then   echo 1 or 2  fi 
exit

1 个答案:

答案 0 :(得分:1)

我试过这个并且有效:

#!/bin/bash
read number
if [ "$number" != 1 -o "$number" != 2 ];then
    echo not 1 or 2
fi
if [ "$number" == 1 -o "$number" == 2 ];then
    echo 1 or 2
fi
exit

输出:

[~]$./test1.sh 
2
not 1 or 2
1 or 2

无论如何根据正确的语法和你的第一个输出消息你应该使用它:

#!/bin/bash
read number
if [ "$number" -ne 1 ] && [ "$number" -ne 2 ];then
     echo not 1 or 2
fi
if [ "$number" -eq 1 ] || [ "$number" -eq 2 ];then
    echo 1 or 2
fi
exit

输出:

[~]$./test1.sh 
1
1 or 2
[~]$./test1.sh 
2
1 or 2
[~]$./test1.sh 
3
not 1 or 2
[~]$./test1.sh 
4
not 1 or 2

最诚挚的问候 克劳迪奥