来源:https://coding.m.imooc.com/classindex.html?cid=314
1.函数返回值
shell函数返回值分为两种
return: return 只能返回0~255整数,0表示函数运行成功,非0表示函数运行失败,返回函数状态码
echo: echo 作为函数的返回值
代码:
#!/bin/bash
#
#得到到运行当前脚本的进程id
this_pid=$$
function is_nginx_run
{
ps -ef | grep nginx | grep -v grep | grep -v $this_pid &> /dev/null
if [ $? -eq 0 ];then
return
else
return 1;
fi
}
is_nginx_run && echo "Nginx is running......" || echo "Nginx is down"
2.函数中变量的作用域
在shell中若不做声明都为全局变量
#!/bin/bash
#shell中若不声明所有变量都是全局变量
function test
{
var1="hello"
local var2="world"
}
test
echo $var1
echo $var2
返回结果
3. 函数库
如果某些函数被多个脚本使用可以把那些函数写在一个函数库中供其他脚本调用
案例:调用函数库中的加减乘除函数
function add
{
echo `expr $1 + $2`
}
function reduce
{
echo `expr $1 - $2`
}
function multiple
{
echo `expr $1 \* $2`
}
function div
{
echo `expr $1 / $2`
}
#!/bin/bash
#
#引用函数库
. /root/script/4.fun/lib/base_function
add 3 4
reduce 90 34
multiple 12 12
div 5 2