【问题标题】:Weird Bash error while comparing a string and a variable比较字符串和变量时出现奇怪的 Bash 错误
【发布时间】:2019-02-04 22:43:13
【问题描述】:

所以我对 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

【问题讨论】:

标签: linux bash scripting


【解决方案1】:

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

来自bashman 页面:

arg1 操作 arg2

          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] ]]

【讨论】:

  • 这个肯定有几十个重复。虽然我不确定如何搜索它们。
  • @Barmar:可能,但回答起来更快。
  • 嗯,这是一个很好、简洁的答案,我会把它作为我的欺骗候选人。
  • @Barmar 我只发现很多与该错误消息有关的问题几乎重复,但没有一个好问题。
  • 但是,我不认为“快速回答”是回答重复问题的好理由。
猜你喜欢
  • 1970-01-01
  • 2023-02-07
  • 2017-10-11
  • 2011-09-18
  • 2018-09-23
  • 1970-01-01
  • 2014-09-25
  • 2011-04-07
  • 1970-01-01
相关资源
最近更新 更多