1.查看信号
2.捕捉信号
[root@localhost mnt]# trap "echo hello" 2 编辑按Ctrl+C时输出hello
[root@localhost mnt]# ^Chello
3.屏蔽信号
[root@localhost mnt]# trap "" 2
[root@localhost mnt]# trap : 2
[root@localhost mnt]# ^C
4.脚本捕捉信号
[root@localhost mnt]# cat trap_01.sh
#!/bin/bash
trap "echo 'Sorry!I have trapped Ctrl+C'" 2
echo "This is a test script~"
count=1
while [ $count -le 10 ]
do
echo "Loop #$count"
sleep 2
count=$[ $count + 1 ]
done
echo "This is the end of the script~"
trap - 2
echo "I just removed the trap"
脚本捕捉信号
#!/bin/bash
trap "echo ByeBye~" EXIT
count=1
while [ $count -le 5 ]
do
echo "Loop #$count"
sleep 2
count=$[ $count + 1 ]
done
练习:按Ctrl+C将/tmp//westos目录下文件全部删除
[root@localhost mnt]# cat trap_02.sh
#!/bin/bash
trap "find /tmp/westos -type f -name "westos_*" | xargs rm -f && exit" 2
while true
do
touch /tmp/westos/westos_$(date +%F-%N-%M-%S)
sleep 2
ls -l /tmp/westos/westos*
done