转自:https://www.linuxjournal.com/content/return-values-bash-functions

Bash functions, unlike functions in most programming languages do not allow you to return a value to the caller. When a bash function ends its return value is its status: zero for success, non-zero for failure. To return values, you can set a global variable with the result, or use command substitution, or you can pass in the name of a variable to use as the result variable. The examples below describe these different mechanisms.

Although bash has a return statement, the only thing you can specify with it is the function's status, which is a numeric value like the value specified in an exit statement. The status value is stored in the $? variable. If a function does not contain a return statement, its status is set based on the status of the last statement executed in the function. To actually return arbitrary values to the caller you must use other mechanisms.

The simplest way to return a value from a bash function is to just set a global variable to the result. Since all variables in bash are global by default this is easy:

function myfunc()
{
myresult='some value'
} myfunc
echo $myresult

The code above sets the global variable myresult to the function result. Reasonably simple, but as we all know, using global variables, particularly in large programs, can lead to difficult to find bugs.

A better approach is to use local variables in your functions. The problem then becomes how do you get the result to the caller. One mechanism is to use command substitution:

function myfunc()
{
local myresult='some value'
echo "$myresult"
} result=$(myfunc) # or result=`myfunc`
echo $result

Here the result is output to the stdout and the caller uses command substitution to capture the value in a variable. The variable can then be used as needed.

The other way to return a value is to write your function so that it accepts a variable name as part of its command line and then set that variable to the result of the function:

function myfunc()
{
local __resultvar=$1
local myresult='some value'
eval $__resultvar="'$myresult'"
} myfunc result
echo $result

Since we have the name of the variable to set stored in a variable, we can't set the variable directly, we have to use eval to actually do the setting. The eval statement basically tells bash to interpret the line twice, the first interpretation above results in the string result='some value' which is then interpreted once more and ends up setting the caller's variable.

When you store the name of the variable passed on the command line, make sure you store it in a local variable with a name that won't be (unlikely to be) used by the caller (which is why I used __resultvar rather than just resultvar). If you don't, and the caller happens to choose the same name for their result variable as you use for storing the name, the result variable will not get set. For example, the following does not work:

function myfunc()
{
local result=$1
local myresult='some value'
eval $result="'$myresult'"
} myfunc result
echo $result

The reason it doesn't work is because when eval does the second interpretation and evaluates result='some value', result is now a local variable in the function, and so it gets set rather than setting the caller's result variable.

For more flexibility, you may want to write your functions so that they combine both result variables and command substitution:

function myfunc()
{
local __resultvar=$1
local myresult='some value'
if [[ "$__resultvar" ]]; then
eval $__resultvar="'$myresult'"
else
echo "$myresult"
fi
} myfunc result
echo $result
result2=$(myfunc)
echo $result2

Here, if no variable name is passed to the function, the value is output to the standard output.

Returning Values from Bash Functions的更多相关文章

  1. [C++] Returning values by reference in C++

    A C++ program can be made easier to read and maintain by using references rather than pointers. A C+ ...

  2. Zend API:深入 PHP 内核

    Introduction Those who know don't talk. Those who talk don't know. Sometimes, PHP "as is" ...

  3. [Go] Returning Multiple Values from a Function in Go

    Returning multiple values from a function is a common idiom in Go, most often used for returning val ...

  4. [Bash] Understand and Use Functions in Bash

    n this lesson, we'll go over how bash functions work. Bash functions work like mini bash scripts--yo ...

  5. Introduction to Writing Functions in R

    目录 在R中编写函数 args(函数名) 创建一个函数的步骤 1.default args Passing arguments between functions Checking arguments ...

  6. JavaScript Patterns 4.5 Immediate Functions

    The immediate function pattern is a syntax that enables you to execute a function as soon as it is d ...

  7. Bash String Manipulation Examples – Length, Substring, Find and Replace--reference

    In bash shell, when you use a dollar sign followed by a variable name, shell expands the variable wi ...

  8. bash5.0参考手册

    Bash Reference Manual a.summary-letter { text-decoration: none } blockquote.indentedblock { margin-r ...

  9. 关于OC中的小数精确计算---NSDecimalNumber

    NSDecimalNumber 翻译补充自:http://rypress.com/tutorials/objective-c/data-types/nsdecimalnumber 感谢乐于分享的大神 ...

随机推荐

  1. BZOJ2648/2716:SJY摆棋子/[Violet]天使玩偶(K-D Tree)

    Description 这天,SJY显得无聊.在家自己玩.在一个棋盘上,有N个黑色棋子.他每次要么放到棋盘上一个黑色棋子,要么放上一个白色棋子,如果是白色棋子,他会找出距离这个白色棋子最近的黑色棋子. ...

  2. [19/03/15-星期五] 常用类_String类&StringBuilder和StringBuffer类

    一.基本概念 String 类对象代表不可变的Unicode字符序列,因此我们可以将String对象称为“不可变对象”. 那什么叫做“不可变对象”呢?  指的是对象内部的成员变量的值无法再改变.Str ...

  3. org.apache.tomcat.util.descriptor.web.WebXml.setVersion Unknown version string [4.0]. Default version will be used.报错

    org.apache.tomcat.util.descriptor.web.WebXml.setVersion Unknown version string [4.0]. Default versio ...

  4. c#正则表达式最简demo

    各个语言的正则表达式规则略有不同 项目中用到,所以将这个最简单的demo记录 using System; using System.Collections.Generic; using System. ...

  5. HDU 2005 第几天?(闰年判断)

    传送门: acm.hdu.edu.cn/showproblem.php?pid=2005 第几天? Time Limit: 2000/1000 MS (Java/Others)    Memory L ...

  6. 64 位系统(win7/win8) 下使用C# 程序问题

    1  C# 程序是控制台类,使用的组件如果是32位,建议在编译的时候,platform (X86,AnyCPU,X64)选择X86 .使用X86 模式编译,才能调用32位程序的API. 2  ASP. ...

  7. o'Reill的SVG精髓(第二版)学习笔记——第二章

    在网页中使用SVG 将SVG作为图像: SVG是一种图像格式,因此可以使用与其他图像类型相同的方式包含在HTML页面中,具体可以采用两种方法:将图像包含在HTML标记的<img>元素内(当 ...

  8. 大数据开发从入门小白到删库跑路(一)- 获取Hadoop

    Hadoop是一个可以通过相对简单编程模型实现跨多台计算机集群分布式处理大型数据集的框架.它不是依赖于高额成本的硬件可靠性来提供高可用性,Hadoop的设计能从单个服务器扩展到数千台机器,每个机器提供 ...

  9. Vue使用json-server来进行后端数据模拟

    正开发过程中 前后端分离或者不分离 ,接口多半是之后与页面的开发 ,所以建立rest的APL的接口 给前端提供虚拟的数据是非常必要的 所以这里我使用了json-server作为工具,支持CORS和JS ...

  10. JZOJ 5934. 列队

    Description         Sylvia是一个热爱学习的女孩子.        在平时的练习中,他总是能考到std以上的成绩,前段时间,他参加了一场练习赛,众所周知,机房是一个 的方阵.这 ...