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