在shell脚本中使用if elif fi

Zen*_*net 55 bash shell

我不确定如何if在shell中进行多项测试.我在编写这个脚本时遇到了麻烦:

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
Run Code Online (Sandbox Code Playgroud)

问题是我每次都会收到此错误:

./compare.sh:[:missing`]'找不到命令

Jos*_*Lee 33

sh&&将shell 解释为shell运算符.将它更改为-a,这[是联合运算符:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]
Run Code Online (Sandbox Code Playgroud)

此外,你应该总是引用变量,因为[当你离开参数时会感到困惑.


Spl*_*ked 33

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
Run Code Online (Sandbox Code Playgroud)


Hen*_*sek 9

使用双括号......

if [[ expression ]]

  • 从技术上讲,`[`是一个内置的shell,但是`[[`是一个shell关键字.这就是区别. (4认同)
  • 注意,这是一种解决方案,因为外壳中内置了[[]构造,而`[`是`test`命令的另一个名称,因此受其语法约束-参见`man test` (2认同)

小智 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
Run Code Online (Sandbox Code Playgroud)

这应该工作。:)


Eth*_*ost 5

将"["改为"[["和"]"改为"]]".