Getting the return value in "sh -e"

sh, shell

Solution

Your question appears to imply `set -e`.

Assuming `set -e`:

Instead of `command || true` you can use `command || exitCode=$?`. The script will continue and the exit status of `command` is captured in `exitCode`.

`$?` is an internal variable that keeps the exit code of the last command.

Since `||` short-circuits if `command` succeeds, set `exitCode=0` between tests or instead use: `command && exitCode=0 || exitCode=$?`.

But prefer to avoid `set -e` style scripting altogether, and instead add explicit error handling to each command in your script.

Problem

I'm writing a shell script with `#!/bin/sh` as the first line so that the script exits on the first error. There are a few lines in the file that are in the form of `command || true` so that the script doesn't exit right there if the command fails. However, I still want to know know the exit code of the command. How would I get the exit code without having to use `set +e` to temporarily disable that behavior?

Original source