How to make `trap` know if the EXIT is after successful program finish or because of premature as an error or something Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to make `trap` know if the EXIT is after successful program finish or because of premature as an error or something without wasting too much if your time.

The question is published on by Tutorial Guruji team.

PROBLEM:

I have a shell program that I have been writing but I can’t find out how to make sure that trap is trapping for cleanup at the end or because of a error in some command, it cleans up either way.

Here is the code:

################################### 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

QUESTION:

How can I make trap only trap EXIT on program finish?

Here is the full script:

debianConfigAwsome.5.3.sh

Answer

On entry to the EXIT trap, $? contains the exit status. That’s the same value you’d find as $? after calling this script in another shell: either the argument passed to exit (truncated to the range 0–255) or the return status of the preceding command. In the case of an exit due to set -e, it’s the return status of the command that triggered the implicit exit.

Usually you should save $? and exit again with the same status.

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
We are here to answer your question about How to make `trap` know if the EXIT is after successful program finish or because of premature as an error or something - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji