shell函数案例

来源: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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值