Exit code of traps in Bash

血红的双手。 提交于 2019-12-04 19:34:35

问题


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:

  1. echo returns 0
  2. I would expect mytrap to return 0
  3. Since mytrap is the last function executed, the script should return 0

Why is this not the case? Where is my thinking wrong?


回答1:


Look the reference from the below man bash page,

exit [n] Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.

You have the debug version of the script to prove that,

+ trap mytrap EXIT
+ exit 3
+ mytrap
+ echo 'Trapped!'
Trapped!

Consider the same as you mentioned in your comments, the trap function returning an error code,

function mytrap {
    echo "Trapped!"
    exit 1
}

Look the expanded version of the script,

+ trap mytrap EXIT
+ exit 3
+ mytrap
+ echo 'Trapped!'
Trapped!
+ exit 1

and

echo $?
1

To capture the exit code on trap function,

function mytrap {
    echo "$?"
    echo "Trapped!"
}


来源:https://stackoverflow.com/questions/41619629/exit-code-of-traps-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!