Chinaunix首页 | 论坛 | 博客
  • 博客访问: 631028
  • 博文数量: 244
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 130
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-27 09:53
个人简介

记录学习,记录成长

文章分类

全部博文(244)

我的朋友

分类: LINUX

2015-07-21 16:57:46

这个脚本用到了函数,所以用几种方法实现:

1.功能在函数体中实现,主函数中调用该函数
代码:
[root@localhost ping_shell]# cat ping_1.sh 
#!/bin/bash
# simple ping shell
PING() {
        for i in {10..16}
        do
        if ping -c 1 -W 1 122.207.210.$i &> /dev/null      #用-c和-W选项是为了不让脚本等待很长时间,并且不让ping的结果输出到屏幕
        then
                echo "122.207.210.$i is up..."
        else
                echo "122.207.210.$i is down..."
        fi
        done
}

PING

结果:
[root@localhost ping_shell]# ./ping_1.sh 
122.207.210.10 is down...
122.207.210.11 is down...
122.207.210.12 is up...
122.207.210.13 is down...
122.207.210.14 is down...
122.207.210.15 is down...
122.207.210.16 is down...

2.函数体接受参数并打印信息,主函数中多次调用函数实现功能
代码:
[root@localhost ping_shell]# vim ping_2.sh 
#!/bin/bash
# simple ping shell
PING() {
        if ping -c 1 -W 1 $1 &> /dev/null
        then
                echo "$1 is up....."
        else
                echo "$1 is down..."
        fi
}
for i in {10..15}
do
PING 122.207.210.$i
done
结果:
[root@localhost ping_shell]# ./ping_2.sh 
122.207.210.10 is down...
122.207.210.11 is down...
122.207.210.12 is up.....
122.207.210.13 is down...
122.207.210.14 is down...
122.207.210.15 is down...

3.函数体接受参数且只有该函数的状态返回值,主函数中实现Ping功能
代码:
[root@localhost ping_shell]# cat ping_3.sh 
#!/bin/bash
# simple ping shell
PING() {
        if ping -c 1 -W 1 $1 &> /dev/null
        then
                return 0
        else
                return 1
        fi
}
for i in {10..15}
do
if PING 122.207.210.$i        #这里将参数传递给函数执行后返回执行状态结果(0|1),if语句接受该状态信息,为1则up,否则down
then
        echo "122.207.210.$i is up..."
else
        echo "122.207.210.$i is down..."
fi
done
结果:
[root@localhost ping_shell]# ./ping_3.sh 
122.207.210.10 is down...
122.207.210.11 is down...
122.207.210.12 is up...
122.207.210.13 is down...
122.207.210.14 is down...
122.207.210.15 is down...


如果是ping122.207.x.y这个网段的在线主机可以使这样:
代码:
[root@localhost ping_shell]# cat ping_4.sh 
#!/bin/bash
#
PING() {
        if ping -c 1 -W 1 $1 &>/dev/null
        then 
                return 0
        else
                return 1
        fi
}

for i in 210 211
do
  for j in 10 11 12
  do
        if PING 122.207.$i.$j
        then
                echo "122.207.$i.$j id up....."
        else
                echo "122.207.$i.$j is down..."
        fi
  done
done

结果:
[root@localhost ping_shell]# ./ping_4.sh 
122.207.210.10 is down...
122.207.210.11 is down...
122.207.210.12 id up.....
122.207.211.10 is down...
122.207.211.11 is down...
122.207.211.12 is down...

阅读(1057) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~