Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trap exit code in Bash script

There're many exit points in my bash code. I need to do some clean up work on exit, so I used trap to add a callback for exit like this:

trap "mycleanup" EXIT 

The problem is there're different exit codes, I need to do corresponding cleanup works. Can I get exit code in mycleanup?

like image 816
Dagang Avatar asked Mar 15 '11 13:03

Dagang


People also ask

How do you use traps in bash?

To set a trap in Bash, use trap followed by a list of commands you want to be executed, followed by a list of signals to trigger it. For complex actions, you can simplify trap statements with Bash functions.

What is the exit code of a bash script?

For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure. If a command is not found, the child process created to execute it returns a status of 127.

How do I print an exit code?

To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.


1 Answers

The accepted answer is basically correct, I just want to clarify things.

The following example works well:

#!/bin/bash  cleanup() {     rv=$?     rm -rf "$tmpdir"     exit $rv }  tmpdir="$(mktemp)" trap "cleanup" EXIT # Do things... 

But you have to be more careful if doing cleanup inline, without a function. For example this won't work:

trap "rv=$?; rm -rf $tmpdir; exit $rv" EXIT 

Instead you have to escape the $rv and $? variables:

trap "rv=\$?; rm -rf $tmpdir; exit \$rv" EXIT 

You might also want to escape $tmpdir, as it will get evaluated when the trap line gets executed and if the tmpdir value changes later that might not give the expected behaviour.

Edit: Use shellcheck to check your bash scripts and be aware of problems like this.

like image 154
Paul Tobias Avatar answered Sep 25 '22 15:09

Paul Tobias