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?
I’m writing a shell script with #!/bin/sh as the first line so that the
Share
Your question appears to imply
set -e.Assuming
set -e:Instead of
command || trueyou can usecommand || exitCode=$?. The script will continue and the exit status ofcommandis captured inexitCode.$?is an internal variable that keeps the exit code of the last command.Since
||short-circuits ifcommandsucceeds, setexitCode=0between tests or instead use:command && exitCode=0 || exitCode=$?.But prefer to avoid
set -estyle scripting altogether, and instead add explicit error handling to each command in your script.