Bash: trap exit code
This is myscript.sh :
#!/bin/bash function mytrap { echo "Trapped!" } trap mytrap EXIT exit 3 And when I ran it:
> ./myscript.sh echo $? 3 Why is the exit code of the exit code script with the trap the same as without it? Typically, a function returns an implicit exit code for the last command executed. In this case:
- echo returns 0
- I would expect
mytrapreturn 0 - Since
mytrapis the last function to execute, the script should return 0
Why is this not so? Where is my thinking wrong?
Check out the link on the man bash page below.
exit [n] Turn off the shell with the status n. If n is omitted, the exit status is the status of the last command executed. The EXIT trap is completed before the shell terminates.
You have a debug version of the script to prove that
+ trap mytrap EXIT + exit 3 + mytrap + echo 'Trapped!' Trapped! Consider the same ones that were mentioned in your comments, the trap function that returns an error code,
function mytrap { echo "Trapped!" exit 1 } Check out the advanced version of the script,
+ trap mytrap EXIT + exit 3 + mytrap + echo 'Trapped!' Trapped! + exit 1 and
echo $? 1 To write the exit code to trap ,
function mytrap { echo "$?" echo "Trapped!" }