开发者

Can you access the code of an exit command in a trap?

开发者 https://www.devze.com 2023-03-09 12:37 出处:网络
I understand that I can use $? to see the exit code of the last 开发者_开发问答executed command, but what if I want to identify whether I have thrown my own \"exit 0\" or \"exit 1\"?

I understand that I can use $? to see the exit code of the last 开发者_开发问答executed command, but what if I want to identify whether I have thrown my own "exit 0" or "exit 1"?

For example:

#!/bin/bash -e    
trap "{ echo Exit code $?; exit; }" EXIT    
exit 1

If I run this script, it prints out "Exit code 0" and then exits with exit code 1. Can I access the code in the trap, or am I just going about this the wrong way? In other words, I would like this simple script to print out "Exit code 1".


It's 0 because $? at the beginning of a script, where it is substituted due to the double quotes, is 0.

Try this instead:

trap '{ echo Exit code $?; exit; }' EXIT


Any process that terminates sets the $?, it means that it constantly will get overwritten. Save $? to a separately named var that is unique and echo that upon exit.

Edit

See Exit Shell Script Based on Process Exit Code

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号