This is myscript.sh
:
#!/bin/bash
function mytrap {
echo "Trapped!"
}
trap mytrap EXIT
exit 3
And when I run it:
> ./myscript.sh
echo $?
3
Why is the exit code of the script the exit code with the trap the same as without it? Usually, a function returns implicitly the exit code of the last command executed. In this case:
- echo returns 0
- I would expect
mytrap
to return 0 - Since
mytrap
is the last function executed, the script should return 0
Why is this not the case? Where is my thinking wrong?
Look the reference from the below
man bash
page,You have the debug version of the script to prove that,
Consider the same as you mentioned in your comments, the
trap
function returning an error code,Look the expanded version of the script,
and
To capture the exit code on
trap
function,