bash: exit

This is a wiki page. Be bold and improve it!

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

exit N

Exit with the status code N.

echo $?

echo the last command's exit code.



Special care must be taken when using pipes.
By default, the return value of a command is that of the last command in the pipe chain.
If one wants to capture an error return value, one may use set -o pipefail:
"pipefail: the return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if no command exited with a non-zero status."

set -o pipefail
sudo command_1 | command_2 | command_3
exit $? # returns 0 or the status of the first command that returns a non-0 status.

Another solution, is to use the Bash internal variable PIPESTATUS:
test ${PIPESTATUS[0]} -eq 0

Why exit does not exit

function return_error {
  return 1

return_error (echo "Error returned. Exiting."; exit 1;)
echo "Continuing..."

The above code, contrary to expectations, outputs:

Error returned. Exiting.

It because the parenthesis () start a sub-shell environment. The return status of the sub-shell itself is 0, not 1.
One must use curly brackets {}, a code block, to achieve the desired effect.

return_error {echo "Error returned. Exiting."; exit 1;}
echo "Continuing..."