信号捕捉

trap 信号捕捉

trap用法:trap 'echo ' signal
/bin/bash
trap 'echo "haha  I am still here"' INT
read A

当按下ctrl+c的时候会出现脚本的定义输出的信息
2、
trap 'echo "quit the script";exit 1' INT
read A
捕捉信号后输出echo quit..然后退出





赋值,当捕捉到信号时清楚赋值的内容
/bin/bash
var1=3
var2=4

trap 'unset var1 var2;echo "haha  I am still here"' INT
read A


创建文件夹,当捕捉到信号删除创建的文件夹,然后输出信息
/bin/bash
touch /tmp/traptest
trap 'rm /tmp/traptest &>/dev/null;echo 

"haha  I am still here"' INT
read A


调用函数,捕捉信号
/bin/bash
touch /tmp/traptest
mytrap() {
rm -rvf /tmp/traptest &>/dev/null
echo "quid the script..."
exit 1

trap 'mytrap' INT
read A


捕捉ping
/bin/bash
trap ‘echo "Quit..."; exit 1' SIG
for i in {1..254};do
ping -c1 -W1 192.168.0.$i &>/dev/null
[ $? -eq 0 ] echo "this station is online" || echo "this is offline"
done

执行脚本,当按下ctrl+c ping就立即结束!

你可能感兴趣的:(职场,trap,休闲,信号捕捉)