简体   繁体   中英

Weird Bash error while comparing a string and a variable

So I am pretty familiar with bash but the second if statement keeps throwing me an error.

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

I am not exactly sure what is the problem. I am pretty sure my syntax is correct.

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 is used for integer comparisons, for text comparisons use =

From the bash man pages:

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. 

and

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). 

By the way, your comparison could be written as a pattern :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM