Bash – Capture exit code of exit command

bashexecexitexit-statusshell-script

I have this in a bash script:

exit 3;

exit_code="$?"

if [[ "$exit_code" != "0" ]]; then
    echo -e "${r2g_magenta}Your r2g process is exiting with code $exit_code.${r2g_no_color}";
    exit "$exit_code";
fi

It looks like it will exit right after the exit command, which makes sense.
I was wondering is there some simple command that can provide an exit code without exiting right away?

I was going to guess:

exec exit 3

but it gives an error message: exec: exit: not found
What can I do? 🙂

Best Answer

If you have a script that runs some program and looks at the program's exit status (with $?), and you want to test that script by doing something that causes $? to be set to some known value (e.g., 3), just do

(exit 3)

The parentheses create a sub-shell.  Then the exit command causes that sub-shell to exit with the specified exit status.

Related Question