如果希望在shell脚本退出时,执行一些命令(例如,环境清理等),可以使用以下方法: ```bash trap_exit_fun() { echo "exit code: $?" # do something... } trap trap_exit_fun EXIT …… ``` 实例(demo.sh): ```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" ``` 执行结果: ```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 ```