./...">

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 mytrap return 0
  • Since mytrap is the last function to execute, the script should return 0

Why is this not so? Where is my thinking wrong?

+7
bash exit-code
source share
1 answer

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!" } 
+6
source share

All Articles