Shell函数
本篇内容如下:
- Shell函数的定义方法
- Shell函数的执行方法
函数写法
标准写法:
function 函数名(){
指令...
return n
}
简化写法:
function 函数名{
指令...
return n
}
简化写法:
函数名(){
指令...
return n
}
函数执行
Shell的函数分为最基本的函数和可以传参的函数两种,其执行方式分别说明如下。
-
执行不带参数的函数时,直接输入函数名即可(注意不带小括号)
- 在Shell函数里面,return命令的功能与exit类似,return的作用是退出函数,而exit是退出脚本文件。
- return语句会返回一个退出值(即返回值)给调用函数的当前程序,而exit会返回一个退出值(即返回值)给执行程序的当前Shell。
- 如果将函数存放在独立的文件中,被脚本加载使用时,需要使用source或“. ”来加载。
- 在函数内一般使用local定义局部变量,这些变量离开函数后就会消失。
-
带参数的函数执行方法,格式如下
函数名 参数1 参数2
- Shell的位置参数($1、 2 … 、 ‘ 2…、` 2…、‘#
、
∗ ‘ 、 ‘ *`、` ∗‘、‘?及
$@`)都可以作为函数的参数来使用。 - 此时父脚本的参数临时地被函数参数所掩盖或隐藏
$0
比较特殊,它仍然是父脚本的名称- 当函数执行完成时,原来的命令行脚本的参数即可恢复。
- 函数的参数变量是在函数体里面定义的
- Shell的位置参数($1、 2 … 、 ‘ 2…、` 2…、‘#
实践
一个简单的函数
[root@localhost shell]# cat 8_1.sh
#!/bin/bash
#***********************************************
#Author: luotianhao
#Mail: tianhao.luo@hand-china.com
#Version: 1.0
#Date: 2021-03-10
#FileName: 8_1.sh
#Description: This is a test script.
#***********************************************
oldboy(){
echo "i am oldboy"
}
function oldgirl(){
echo "i am oldgirl"
}
oldboy
oldgirl
[root@localhost shell]# sh 8_1.sh
i am oldboy
i am oldgirl
URL检测脚本:
将函数的传参转换成脚本文件命令行传参,判断任意指定的URL是否存在异常。
1.实现脚本传参,检查url是否正常
[root@localhost shell]# cat 8_5.sh
#!/bin/bash
#***********************************************
#Author: luotianhao
#Mail: tianhao.luo@hand-china.com
#Version: 1.0
#Date: 2021-03-10
#FileName: 8_5.sh
#Description: This is a test script.
#***********************************************
if [ $# -ne 1 ]
then
echo $"usage:$0 url"
exit 1;
fi
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
2.将上述检测的功能写成函数,并将函数传参转换成脚本命令行传参,判断任意指定的URL是否存在异常。
[root@localhost shell]# cat 8_5_1.sh
#!/bin/bash
#***********************************************
#Author: luotianhao
#Mail: tianhao.luo@hand-china.com
#Version: 1.0
#Date: 2021-03-10
#FileName: 8_5_1.sh
#Description: This is a test script.
#***********************************************
function usage(){
echo $"usage:$0 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
}
function main(){
if [ $# -ne 1 ]
then
usage
fi
check_url $1
}
#<===这里的$*就是吧命令行接收的所有参数作为函数参数传给函数内部
main $*
[root@localhost shell]# sh 8_5_1.sh www.baidu.com
www.baidu.com is no
[root@localhost shell]# sh 8_5_1.sh
usage:8_5_1.sh url
[root@localhost shell]#