首页 > 解决方案 > 比较字符串和变量时出现奇怪的 Bash 错误

问题描述

所以我对 bash 非常熟悉,但是第二个 if 语句一直给我一个错误。

./run.sh: line 39: [: q: integer expression expected
./run.sh: line 39: [: q: integer expression expected

我不确定是什么问题。我很确定我的语法是正确的。

read -p "Option Number-> " answer
#  Check to see if the answer is only letters
if [[ "$answer" =~ ^[a-zA-Z]+$ ]];then
    if [ "$answer" -eq "q" ] || [ "$answer" -eq "Q" ];then
        exit
    fi

标签: linuxbashscripting

解决方案


-eq用于整数比较,用于文本比较=

bash man页面:

参数 1 操作参数 2

          OP  is one of -eq, -ne, -lt, -le, -gt, or -ge.  These arithmetic
          binary operators return true if arg1 is equal to, not equal  to,
          less  than, less than or equal to, greater than, or greater than
          or equal to arg2, respectively.  Arg1 and arg2 may  be  positive
          or negative integers.

字符串 1 == 字符串 2

字符串 1 = 字符串 2

          True if the strings are equal.  = should be used with  the  test
          command  for  POSIX conformance.  When used with the [[ command,
          this performs pattern matching as described above (Compound Com-
          mands).

顺便说一句,您的比较可以写成一个模式

if [[ "$answer" == [Qq] ]]

推荐阅读