我需要做这件事:
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
您需要将每个选项转换为单独的条件表达式,然后使用 &&
(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
,则需要使用双引号,因为参数值中的空格将导致语法错误。$PATH
和 $TERM
等等。||
,其工作方式相同。您甚至可以想得不同...
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
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
最接近你已有的
$X
,因为bash
不会对参数执行单词扩展。即使X="lassie scooby"
,[[ $X != dogs ]]
也可以正常工作。 - chepner[[ ! ( $X = dogs || $X = birds || $X = cats ) ]]
吗?这个表达式等价于 && 表达式,但应用了德摩根定律。 - chepner[]
дёӯпјҢжӮЁеҸҜд»ҘдҪҝз”Ё-a
иЎЁзӨә&&
пјҢдҪҝз”Ё-o
иЎЁзӨә||
гҖӮ - Idelic