天天看点

linux shell返回值方式及示例概述

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

概述

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

echo

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

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

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

使用echo返回的示例

[[email protected] ~]# 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"
           

执行

[[email protected] ~]# ./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返回的示例

[[email protected] ~]# 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"
           

执行

[[email protected] ~]# ./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

继续阅读