快速的ping网络中存活的主机,该脚本有并行执行的特点,能够在后台快速完成网络主机的检查。
#!/bin/bash # # for ip in 192.168.1.{1..255} ; do ( ping $ip -c 2 &>/dev/null ; if [ $? -eq 0 ]; then echo $ip is alived fi )& done wait
如果要出事255个地址,ping每一个IP的主机都有一个延迟,所以采用并行方式来加速ping命令的执行。将循环体放入到()&.命令块放入(),使其中的命令可作为子shell来执行,而&可以使之脱离当前线程,在后台继续运行。
for循环执行多个后台进程,然后结束循环并终止脚本。等所有子进程结束后在终止脚本,我们的使用过wait命令。将wait命令放在脚本的最后,他就会一直等到所有的子进程全部结束,
wait命令使用脚本只有在所有子进程或者后台进程全部终止或完成之后才能结束。
执行后的结果类似如下:
[root@localhost tmp]# ./ping 192.168.1.4 is alived 192.168.1.1 is alived 192.168.1.6 is alived 192.168.1.10 is alived 192.168.1.12 is alived 192.168.1.15 is alived 192.168.1.16 is alived 192.168.1.30 is alived 192.168.1.28 is alived 192.168.1.32 is alived 192.168.1.33 is alived 192.168.1.50 is alived 192.168.1.51 is alived 192.168.1.52 is alived 192.168.1.124 is alived 192.168.1.131 is alived 192.168.1.22 is alived 192.168.1.39 is alived
原文地址:http://bronte.blog.51cto.com/2418552/1433400