2

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.

Anders S
  • 121
  • 2

3 Answers3

1

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.

Janne Pikkarainen
  • 31,454
  • 4
  • 56
  • 78
0

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.

Sven
  • 97,248
  • 13
  • 177
  • 225
  • 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 08 '12 at 13:40
0

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
mgorven
  • 30,036
  • 7
  • 76
  • 121