1753770 Members
4778 Online
108799 Solutions
New Discussion юеВ

trapping control C

 
Praveen Bezawada
Respected Contributor

trapping control C

Hi
Can we trap control C in a shell script and exit gracefully ???
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor

Re: trapping control C

Hi,

Yes, try this:

trap "echo intr detected; exit 2" 2

echo "Begin"
echo "Enter Value 1: \c"
read V1
echo "Enter Value 2: \c"
read V2
echo "End"
exit 0

I assume that you have set intterupt to cntl-c.
If at any time, you press ctrl-c the trap is executed - unless the parent process is set to ignore interrupts.

If for example you might create temp files in your script, you should also add rm -f $tfile1 $tfile2 (e.g.) to your trap statement.

This should get you started, Clay
If it ain't broke, I can fix that.
federico_3
Honored Contributor

Re: trapping control C


i'd do like this:

trap "echo ^C captured ; exit " 2

Carlos Fernandez Riera
Honored Contributor

Re: trapping control C

Instead to write a funtion in trap stament ( rm xxx; echo ....; exit ...) you can write a function and call it inside trap.

Also, read sh ( man ksh, sh_posix ..) for exceptions.
unsupported