gpt4 book ai didi

Linux Shell 脚本 : if/else works on bash but not zsh or sh

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:25:56 24 4
gpt4 key购买 nike

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

#!/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 的符号链接(symbolic link),其 [ ... ] 不支持 ==。您可以使用同样适用于 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 Shell 脚本 : if/else works on bash but not zsh or sh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com