脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - shell - Shell函数返回值方式

Shell函数返回值方式

2023-03-01 13:57AllardZhao shell

本文主要介绍了Shell函数返回值方式,主要介绍了两种返回方式,分别介绍了场景的使用和区别,具有一定的参考价值,感兴趣的可以了解一下

1、返回值的方式:

  • 方法一:return
  • 方法二: echo

2、return和echo使用场景区别:

(1).使用return返回值:

  • 使用return返回值,只能返回1-255的整数
  • 函数使用return返回值,通常只是用来供其他地方调用获取状态,因此通常仅返回0或1;0表示成功,1表示失败

(2).使用echo返回值:

  • 使用echo可以返回任何字符串结果
  • 通常用于返回数据,比如一个字符串值或者列表值

3、场景示例

(一) return使用场景

函数通过return返回一个整数,这种场景通常是用来做判断的,也就是说在执行完函数之后,需要根据它的返回值做判断,通0表示成功,非0都是表示失败。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/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返回值,通常是返回数据用的,以供程序的其它地方使用。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/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函数返回值内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_37189082/article/details/121894595

延伸 · 阅读

精彩推荐