命令说明
Trap signals and other events.
Defines and activates handlers to be run when the shell receives signals
or other conditions.
trap 可指定在接收到信号后将要采取的动作
示例
# 捕获 EXIT
trap "echo exit_ok" EXIT
# 捕获 SIGINT
trap "echo exit_2" SIGINT
# 或者
trap "echo exit_2" 2
# 删除捕获
trap -- SIGINT
trap 2
# 指定多个信号
trap "echo sigspec_many" PIPE QUIT TERM INT
#忽略信号
trap '' 2
演示
下面图片中,忽略信号2后,tail 中使用 Ctrl+C 失效。且shell中 无法输出^C。
使用stty -a 查看所有与终端相关的设定,使用 ^\ 退出 tail
[root@localhost ~]# stty -a
speed 38400 baud; rows 52; columns 114; line = 0;
intr = ^C; quit = ^\; erase = ^H; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q;
stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke
[root@localhost ~]#
产生信号
Ctrl+Z 会产生SIGTSTP信号
Ctrl+C 会产生SIGINT信号
exit 命令产生 EXIT
语法
trap [-lp] [[arg] sigspec …]
选项说明
-p 选项而没有提供arg参数则会打印所有与sigspec指定信号相关联的的trap命令;如果没有提供任何参数或者仅有-p选项,trap命令将会打印与每一个信号有关联的命令的列表;
-l 选项的作用是让shell打印一个命令名称和其相对应的编号的列表。
示例