linux shell返回值方式及示例

本文详细介绍了Shell脚本中函数返回值的两种常见方式:echo和return。通过具体示例展示了如何使用这两种方法来实现函数返回值,并解释了它们之间的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权声明:本文为博主转载文章,码字不易,转载请标明出处。 https://blog.csdn.net/yue530tomtom/article/details/76094008

概述

  Shell函数返回值,常用的两种方式:echo和return

echo

据man手册描述:echo是一个输出参数,有空格分割,会产生一个新行。返回永远是0。

echo一般起到一个提示的作用。在shell编程中极为常用, 在终端下打印变量value的时候也是常常用到的。

在shell中子进程会继承父进程的标准输出,因此,子进程的输出也就直接反应到父进程。所以函数的返回值通过输出到标准输出是一个非常安全的返回方式。

使用echo返回的示例

[root@wmstianjin16172 ~]# cat echoTestFun.sh 
#!/bin/bash  
function echoTestFun()  
{  
    if [ -z $1 ] 
    then  
        echo "0"  
    else  
        echo "$@"  
    fi  
}
echo "Agrs not null start:"
echoTestFun $@  
echo "Agrs not null end"
echo "Agrs  null start:"
echoTestFun  
echo "Agrs  null end"

 

 

 

执行

[root@wmstianjin16172 ~]# ./echoTestFun.sh 1 hh 3
Agrs not null start:
1 hh 3
Agrs not null end
Agrs  null start:
0
Agrs  null end

 

 

 

return

shell函数的返回值,可以和其他语言的返回值一样,通过return语句返回,BUT return只能用来返回整数值;且和c的区别是返回为正确,其他的值为错误。

使用return返回的示例

[root@wmstianjin16172 ~]# cat returnTestFun.sh 
#!/bin/bash  
function returnTestFun()  
{  
    if [ -z $1 ]
    then  
        return 0  
    else  
        return 1  
    fi  
}
echo "Agrs not null start:"
returnTestFun $@  
echo $?
echo "Agrs not null end"
echo "Agrs  null start:"
returnTestFun
echo $?
echo "Agrs  null end"

 

 

 

执行

[root@wmstianjin16172 ~]# ./returnTestFun.sh hello world
Agrs not null start:
1
Agrs not null end
Agrs  null start:
0
Agrs  null end

 

 

若返回不是整数的返回值,将会得到一个错误 
如把上例中的return 1改为return $1,使用同样的参数运行将得到提示:

./returnTestFun.sh: line 8: return: hello: numeric argument required

版权声明:本文为博主转载文章,码字不易,转载请标明出处。 https://blog.csdn.net/yue530tomtom/article/details/76094008

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值