假设我有两个脚本只打印一个无用的下标中的返回码:
SCRIPT1
(echo; exit 0)
echo $?
SCRIPT2
(echo)
echo $?
两者都回馈0
。但有没有办法告诉第一个下标明确使用exit
命令?
答案 0 :(得分:1)
exit_handler
,只需检查最后一个命令就可以判断是否有退出呼叫。
#! /bin/bash
exit_handler () {
ret=$?
if echo "$BASH_COMMAND" | grep -e "^exit " >> /dev/null
then
echo "it was an explicit exit"
else
echo "it was an implicit exit"
fi
exit $ret
}
trap "exit_handler" EXIT
exit 22
这将打印
it was an explicit exit
现在为了告诉父母,而不是回应,我们宁可写入文件,命名管道等等。
根据choroba的注意,没有参数的exit
将给出implicit call
,这是不可能的,因为exit
(没有参数)与exit $?
相同。因此,正则表达式必须考虑到这一点:
#! /bin/bash
exit_handler () {
ret=$?
if echo "$BASH_COMMAND" | grep -e "^exit \|^exit$" >> /dev/null
then
echo "it was an explicit exit"
else
echo "it was an implicit exit"
fi
exit $ret
}
trap "exit_handler" EXIT
exit 22