BASH:如何判断脚本是否使用退出?

时间:2014-09-04 18:00:18

标签: bash return-value exit difference subscript

假设我有两个脚本只打印一个无用的下标中的返回码:

SCRIPT1

(echo; exit 0)
echo $?

SCRIPT2

(echo)
echo $?

两者都回馈0。但有没有办法告诉第一个下标明确使用exit命令?

1 个答案:

答案 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