这是我正在写的一个安装程序,删除了所有不相关的部分:
#!/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
时,install部分执行,当我键入remove
时,remove部分执行,最后当我键入random characters时,它中止。但用
#!/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 only mentions "="并且根据dash manual,“只有posix指定的特性,加上一些berkeley扩展,才被合并到这个shell中。”
关于linux - Linux Shell脚本:if/else在bash上有效,但在zsh或sh上无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57271359/