In Linux, the Trap command is used primarily to receive signals and act, signals are sent asynchronously to a program's event, by default, a program can be terminated, and the Trap command prototype is as follows:
Trap command Signal
Signal is the signal received, the command is received by the signal to take action. The following are two simple signals.
Signal
Description
INT (2)
Ctrl + C
QUIT (3)
Ctrl + \
The sample code is as follows
[Root@localhost shell]# cat-n trap.sh
1 #!/bin/bash
2 trap ' echo ' sorry! I Habe Trapped Ctrl + C "SIGINT sigterm
3 echo This are a test program
4 count=1 5 while [$coun T-le]
6 do
7 echo "LOOP # $count" 8 sleep 5
9 count=$[$count + 1]
10< C23/>done echo This is the " test program
[root@localhost shell]#
Run-Time CTRL + C results as shown in figure:
[Root@localhost shell]#./trap.sh This are
a test program
loop #1
loop #2
^csorry! I Habe Trapped Ctrl + C
loop #3
loop #4
^csorry! I Habe Trapped Ctrl + C
loop #5
loop #6 loop
#7
loop #8
^csorry! I Habe Trapped Ctrl + C loop #9 Loop #10 This is the "the"
test program
[root@localhost shell]#
If you want to capture the exit of the shell script, just add the exit signal to the trap command, and the code is as follows:
[Root@localhost shell]# cat-n trap.sh
1 #!/bin/bash
2 trap ' echo ' sorry! I Habe Trapped Ctrl + C "" SIGINT sigterm
3 trap "echo Goodbye" EXIT
4 echo This are a test program
5 count=1
6 while [$count-le]
7 does
8 echo "LOOP # $count" 9 Sleep 5< c35/>10 count=$[$count + 1] One by one the echo this is the "the"
test program
[Root@loca Lhost shell]#
The results of the operation are as follows:
[Root@localhost shell]#./trap.sh This are
a test program
LOOP #1
^csorry! I Habe Trapped Ctrl + C
LOOP #2
^csorry! I Habe Trapped Ctrl + C
LOOP #3
^csorry! I Habe Trapped Ctrl + C
loop #4
loop #5
loop #6
^csorry! I Habe Trapped Ctrl + C
LOOP #7
^csorry! I Habe Trapped Ctrl + C
loop #8
loop #9 Loop #10 This was the end of the "
test program
Goodbye
[ Root@localhost shell]#
You can also remove the capture in the shell, as follows:
[Root@localhost shell]# cat-n trap.sh
1 #!/bin/bash
2 trap ' echo ' sorry! I Habe Trapped Ctrl + C "" SIGINT sigterm
3 trap "echo Goodbye" EXIT
4 echo This are a test program
5 count=1
6 while [$count-le]
7 does
8 echo "LOOP # $count" 9 Sleep 1< C38/>10 count=$[$count + 1] One by one the echo this is the "the" test program TR Ap-exit echo " I just remove EXIT trap"
The exit capture is removed before the program ends, and the goodbye is eventually not exported:
[Root@localhost shell]#./trap.sh This are
a test program
loop #1
loop #2
loop #3
loop #4
Loop #5 C6/>loop #6
loop #7 loop
#8
loop #9 Loop #10 This is the "end of" the
test program
I just remove EXIT trap
[Root@localhost shell]#