繁体   English   中英

在“ if!”之后获取某个命令的退出状态。 某个命令”

[英]Getting exit status of somecommand after “if ! somecommand”

如果出现以下情况,我似乎无法在Bash中获取命令执行的退出代码:

#! /bin/bash

set -eu

if ! curl -sS --fail http://not-there; then
  echo "ERROR: curl failed with exit code of $?" >&2
fi

但是$? 当我的curl以非零值退出时,总是返回零。

如果我不在if条件内执行curl命令,那我的$? 正确返回。

我在这里想念什么吗?

在您的原始代码中, $? 返回的退出状态不是curl而是! curl ! curl

要保留原始值,请选择不需要该求逆的控件结构:

curl -sS --fail http://not-there || {
  echo "ERROR: curl failed with exit code of $?" >&2
  exit 1
}

...或类似以下内容:

if curl -sS --fail http://not-there; then
  : "Unexpected success"
else
  echo "ERROR: curl failed with exit status of $?" >&2
fi

实现目标的另一种方法是先收集返回码,然后执行if语句。

#!/bin/bash
set -eu
status=0
curl -sS --fail http://not-there || status=$?
if ((status)) then
  echo "ERROR: curl failed with exit code of $status" >&2
fi

当您想在脚本或函数的末尾返回错误代码(如果其中任何一个失败)时,检查多个命令是否失败时,我发现此方法特别方便。

请注意,在上面我使用了算术测试,如果里面的值非零,则返回true(0),否则返回false(非零)。 它比使用[[ $status != 0 ]]更短(并且更容易理解)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM