Bash function, return value and error handling

basherror handling

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.

Best Answer

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.