bash - 为什么在匹配单个 0 时 expr 会失败

标签 bash expr

以下命令有效:

$ 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/

相关文章:

linux - Azure Batch 使用哪种 "command line"来执行 Ubuntu 上的启动任务?

arrays - 使用 jq 为 JSON 数组运行计数器

bash - 逐行读取文件时,我只能在第一行执行 ffmpeg

if-statement - 如何在 if 语句中使用 expr?

python - python中mathematica的等价运算

javascript - MongoDB 查找具有多个 eq 的 expr

linux - 使用 expr 实用程序在 Linux 中进行浮点运算

bash - bash 中的递归函数

linux - 如何使用 Bash 和标准实用程序确定两个字符串之间的行数?

arrays - bash- 求行中数字的平均值