【问题标题】:Capture and check return status inline in if statement inside [[ ]] [duplicate]在 [[ ]] 内的 if 语句中内联捕获并检查返回状态 [重复]
【发布时间】:2021-05-31 09:39:04
【问题描述】:

我正在重构我的脚本并尝试将所有if cmd; then fi; 语句转换为if [[cmd]]; then fi。我知道如何通过调用上一行中的命令并在当前行中使用其退出代码来转换它,但我想知道如何内联。

例子:

# I have this

if grep "some-string" some_file.txt > /dev/null; then
  echo "non zero exit status"
fi
# I know how to do this

$(grep "some-string" some_file.txt > /dev/null)
if [[ $? -ne 0 ]]; then
  echo "non zero exit status"
fi
# I want to know how to do something like this?

if [[ grep "some-string" some_file > dev/null ]]; then
  echo "non zero exit status"
fi

请告诉我如何内联执行和检查if [[...]]; then fi 语句中的命令的状态码?

我从 this 引用 bash 并尝试遵循 this 的样式

【问题讨论】:

  • 不要。您现在拥有的if grep ... 版本是正确且惯用的。 [[ ]] 用于测试条件表达式,而不是查看命令是否成功(除非您将命令的退出状态存储在变量中,在这种情况下,您需要条件表达式来检查值变量)。
  • 什么?! [[ grep ... 没有任何意义。 if grep ... 是正确的方法。该样式指南的哪一部分让您认为需要对其进行重构?
  • (OT:重构代码需要删除> /dev/null并添加-q。)
  • @Biffen this part in the style guide 让我感到困惑。我在使用 shell 时并不精通 shell 脚本。不过,grep 的 -q 标志很有帮助。
  • @rsampaths16 该部分不适用于命令的退出代码。它只是说使用[[ 而不是test(以及其他调用test 的方式,例如[)。您没有使用test,因此该规则不适用。

标签: bash


【解决方案1】:

这没有意义:

if cmd ; ...

将运行cmd,然后根据 cmd 的退出状态进行分支。

同样,

if [[ cmd ]]; ....

运行命令 [[...]] 并相应地分支。它不运行cmd

实际上,只要您只想知道退出状态是否为零,我看不出您有什么理由要摆弄$?。如果您有多个退出状态值要区分,情况会有所不同。例如:

grep foo bar; status=$?
if (( status == 0 ))
then
   # actions where grep found the pattern
elif (( status == 1 ))
   # actions where grep did not find the pattern
else
   # actions where grep encountered a serious problem
fi

在这种情况下,调用命令后立即将退出代码存储到某个变量中,稍后使用ifcase 或您需要的任何内容进行处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 2019-06-23
    • 1970-01-01
    • 2016-08-27
    • 2018-11-09
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多