我需要这样做:
if [ $X != "dogs" and "birds" and "dogs" ]
then
echo "it's is a monkey"
fi
使用 bash 脚本。如何进行?
我需要这样做:
if [ $X != "dogs" and "birds" and "dogs" ]
then
echo "it's is a monkey"
fi
使用 bash 脚本。如何进行?
&&
您需要将每个选项转换为单独的条件表达式,然后使用(AND) 运算符将它们连接在一起。
if [[ $X != dogs && $X != birds && $X != cats ]]; then
echo "'$X' is not dogs or birds or cats. It must be monkeys."
fi
您也可以使用 single [
...来执行此操作]
,但是您必须为每个比较使用单独的集合并将 and 运算符移到它们之外:
if [ "$X" != dogs ] && [ "$X" != birds ] && [ "$X" != cats ]; then
...
fi
请注意,您不需要在单字字符串dogs
(如$X
没有引号。
此外,不需要像X
在 shell 脚本中那样使用大写的变量名;这最好保留给来自环境的变量,比如$PATH
等等$TERM
。
OR 的 shell 运算符版本是||
,其工作方式相同。
你甚至可以有不同的想法...
if ! [[ $X == dogs || $X == birds || $X == cats ]]; then
echo "'$X' is not dogs or birds or cats... It could be monkeys."
fi
作为思考:
它不是狗,也不是猫,也不是鸟
与思考不完全相同
它不是……狗或猫或鸟之一。
这使得方法case
更加明显;好吧,我认为,在这种情况下,正确的做法是:
case $X in
dogs )
# There may be some part of code
;;
birds )
# There may be some other part
;;
cats )
# There is no need to be something at all...
;;
* )
echo "'$X' is not dogs or birds or cats... It could be monkeys."
;;
esac
或者如果真的不需要处理鸟、猫或狗的情况:
case $X in
dogs|birds|cats ) ;;
* )
echo "'$X' is not dogs or birds or cats... It could be monkeys."
;;
esac
我能想到的在 Bash 中避免多次输入 $X 的唯一方法是使用 RegEx:
if [[ ! "$X" =~ (dogs|birds|cats) ]]; then
echo "it's is a monkey"
fi
同样,简而言之:
[[ ! "$X" =~ (dogs|birds|cats) ]] && echo "it's is a monkey"
This is helpful when you have very long variables, and/or very short comparisons.
Remember to escape special characters.
X=$1;
if [ "$X" != "dogs" -a "$X" != "birds" -a "$X" != "dogs" ]
then
echo "it's is a monkey"
fi
最接近你已经拥有的