linux - 比较字符串和变量时出现奇怪的 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
解决方案
-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] ]]
推荐阅读
- javascript - ReactJS:使用 JSX 进行数据转换
- python - 我试图理解 __init__ 中的参数和下面代码中的函数
- r - 删除以特定单词开头的所有句子
- firebase - 如何通过自定义令牌在 Firebase 身份验证上设置标识符?
- java - 比较器数据结构排序 - 如何在另一个字段上排序时保持插入顺序?
- javascript - 如何读出 SourceBuffer/MediaSource 对象的字节流数据?
- scala - 使用火花在红移中写入慢速数据帧
- javascript - 如何使用 angular-screenshot 打印整个 DOM 元素?
- python - 变量是否需要在 tflearn 的会话中初始化?
- regex - 如何从每行的第一个单词中删除下划线?