您可以在陷阱中访问退出命令的代码吗? [英] Can you access the code of an exit command in a trap?
问题描述
我知道我可以使用$?来查看最后执行的命令的退出代码,但是如果我想确定自己抛出了自己的退出0"还是退出1"怎么办?
例如:
#!/bin/bash -e陷阱"{echo退出代码$ ?;退出;}"退出1号出口
如果运行此脚本,它将打印出退出代码0",然后以退出代码1退出.我可以访问陷阱中的代码吗,还是我使用错误的方法?换句话说,我希望这个简单的脚本打印出退出代码1".
为0,因为脚本开头的 $?
(由于双引号而被替换)为0./p>
尝试以下方法:
trap'{echo退出代码$ ?;出口;}' 出口
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
这篇关于您可以在陷阱中访问退出命令的代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!