Bash脚本退出时执行指定命令
如果希望在shell脚本退出时,执行一些命令(例如,环境清理等),可以使用以下方法:
- snippet.bash
trap_exit_fun() { echo "exit code: $?" # do something... } trap trap_exit_fun EXIT ……
实例(demo.sh):
- snippet.bash
set -eo pipefail trap_exit_fun() { exit_code=$? echo "exit code: $exit_code" if [ "$exit_code" != "0" ]; then echo "error!" fi } trap trap_exit_fun EXIT echo "start" xxxxx # error here echo "end"
执行结果:
- snippet.bash
[yz@bogon demo]$ sh demo.sh start demo.sh: line 15: xxxxx: command not found exit code: 127 error! [yz@bogon demo]$ echo $? 127
打赏作者以资鼓励: