bash检查命令是否从变量成功

时间:2019-02-20 17:14:51

标签: bash

我通常会检查命令是否成功执行或超时,这样就可以了;

if timeout 30 someCommand; then
    echo "we're good"
else
    echo "command either failed or timed out"
fi

但是使用我的新脚本处理循环和变量,这根本无法按预期工作;

wallets=/usr/local/bin/*-cli

for i in $wallets; do
    current_blocks=$(timeout 30 $i getblockcount)

    if $current_blocks; then
        echo "we're good"
    else
        echo "command either failed or timed out"
    fi
done

我该如何解决?

2 个答案:

答案 0 :(得分:3)

上一个命令的状态显示为$?

wallets=/usr/local/bin/*-cli

for i in $wallets; do
    current_blocks=$(timeout 30 "$i" getblockcount)
    status=$?

    if [ "$status" -eq 0 ]; then
        echo "we're good"
    else
        echo "command either failed or timed out"
    fi
done

或者您可以直接检查状态:

if current_blocks=$(timeout 30 "$i" getblockcount)
then
  echo "It's good and the result is $current_blocks"
fi

答案 1 :(得分:2)

假设$(timeout 30 $i getblockcount)的正常结果是一堆JSON,您将需要使用更多的引号来捕获字符串,然后对其进行非空性测试。

代码片段应如下所示:

  current_blocks="$(timeout 30 $i getblockcount)"

  if [[ -n "$current_blocks" ]]; then
    echo "we're good"
  else
    echo "Command failed or timed out"
  fi

或者,如果只想检查命令的返回状态,则可以检查$?变量。但是,将timeout与命令配合使用时,结果状态可以是 命令状态,也可以是124(超时)。如果该命令无法很好地返回状态,则测试一致状态可能会很困难-除非您只是想测试零(成功)状态。

在这种情况下,代码片段可能类似于:

  current_blocks="$(timeout 30 $i getblockcount)"

  if (( $? == 0 )); then
    echo "we're good"
  else
    echo "Command failed or timed out"
  fi