目录1、返回值的方式:2、return和echo使用场景区别:3、场景示例1、返回值的方式: 方法一:return方法二: echo 2、return和echo使用场景区别: (1).使用return返回值: 使用ret
(1).使用return返回值:
(2).使用echo返回值:
(一) return使用场景
函数通过return返回一个整数,这种场景通常是用来做判断的,也就是说在执行完函数之后,需要根据它的返回值做判断,通0表示成功,非0都是表示失败。
#!/bin/bash
this_pid=$$
# 判断Nginx进程是否正在运行
function is_nginx_running
{
ps -ef | grep nginx | grep -v grep | grep -v $this_pid &>/tmp/null
if [ $? -eq 0 ];then
# return 0,也可以省略0直接return,两个是等价
return
else
return 1
fi
}
# return在函数中的返回值,只是用来做状态判断的,根据状态值做下一步判断
# 函数的返回值为0时,表示nginx服务运行正常输出 && 后字符串,否则返回 ||后字符串
is_nginx_running && echo "Nginx is running" || echo "Nginx is stoped"
# 运行脚本
~ % sh 29.echo_return_nginx.sh
Nginx is stoped
~ % sudo nginx # Mac 使用,linux为 systemctl start nginx
~ % sh 29.echo_return_nginx.sh
Nginx is running
(二) echo使用场景
函数通过echo返回值,通常是返回数据用的,以供程序的其它地方使用。
#!/bin/bash
# 获取整个Linux系统上所拥有的所有用户
function get_users
{
# users=`cat /etc/passwd | cut -d: -f1` # linux使用
# Mac 使用
users=`cat /etc/passwd | tail -n+11 | cut -d: -f1 | cut -d_ -f2`
echo $users
}
# 执行该函数,返回值为用户列表
# get_users
# 遍历用户列表对用户名做处理
user_list=`get_users`
index=1
for user in $user_list
do
echo "This $index user is : $user"
index=$(($index+1))
done
# 运行脚本
~ % sh 30.echo_sys_user.sh
This 1 user is : nobody
This 2 user is : root
... ...
This 109 user is : oahd
到此这篇关于shell函数返回值方式的文章就介绍到这了,更多相关Shell函数返回值内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
--结束END--
本文标题: Shell函数返回值方式
本文链接: https://www.lsjlt.com/news/33510.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-29
2024-04-29
2024-04-29
2024-04-18
2024-04-17
2024-04-11
2024-04-08
2024-04-08
2024-04-03
2024-03-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0