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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值