Marry Jane
Marry Jane

Reputation: 364

bash check if a command succeeds from variable

I usually check if a command succeeds or time out like this, which works just fine;

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

But with my new script which works with loops and variables, this simply doesn't work as expected;

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

how can I fix this?

Upvotes: 0

Views: 120

Answers (2)

aks
aks

Reputation: 2346

Assuming that the normal result of $(timeout 30 $i getblockcount) is a bunch of JSON, you'll need to use more quotes in order to capture the string and then test it for non-emptiness.

The code fragment should look something like this:

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

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

Alternatively, if you only want to check the return status of the command, you can check the $? variable. However, when using timeout with a command, the result status can be either the command status, or 124 from a timeout. If the command does not manage status returns very well, testing for a consistent status might be challenging -- unless you simply want to test for a zero (success) status.

In which case, the code fragment might look like:

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

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

Upvotes: 1

that other guy
that other guy

Reputation: 123680

The status of the previous command is available as $?:

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

Or you can check the status directly:

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

Upvotes: 2

Related Questions