Linux Shell 脚本:if/else 适用于 bash,但不适用于 zsh 或 sh



这是我正在编写的安装程序,删除了所有不相关的位:

#!/bin/bash
echo "In the prompt below, type 'install' or 'remove' (without the quotes)"
echo "If you type neither, this script will terminate."
read -p "Action to perform: " OPERATION
if [ "$OPERATION" == "install" ]
then
echo "Installing..."
echo "Install successful!"
elif [ "$OPERATION" == "remove" ]
then
echo "Removing..."
echo "Remove successful!"
else
echo "Aborting with no actions"
fi

此脚本完全按照您的预期工作。当我键入install时,安装部分执行,当我键入remove删除部分执行,最后当我键入随机字符时,它会中止。

但是相同的脚本将#!/bin/bash替换为#!/bin/sh或留空(我的常规shell是ZSH),它出错了:

In the prompt below, type 'install' or 'remove' (without the quotes)
If you type neither, this script will terminate.
Action to perform: sdfsdfdsf
./test.sh: 7: [: sdfsdfdsf: unexpected operator
./test.sh: 11: [: sdfsdfdsf: unexpected operator
Aborting with no actions

对于某些上下文,我在Ubuntu Studio 18.04上,zsh --version打印zsh 5.4.2 (x86_64-ubuntu-linux-gnu)

有人可以帮助我理解为什么会发生这种情况吗?

在 ubuntu 18.04 上,/bin/sh是指向[ ... ]不支持==/bin/dash的符号链接。您可以使用也适用于 zsh 的[ = ]

[STEP 101] # grep 18.04 /etc/os-release
VERSION="18.04.2 LTS (Bionic Beaver)"
PRETTY_NAME="Ubuntu 18.04.2 LTS"
VERSION_ID="18.04"
[STEP 102] # ls -l /bin/sh
lrwxrwxrwx 1 root root 4 2019-02-14 09:49 /bin/sh -> dash
[STEP 103] # /bin/sh
# [ a == b ]
/bin/sh: 1: [: a: unexpected operator
# test a == b
/bin/sh: 2: test: a: unexpected operator
# [ a = b ]
# test a = b
# exit
[STEP 104] #

请注意,POSIX只提到了"=",并且根据dash手册,">只有POSIX指定的功能,加上一些Berkeley扩展,才被合并到这个shell中。

拳头您应该更新您的 shebang 以使用sh而不是bash然后您将不得不使用稍微不同的语法。您可以使用 shellcheck 来查看详细错误。

文章的语气描述了这种差异,例如: https://stackoverflow.com/a/5725402/3872881

#!/bin/sh
echo "In the prompt below, type 'install' or 'remove' (without the quotes)"
echo "If you type neither, this script will terminate."
echo -n "Action to perform: "
read -r OPERATION
if [ "$OPERATION" = "install" ]
then
echo "Installing..."
echo "Install successful!"
elif [ "$OPERATION" = "remove" ]
then
echo "Removing..."
echo "Remove successful!"
else
echo "Aborting with no actions"
fi

最新更新