Trap allows you to capture signals in the script. The common form of this command is:
Trap name signal (s)
Among them, name is a sequence of operations taken after the captured signal. In real life, name is generally a function specifically used to process the captured signal. Name must be enclosed in double quotation marks. signal is the signal to be captured.
The script usually takes some action after capturing a signal. The most common actions include:
1) Clear temporary files
2) Ignore this signal
3) Ask the user whether to terminate the script.
Common signals include 1, 2, 3, and 15.
1----sighup suspended or the parent process is killed
2----sigint: keyboard interrupt <Ctrl + C>
3----sigquit: Exit from the keyboard
15----sigterm soft termination
Instance: trap. Sh
#! /Bin/sh
Trap "my_exit" 1 2 3 15
Loop = 0
Hold1 =/tmp/hold1. $
Hold2 =/tmp/hold2. $
My_exit ()
{
Echo-e "\ nreceived interrupt ..."
Echo "do you wish to really exit ?? "
Echo "Y: Yes"
Echo "N: No"
Echo-n "your choice [y .. n]>"
Read ans
Case $ ans in
Y | Y) Exit 1 ;;
N | N );;
Esac
}
Echo-n "enter your name :"
Read name
Echo-n "Enter your age :"
Read age
After the script captures the signal 2, it will provide you with a choice to ask whether the user really wants to exit.