Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I'm trying to write an exit routine for ksh script which ideally should capture the user input "control c" and then exit the script gracefully.
Any ideas and suggestions ?
Thanks,

If a script is at a certain critical stage where a user cancel might leave things in a bad state, the script will want to disable the user cancel request for this portion of the script. Also, I have some scripts that make use of temporary files. If the user cancels, I do honor the cancel request, but I intercept it so that I can do some house cleaning first.
You can define what you want to happen when a certain signal is detected via the trap command. The trap command watches for a certain signal, not a certain key. Signal 2 is interrupt signal, usually mapped to Ctrl-C. If the trap code does not exit, the script will continue its execution after the trap executes. Run the following script and try to cancel it:
#!/bin/ksh
trap 'echo Ouch' 2
sleep 3
sleep 3
sleep 3
sleep 3
sleep 3
sleep 3
exit 0Following is a signal 2 trap that does some stuff and then exits. Just for testing, it exits with status code 3, but could be zero or whatever:
trap 'echo "You pressed interrupt key";\
echo "doing some cleanup";\
exit 3' 2

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |