Trap "^C" "^Z" and "^\"

Trap "^C" "^Z" and "^\"

Post by Jack McDe » Sat, 14 Apr 2001 05:28:51



Hi

Can somebody tell me how can I trap "ctrl C", "ctrl Z and "ctrl \". I am
writing a shell script which is a menu and I don't wan the user to break
from the menu and go to the command prompt.

Please help, and Thank you advance for your help.

 
 
 

Trap "^C" "^Z" and "^\"

Post by Johan J?nem » Sat, 14 Apr 2001 07:14:57




Quote:> Hi

> Can somebody tell me how can I trap "ctrl C", "ctrl Z and "ctrl \". I am
> writing a shell script which is a menu and I don't wan the user to break
> from the menu and go to the command prompt.

> Please help, and Thank you advance for your help.

Use trap!

Exampel:

trap "" SIGINT

This means do "" (nothing) when you recieve the signal interrupt (which
ought to be what ^C does). An other signal you might want to respond to is
SIGTERM. To get all the signal names you execute "kill -l" at the prompt.

Johan J?nemo

 
 
 

Trap "^C" "^Z" and "^\"

Post by Anthony Borl » Sat, 14 Apr 2001 07:29:39



Quote:> Hi

> Can somebody tell me how can I trap "ctrl C", "ctrl Z and "ctrl \". I am
> writing a shell script which is a menu and I don't wan the user to break
> from the menu and go to the command prompt.

Jack,

In a shell script you don't 'trap' keystrokes, as such, but the 'signals'
that the system issues when such events as the typing of the ctrl-C
combination occur.

To trap such signals, use the 'trap' command. The usual approach is to
specify the signal you wish to have trapped, and assign a series of commands
or a shell function that you wish executed when the trap occurs.

Simple example:

#!/bin/sh

# Function to be invoked on trap
handleCtrlC()
{
  echo "Ctrl-C pressed"
  exit 1

Quote:}

# Set trap for Ctrl-C (SIGINT)
trap "handleCtrlC" 2

# Rest of script
...
...

Refer to 'man 7 signal' for more information on the various signals. Note
that you can also set the shell to ignore certain signals by assigning a
null string; for example:

     trap "" 1 2 15

will ensure the specified signals are not handled by the script, and are,
effectively, ignored.

I hope this helps.