linux - 比较字符串和变量时出现奇怪的 Bash 错误

标签 linux bash scripting

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

最佳答案

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

来自 bash man 页面:

arg1 OP 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.

string1 == string2

string1 = string2

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

关于linux - 比较字符串和变量时出现奇怪的 Bash 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54525432/

相关文章:

c - 为什么我不能在设置 F_SEAL_WRITE 后创建只读的共享映射?

c - 在参数 typedef 更改时重建动态库

linux - 我的代码给出错误 : ./greeting2.sh: line 11: syntax error: unexpected end of file

linux - tail 和 grep 文件以及按 IP 地址的独特颜色

bash - FFmpeg 脚本不循环

powershell - 如何在 Get-CimInstance 中用 2-3 行将 TotalPhysicalMemory 转换为 GB?

linux - 当完成函数读取文件时,Bash 完成有时会与我的终端相匹配

python - numpy.memmap : bogus memory allocation

linux - Kshell 读取文件并定义记录长度,然后从每条记录的末尾去除 ascii 20 个字符

windows - PowerShell:仅为单个命令设置环境变量