bash 参数相等性检查的意外输出

Unexpected output for bash argument equality check

我在 Bash 脚本中进行了基本的字符串相等性检查,但输出与预期不同。

要重现,请将下面的代码复制到可执行文件中 (在我下面的示例中称为 'deploy').

#!/bin/bash

echo 

if [[ "" -eq "--help" ]] || [[ "" -eq "-h" ]]; then
    echo "hello"
fi


如果我 运行 脚本是这样的:

./deploy -h

输出为:

-h
hello

如果我 运行 脚本是这样的:

./deploy --help

输出为:

-help

为什么条件语句不解析为真?

-eq 比较整数。使用 === 比较字符串。

if [[ "" == "--help" ]] || [[ "" == "-h" ]]; then
    echo "hello"
fi

您可以省略引号。 == 的 left-hand 一侧的变量扩展在使用双括号时是安全的。

你也可以在括号内使用||。用单括号不可能做到这一点,但双括号是一种语法特征,具有允许这样做的特殊解析规则。

if [[  == --help ||  == -h ]]; then
    echo "hello"
fi

如果情况变得更复杂,您还可以考虑 case 块。

case  in
    -h|--help)
        echo "hello";;
esac

If -eq is for numerical comparison, how come ./deploy -h worked as expected?

算术求值通常会在给定非法表达式时打印一条错误消息,但碰巧您要求它求值的两个字符串在语法上是有效的。

  • -h 否定未定义变量 $h 的值。结果为 0.
  • --help 是递减未定义的变量$help。结果是-1.

尝试使用无效的字符串,您将收到错误消息。

$ ./deploy 'foo bar'
bash: [[: foo bar: syntax error in expression (error token is "bar")
$ ./deploy @
bash: [[: @: syntax error in expression (error token is "@")