函数语法案例1

一、rsync启停脚本(函数)

  1. 脚本
  • cat /server/scripts/b6.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/sh
# chkconfig: 2345 20 80
# description:rsyncd start up scripts by noah.
. /etc/init.d/functions
function usage () {
echo $"usage:$0{start|stop|restart}"
exit 1
}
function start () {
rsync --daemon
sleep 1
if [ `netstat -lntup|grep rsync|wc -l` -ge 1 ]
then
action "rsyncd is started." /bin/true
else
action "rsyncd is started." /bin/false
fi
}
function stop () {
pkill rsync &>/dev/null
sleep 2
if [ `netstat -lntup|grep rsync|wc -l` -eq 0 ]
then
action "rsyncd is stopped." /bin/true
else
action "rsyncd is stopped." /bin/false
fi
}
function main () {
if [ $# -ne 1 ]
then
usage
fi
if [ "$1" = "start" ]
then
start
elif [ "$1" = "stop" ]
then
stop
elif [ "$1" = "restart" ]
then
stop
sleep 2
start
else
usage
fi
}
main $*
  1. 执行结果:
  • sh /server/scripts/b6.sh stop
    rsyncd is stopped. [确定]
  • sh /server/scripts/b6.sh start
    Failed to parse config file: /etc/rsyncd.conf
    rsyncd is started. [失败]

函数语法案例2

一、函数传参测试网址异常

1. 基本实现

  1. 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cat /server/scripts/b5.sh
#!/bin/bash
function usage () {
echo "usage:$0 input one url"
exit 1
}
#错误提示函数
function check_url () {
wget --spider -q -o /dev/null --tries=1 -T 5 $1
if [ $? -eq 0 ]
then
echo "$1 is yes."
else
echo "$1 is no."
fi
}
#url测试函数,注意$1
function main () {
if [ $# -ne 1 ]
then
usage
fi
check_url $1
}
#主函数,先判断参数个数,不符合要求调用错误提示函数提示,符合要求的话,调用check_url函数并把$1传递给函数
main $*
#这是将命令行接受到的所有参数,作为函数参数传递给函数内部的一种常用手法
  1. 执行情况

2. 改为命令行传参

  1. 脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cat /server/scripts/b5.sh
#!/bin/bash
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit 1
function usage () {
echo "usage:$0 input one url"
exit 1
}
function check_url () {
wget --spider -q -o /dev/null --tries=1 -T 5 $1
if [ $? -eq 0 ]
then
action "$1 is yes." /bin/true
else
action "$1 is no." /bin/false
fi
}
function main () {
if [ $# -ne 1 ]
then
usage
fi
check_url $1
}
main $*
  1. 执行结果