[英]Multiple conditions variables in bash script
我需要这样做:
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
您也可以使用单个[
... ]
进行此操作,但随后必须为每个比较使用单独的集合,并将and运算符移到它们之外:
if [ "$X" != dogs ] && [ "$X" != birds ] && [ "$X" != cats ]; then
...
fi
请注意,您不需要在诸如dogs
类的单字字符串周围加上双引号,但在单括号版本中确实需要在诸如$X
类的参数扩展(变量)周围使用双引号,因为参数值中的空格会导致没有引号的语法错误。
另外,无需在外壳程序脚本中使用大写的变量名,如X
最好保留来自环境的变量,例如$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"
当您有很长的变量和/或很短的比较时,这很有用。
记住要转义特殊字符。
X=$1;
if [ "$X" != "dogs" -a "$X" != "birds" -a "$X" != "dogs" ]
then
echo "it's is a monkey"
fi
最接近您已有的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.