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