shell中trap的作用

信号

linux通过信号来在运行在系统上的进程之间通信也可以通过信号来控制shell脚本的运行
(1)捕捉信号:trap命令
常用信号 ctrl+c(终止进程) ctrl+z(暂停进程,打入后台)

[root@server ~]# trap "echo westos" 2
[root@server ~]# ^Cwestos

(2)信号屏蔽

[root@server ~]# trap "" 2	##信号屏蔽
[root@server ~]# trap : 2	##恢复信号

(3)脚本形式:

#!/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"

练习:

执行脚本时,使用ctrl+c可以将/tmp/westos下建立的文件都删除掉

#!/bin/bash

trap "find /tmp -type f -name "westos_*" | xargs rm -f && exit " 2

while true
do
    touch /tmp/westos_$(date +%F-%N-%M-%S)
    sleep 2
    ls -l /tmp/westos*
done

猜你喜欢

转载自blog.csdn.net/gordzafkiel/article/details/87229179
今日推荐