Forcing cleanup code in shell scripts?

nmeyers at javalinux.net nmeyers at javalinux.net
Thu Nov 3 12:50:07 EST 2005


On Thu, Nov 03, 2005 at 12:43:27PM -0500, Josh ChaitinPollak wrote:
> Is it possible to trap Ctrl-C and run some cleanup code in a shell  
> script? How would I do that?

#!/bin/bash

trap "echo hello world; exit" 2 3 15

... rest of your script ...



If any of the common kill signals shows up (2 = ctrl-c/interrupt, 3 =
quit, 15 = terminate), the script will execute the code between the
quotes. In your case, you probably want to call another script rather
than echoing "hello world" to the console :-).

Nathan

> 
> I've got this shell script for setting up a gentoo embedded  
> environment, and it mounts a few directories, then chroots. If it  
> runs successfully, it umounts when done, but if it fails, it doesn't  
> run the umounts. Then I fix whatever bug it was that caused it to  
> fail, and rm -rf that directory to start again from scratch. And that  
> deletes my /usr/portage tree, and I get pissed and waste time.
> 
> Any ideas?
> 
> _______________________________________________
> Discuss mailing list
> Discuss at blu.org
> http://olduvai.blu.org/mailman/listinfo/discuss
> 



More information about the Discuss mailing list