Reputation: 307
I was asking myself if it is possible that when I terminate a bash script with crtl+c, the script would execute a last command before aborting, like delete a file which was created by that script?
Upvotes: 4
Views: 3868
Reputation: 11
You can first trap ctrl+c by :
trap ctrl_c INT
This line will call a function ctrl_c
after pressing ctrl+c(stopping the execution of the script).
Then make a function ctrl_c
and delete the files which you want to delete inside that function like this:
function ctrl_c(){
rm -rf ~/PATH-OF-THE-FILE-TO-DELETE
}
Upvotes: 0
Reputation: 531265
You can trap the pseudo-signal EXIT
to execute something before exiting for any reason:
trap 'rm myfile' EXIT
or trap INT
to excecute a command on before exiting due to Control-C:
trap 'rm myfile' INT
Upvotes: 4
Reputation: 1034
You want ctrl-c trapping for post script cleanup.
https://rimuhosting.com/knowledgebase/linux/misc/trapping-ctrl-c-in-bash
Upvotes: 0