【问题标题】:Unexpected operator in if statementif 语句中出现意外的运算符
【发布时间】:2019-08-01 09:46:54
【问题描述】:

在以下两行中我得到了这个错误?

怎么了?

Debian Buster

my.sh: 101: [: !=: 意外操作符

my.sh: 103: [: !=: 意外操作符

if [ $CONTINUE != "y" ] && [ "$CONTINUE" != "n" ]; then

elif [ $CONTINUE = "n" ]; then

更新

echo "\nContinue downloading? [y/n]"
read CONTINUE

#   Error: Invalid argument
if [ $CONTINUE != "y" ] && [ $CONTINUE != "n" ]; then
    error "Invalid argument"
elif [ $CONTINUE = "n" ]; then
    echo "\nDonwload terminated!"
    exit
fi

【问题讨论】:

  • 您实际使用的是 Bash 还是 sh?这对解决方案至关重要。

标签: shell if-statement operators sh


【解决方案1】:

您发布的脚本存在各种问题,ShellCheck 突出显示:

Line 1:
echo "\nContinue downloading? [y/n]"
     ^-- SC2028: echo may not expand escape sequences. Use printf.

Line 2:
read CONTINUE
^-- SC2162: read without -r will mangle backslashes.

Line 5:
if [ $CONTINUE != "y" ] && [ $CONTINUE != "n" ]; then
     ^-- SC2086: Double quote to prevent globbing and word splitting.
                             ^-- SC2086: Double quote to prevent globbing and word splitting.

Did you mean: (apply this, apply all SC2086)
if [ "$CONTINUE" != "y" ] && [ "$CONTINUE" != "n" ]; then

Line 7:
elif [ $CONTINUE = "n" ]; then
       ^-- SC2086: Double quote to prevent globbing and word splitting.

Did you mean: (apply this, apply all SC2086)
elif [ "$CONTINUE" = "n" ]; then

Line 8:
    echo "\nDonwload terminated!"
         ^-- SC2028: echo may not expand escape sequences. Use printf.

但尽管存在这些问题脚本实际上在其他方面按预期工作在 Debian (Buster) 的默认 shell(即 dash)上。您可能正在运行非默认 shell。因此,解决您的问题的最简单方法是

  • 声明一个有效的shebang line
  • 修复上面突出显示的问题。

这给我们留下了这个:

#!/bin/sh

printf "\nContinue downloading? [y/n] "
read -r CONTINUE

error() {
    printf >&2 '%s\n' "$@"
    exit 1
}

if [ "$CONTINUE" != y ] && [ "$CONTINUE" != n ]; then
    error "Invalid argument"
elif [ "$CONTINUE" = n ]; then
    printf "\nDownload terminated!\n"
    exit
fi

(这也为未定义的error 调用添加了定义;酌情替换。)

【讨论】: