shell 编程-函数
function (功能) 功能函数
完成特定功能的代码片段
函数必须先定义才能使用
优点:避免重复的代码
定义函数
调用函数
取消函数
函数传参
命名空间
local
返回值
return value
value不能超过0-255
shell 函数function
函数声明
function_name () {
list of commands
}
函数名 function_name,这就是你将使用它从其他地方在你的脚本调用。
取消函数
unset myfunc //取消函数
myfunc() //函数定义
{
echo “This is my first shell function”
}
myfunc //函数调用
产生以下执行结果
./test.sh
This is my first shell function
函数必须提前定义测试
[root@newrain fun]# cat fun05.sh
#!/bin/bash
fun () {
echo "hello"
}
fun
unset fun
fun
[root@newrain fun]# bash fun05.sh
hello
fun05.sh: line 8: fun: command not found
函数的返回值,返回的是函数体内最后一条命令是否成功的返回值
[root@newrain fun]# systemctl stop httpd
[root@newrain fun]# cat fun03.sh
#!/bin/bash
fun() {
systemctl status httpd &>/dev/null
systemctl status vsftpd &>/dev/null
}
fun
echo $?
[root@newrain fun]# systemctl stop vsftpd
[root@newrain fun]# bash fun03.sh
3
函数传参 在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $¥n 的形式来获取参数的值,例如,$1表示第一个参 数,$2表示第二个参数
示例
[root@newrain fun]# cat fun06.sh
#!/bin/bash
if [ ! $# -eq 3 ];then
echo "Must Input Three number: " p1 p2 p3
exit
fi
fun() {
echo $[$1*$2*$3]
}
fun 1 2 3 这个时候只是传参到了脚本,并没有传到函数里面
[root@newrain fun]# bash fun06.sh 1 3 4 6
修改版:
[root@newrain fun]# cat fun06.sh
#!/bin/bash
if [ ! $# -eq 3 ];then
echo "Must Input Three number: " p1 p2 p3
exit fi
fun() {
echo $[$1*$2*$3]
}
fun $1 $2 $3