我不确定如何在shell中进行多个测试if
。我在编写这个脚本时遇到了麻烦:
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" && "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 = $arg2 && $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
问题是我每次都会收到此错误:
./ compare.sh:[:missing`]'找不到命令
答案 0 :(得分:32)
sh
将&&
解释为shell运算符。将其更改为-a
,即[
的合作运算符:
[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]
另外,你应该总是引用变量,因为[
在你离开参数时会感到困惑。
答案 1 :(得分:30)
Josh Lee的回答有效,但您可以使用“&&”运算符为了更好的可读性,如下所示:
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
答案 2 :(得分:9)
使用双括号......
if [[ expression ]]
答案 3 :(得分:6)
我的代码中有一个示例。试试这个:
echo "*Select Option:*"
echo "1 - script1"
echo "2 - script2"
echo "3 - script3 "
read option
echo "You have selected" $option"."
if [ $option="1" ]
then
echo "1"
elif [ $option="2" ]
then
echo "2"
exit 0
elif [ $option="3" ]
then
echo "3"
exit 0
else
echo "Please try again from given options only."
fi
这应该有效。 :)
答案 4 :(得分:5)
将“[”改为“[[”和“]”改为“]]”。
答案 5 :(得分:1)
这对我有用,
# cat checking.sh
#!/bin/bash
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 == $arg2 ] && [ $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
# ./checking.sh
You have provided the following arguments
All of the specified args are equal
您可以在脚本中添加“set -x”来解决错误,
感谢。