简体   繁体   中英

Getting exit status of somecommand after “if ! somecommand”

I seem to not be able to get the exit code of the command execution in a Bash if condition:

#! /bin/bash

set -eu

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

But the $? always returns zero, when my curl exits with non-zero.

If I don't do the curl command inside of the if-condition, then my $? returns correctly.

Am I missing something here?

In your original code, $? is returning the exit status not of curl , but of ! curl ! curl .

To preserve the original value, choose a control structure that doesn't require that inversion:

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

...or something akin to:

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

Another way to achieve what you want to do is to collect the return code first, then perform the if statement.

#!/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

I find this method especially convenient when checking for failure of several commands when you want to return an error code at the end of your script or function if any of these has failed.

Please note in the above I use an arithmetic test, which returns true (0) if the value inside is non-zero, and false (non-zero) otherwise. It is shorter (and more readable to my own taste) than using something like [[ $status != 0 ]] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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