版权声明:本文为博主原创文章,转载请指明地址。 https://blog.csdn.net/Mr_rsq/article/details/82178712
目录
1 函数的具体功能
简单地说,函数的作用就是把程序里多次调用相同的代码部分定义成一份,然后为这份代码起个名字,其它所有的重复调用这部分代码就都只调用这个名字就可以了。当需要修改这部分重复代码时,只需要改变函数体内的一份代码即可实现所有调用修改。
使用函数的优势:
- 把相同的程序段定义成函数,可以减少整个程序的代码量。
- 可以让程序代码结构更清晰。
- 增加程序的可读、易读性,以及可管理性。
- 可以实现程序功能模块化,不同的程序使用函数模块化。
强调:对于shell来说,linux系统的2000个命令都可以说是shell的函数。
2 Shell函数语法
语法格式:
# 简单语法格式:
函数名() {
指令...
return n
}
# 规范语法格式:
function 函数名() {
指令...
return n
}
# shell是exit输出的返回值,函数里用的是return输出返回值。
3 Shell函数的执行
1. 直接执行函数名即调用(不带括号
)
函数名
注意:
a、执行函数时,函数后的小括号不用带
b、函数定义及函数体必须在要执行的函数名的前面定义,shell的执行从上到下按行执行的。
2.带参数的函数执行方法:
函数名
参数1
参数2
提示:函数的传参和脚本的传参类似,只是脚本名换成函数名即可。
【函数后接的参数说明】
- shell的位置参数(
$1
、$2
、$3
、$4
、$5
、$#
、$*
、$?
以及$@
)都可以是函数的参数 - 此时父脚本的参数临时地被函数参数所掩盖或隐藏。
- $0比较特殊,它仍然是父脚本的名称。
- 当函数完成时,原来的命令行脚本的参数即恢复。
- 在shell函数里面,return 命令功能与shell里的exit类似,作用是跳出函数。
- 在shell函数体里使用exit会退出整个shell脚本,而不是退出shell函数。
- return语句会返回一个退出值(返回值)给调用函数的程序。
- 函数的参数变量是在函数体里面定义,如果是普通变量一般会使用local i定义。
【例子】
# 简单函数
[root@RSQ scripts]# cat func.sh
#!/bin/bash
test1() {
echo "This is test."
}
test1
[root@RSQ scripts]# bash func.sh
This is test.
# 把函数放在/etc/init.d/functions文件中并调用
[root@RSQ scripts]# tail -3 /etc/init.d/functions
test1() {
echo "This is test."
}
[root@RSQ scripts]# cat func.sh
#!/bin/bash
. /etc/init.d/functions
test1
[root@RSQ scripts]# bash func.sh
This is test.
# 函数传参
[root@RSQ scripts]# tail -3 /etc/init.d/functions
test1() {
echo "This is $1."
}
[root@RSQ scripts]# cat func.sh
#!/bin/bash
. /etc/init.d/functions
test1 RSQ
[root@RSQ scripts]# bash func.sh
This is RSQ.
[root@RSQ scripts]# cat func.sh
#!/bin/bash
. /etc/init.d/functions
test1 $1
[root@RSQ scripts]# bash func.sh TEST
This is TEST.
4 实例
函数传参转换成脚本命令行传参,对任意指定的URL判断是否异常。
分步分析:
- 脚本传参检查web url是否正常
- 检查的功能写成函数
- 函数传参转换成脚本命令行传参,对任意指定URL判断是否异常。
【解答】
[root@RSQ scripts]# cat check_url.sh
#!/bin/bash
[ -f /etc/init.d/functions ]&& . /etc/init.d/functions
RETVAL=0
usage() {
echo "USAGE: $0 url"
exit 1
}
CheckUrl() {
wget -T 10 --spider -t 2 $1 &>/dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
action "$1 url" /bin/true
else
action "$1 url" /bin/false
fi
return $RETVAL
}
main() {
if [ $# -ne 1 ]; then
usage
fi
CheckUrl $1
RETVAL=$?
return $RETVAL
}
main $*
#curl_check
#CheckUrl() {
# RETVAL="`curl -I $1 |awk 'NR==1{print $2}'`"
# if [ $RETVAL -eq "200" -o $RETVAL -eq "301" -o $RETVAL -eq "302" ]; then
# echo "Return $RETVAL. Curl URL succesed."
# exit 0
# fi
# echo "Return $RETVAL. Curl URL failed."
# return 2
#}
[root@RSQ scripts]# bash check_url.sh www.baidu.com
www.baidu.com url [ OK ]
[root@RSQ scripts]# bash check_url.sh www.baidu.comdddd
www.baidu.comdddd url [FAILED]
[root@RSQ scripts]# bash check_url.sh www.baidu.com dddd
USAGE: check_url.sh url