簡體   English   中英

Linux Shell腳本:if / else在bash上有效,但在zsh或sh上無效

[英]Linux Shell Scripting: if/else works on bash but not zsh or 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僅提及“ =”,並且根據破折號手冊 ,“ 僅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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM