转自: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. ZJOI2019Day1镇海中学游记(3.24~3.27)

    前言 第一次正式参加省选!不管怎么说,虽然明知自己很弱,但还是要尽力去尝试吧! 最好能进前\(100\),不然就没法去\(Day2\)了. \(Mar\ 24th\):出发 今天,我们正式从二中向宁波 ...

  2. BZOJ3680:吊打XXX(模拟退火)

    Description gty又虐了一场比赛,被虐的蒟蒻们决定吊打gty.gty见大势不好机智的分出了n个分身,但还是被人多势众的蒟蒻抓住了.蒟蒻们将 n个gty吊在n根绳子上,每根绳子穿过天台的一个 ...

  3. LA 3126 出租车

    题目链接:https://vjudge.net/problem/UVALive-3126 题意:有m个客人,位于不同的位置,去一些地方,出发的时间给出,要一些出租车去接,但是,每辆出租车要在出发前一分 ...

  4. 2018.12.2 Mac环境下mysql图形化界面的Navicat premium 12 中文版安装与激活

    软件链接: https://pan.baidu.com/s/1ZUNLQ1DW9rQZUzDXQn2rWQ 提取码: 8i78 复制这段内容后打开百度网盘手机App,操作更方便哦 注意最新版 12.0 ...

  5. visual assist x vs2012不智能提示

    今天装了visual assist x,但是在vs2012里不智能提示,在哪里看了看.找到了开关. 我英文不好.... 默认的话是不选中的.

  6. Angular将填入表单的数据渲染到表格

    一.项目简介 我们将采用Angular框架来做一个demo,这个demo将要实现的功能如下: 在X坐标和Y坐标文本框输入信息,然后点击添加,就会在下面表格 中出现一项相应的数据,点击每一项旁边的删除按 ...

  7. 重写equals方法(未完)

    equals方法是我们日常编程中很常见的方法,Object中对这个方法的解释如下: boolean equals(Object obj) 指示其他某个对象是否与此对象“相等”. 查看该方法的底层代码如 ...

  8. 怎样在Swift中使用CocoaPods

    怎样在Swift中使用CocoaPods 它不是神秘的亚马逊区域的部落人用手捡出来的生可可的豆荚,肯定不是!让CocoaPods website来回答可能是最好的: CocoaPods是Cocoa项目 ...

  9. Java秒杀系统方案优化 高性能高并发实战(已完成)

    1:商品列表 2:商品详情判断是否可以开始秒杀,未开始不显示秒杀按钮显示倒计时,开始显示秒杀按钮,同时会显示验证码输入框以及验证码图片,当点击秒杀按钮的时候会首先判断验证码是否正确,如果正确会返回一个 ...

  10. Redis面向java的Client

    一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...