Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
fi

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
fi

What are my options? Thanks.

share|improve this question
add comment

3 Answers

How about something like this?

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

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
add comment

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
1  
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
add comment

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
fi

do_something $DOWNLOADED_ARTIFACT
share|improve this answer
add comment

Your Answer

 
discard

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.