tso
tso

Reputation: 307

Delete file after script terminated

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

Answers (3)

y.kashyap007
y.kashyap007

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

chepner
chepner

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

Daniel Smith
Daniel Smith

Reputation: 1034

You want ctrl-c trapping for post script cleanup.

https://rimuhosting.com/knowledgebase/linux/misc/trapping-ctrl-c-in-bash

Upvotes: 0

Related Questions