代码:
[root@localhost shell]# cat signal_catch.sh
#!/bin/bash
#
net=122.207.210
FILE=`mktemp /media/test.XXXXXX`
clear() {
echo "quit........"
exit 1
}
trap 'clear' INT
for i in {9..16}
do
if ping -c 1 -W 1 $net.$i &> /dev/null
then
echo "$net.$i is up....." |tee >> $FILE
else
echo "$net.$i is down..."
fi
done
结果:
[root@localhost shell]# ./signal_catch.sh
122.207.210.9 is down...
122.207.210.10 is down...
122.207.210.11 is down...
122.207.210.13 is down...
122.207.210.14 is down...
^Cquit........
此时/media/test.XXXXXX文件内容(只有一台主机在线.....)
[root@localhost media]# ll
total 4
-rw------- 1 root root 26 Jul 23 04:49 test.R15GTV
[root@localhost media]# cat test.R15GTV
122.207.210.12 is up.....
这时我们虽然终止了脚本的进行,但是临时文件还在,可以改一下脚本使得在脚本退出时删除临时文件
此时/media目录下没有任何文件
[root@localhost media]# ll
total 0
[root@localhost media]#
代码:
[root@localhost shell]# cat signal_catch.sh
#!/bin/bash
#
net=122.207.210
FILE=`mktemp /media/test.XXXXXX`
clear() {
echo "quit........"
rm -rf $FILE #想让脚退出时执行哪些命令都可以写在这个函数中
exit 1
}
trap 'clear' INT
for i in {9..16}
do
if ping -c 1 -W 1 $net.$i &> /dev/null
then
echo "$net.$i is up....." |tee >> $FILE
else
echo "$net.$i is down..."
fi
done
结果:
[root@localhost shell]# ./signal_catch.sh
122.207.210.9 is down...
122.207.210.10 is down...
122.207.210.11 is down...
122.207.210.13 is down...
^Cquit........
此时
/media目录下
[root@localhost media]# ll
total 0
[root@localhost media]#
阅读(565) | 评论(0) | 转发(0) |