linux shell返回值方式及示例
2017-07-25 18:46
148 查看
概述
Shell函数返回值,常用的两种方式:echo和returnecho
据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
相关文章推荐
- Java之从任务中产生返回值方式1
- 自学Linux Shell9.3-基于Red Hat系统工具包:RPM属性依赖的解决方式-YUM在线升级
- linux shell 自定义函数(定义、返回值、变量作用域)介绍
- linux shell 自定义函数(定义、返回值、变量作用域)介绍
- linux shell 编程示例
- Linux Shell 自定义函数(定义、返回值、变量作用域)介绍
- Java中对XML格式数据的四种解析方式,代码示例解析
- 通过AJAX的JS、JQuery两种方式解析XML示例介绍
- 多线程1:两种方式创建线程示例
- WinExec、ShellExecute和CreateProcess及返回值判断方式[转]
- C++中各种初始化方式示例详解
- android效果TapBarMenu绘制底部导航栏的使用方式示例
- 源码方式向openssl中添加新算法完整详细步骤(示例:摘要算法SM3)【非engine方式】
- .net单元测试——常用测试方式(异常模拟、返回值测试、参数测试、数据库访问代码测试)
- 关于两种错误处理方式(返回值,异常)的浅显认识
- linux shell 自定义函数(定义、返回值、变量作用域)
- Executor接口实现线程有返回值和无返回值两种方式
- linux shell 自定义函数(定义、返回值、变量作用域)介绍
- 访问main函数返回值的方式
- linux shell执行方式