如何让`trap`知道退出是在程序成功完成之后还是因为错误或其他原因过早

som*_*ing 5 shell-script trap exit-status

问题:

我有一个我一直在编写的 shell 程序,但我不知道如何确保它trap在最后或由于某些命令中的错误而被清除,无论哪种方式都会被清除。

这是代码:

################################### Successful exit then this cleanup ###########################################################3

successfulExit()
{
    IFS=$IFS_OLD
    cd "$HOME" || { echo "cd $HOME failed"; exit 155; }
    rm -rf /tmp/svaka || { echo "Failed to remove the install directory!!!!!!!!"; exit 155; }
}
###############################################################################################################################33
####### Catch the program on successful exit and cleanup
trap successfulExit EXIT
Run Code Online (Sandbox Code Playgroud)

题:

我怎样才能traptrap EXIT在程序完成时制作?

这是完整的脚本:

debianConfigAwsome.5.3.sh

Gil*_*il' 8

在进入EXIT陷阱时,$?包含退出状态。这与您$?在另一个 shell 中调用此脚本后找到的值相同:传递给的参数exit(截断到范围 0–255)或前面命令的返回状态。在由于 退出的情况下set -e,触发隐式exit.

通常您应该$?以相同的状态再次保存并退出。

cleanup () {
  if [ -n "$1" ]; then
    echo "Aborted by $1"
  elif [ $status -ne 0 ]; then
    echo "Failure (status $status)"
  else
    echo "Success"
  fi
}
trap 'status=$?; cleanup; exit $status' EXIT
trap 'trap - HUP; cleanup SIGHUP; kill -HUP $$' HUP
trap 'trap - INT; cleanup SIGINT; kill -INT $$' INT
trap 'trap - TERM; cleanup SIGTERM; kill -TERM $$' TERM
Run Code Online (Sandbox Code Playgroud)