Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to wrap my head around Bash, and think I have gotten pretty far. What I really don't understand yet is the error handling...

I have the following script:

set -e
set -u

DOWNLOADED_ARTIFACT=$(downloadApplication "$WEB_GROUP")
if [[ $? != 0 ]]; then
  exit 1

Even though the downloadApplication function fails (my expected result now), the script does NOT fail. I can't really figure out how to check this when capturing the output into a variable. If I don't put it back into a variable it works and fails as expected:

downloadApplication "$WEB_GROUP"
if [[ $? != 0 ]]; then
  exit 1

What are my options? Thanks.

share|improve this question

How about something like this?

DOWNLOADED_ARTIFACT=$(downloadApplication "$WEB_GROUP" || echo "SomeErrorString")
if [ $DOWNLOADED_ARTIFACT == "SomeErrorString" ]; then
  exit 1

That means "if downloadApplication is not successful, then echo SomeErrorString" (so your DOWNLOADED_ARTIFACT will be set to SomeErrorString. Then you can compare against that value.

share|improve this answer

The command DOWNLOADED_ARTIFACT=$(downloadApplication "$WEB_GROUP") will always suceed, because what matters for $? is the assignment to the variable, which is (nearly) guaranteed to succeed, either with the assignment of 0 or 1 to DOWNLOADED_ARTIFACT.

share|improve this answer
I don't think this is true: var=$(sh -c 'exit 1'); echo $? outputs 1. $? is the exit status of the last command, and variable assignment is not a command. – glenn jackman May 8 '12 at 13:40

Your error handling works fine for me. In fact, with set -e the script exits on the execute-and-assign line because the result isn't checked. Are you sure that downloadApplication exits with the correct exit code? Try executing downloadApplication "$WEB_GROUP"; echo $? directly on the command line.

By the way, you can check the return code and capture the output in a single statement:

if ! DOWNLOADED_ARTIFACT=$(downloadApplication "$WEB_GROUP"); then
    echo "Download failed"
    exit 1

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.