以下命令有效:
$ expr 1 : '\(.\)' || echo fail
1
当尝试匹配字符串“0”时,命令失败,例如$? == 1:
$ expr 0 : '\(.\)' || echo fail
fail
手册页说:
Exit status is 0 if EXPRESSION is neither null nor 0
但是,因为匹配字符串为 0 而返回退出状态 1 是没有意义的。
最佳答案
expr
的退出状态取决于返回的字符串,而不是产生该字符串的操作。
The expr utility exits with one of the following values: 0 the expression is neither an empty string nor 0. 1 the expression is an empty string or 0. 2 the expression is invalid.
由于返回字符串为0,所以退出状态为1。
无论您是使用成功的正则表达式匹配还是使用其他运算符来生成 0 都无关紧要。
$ expr 3 - 3 || echo "fail"
0
fail
关于bash - 为什么在匹配单个 0 时 expr 会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63781988/