您的位置:首页 > 运维架构 > Shell

linux shell返回值方式及示例

2017-07-25 18:46 148 查看

概述

  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: