bash - 在 shell 脚本中使用 if elif fi

标签 bash shell

<分区>

我不确定如何在 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 `]' command not found

最佳答案

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

关于bash - 在 shell 脚本中使用 if elif fi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2359270/

相关文章:

bash - 如何使用 Bash 将一个目录合并到另一个目录?

shell - 从 GNU Makefile 调用 `command -v find`

linux - 执行 printf 命令 shell 脚本

bash - 如何将子 shell 的输出文件描述符重定向到父 shell 中的输入文件描述符?

arrays - 如何在数组中存储带有空格的元素?

python - 从 Python 运行 bash 脚本

linux - 从输出中删除 chkconfig header

shell - 使用 Powershell 脚本调用 Mirth Connect CLI

java - cronjob 执行时 shell 脚本失败,否则工作正常

bash - tr -d [=,=] 的作用是什么?