转自: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. 【洛谷5287】[HNOI2019] JOJO(主席树优化KMP)

    点此看题面 大致题意: 每次往一个字符串末尾加上\(x\)个字符\(c\),或者回到某一历史版本,求\(KMP\)的\(\sum Next_i\). 问题转化 考虑到可以离线. 于是,我们就可以用一个 ...

  2. 过拟合是什么?如何解决过拟合?l1、l2怎么解决过拟合

    1. 过拟合是什么? https://www.zhihu.com/question/264909622    那个英文回答就是说h1.h2属于同一个集合,实际情况是h2比h1错误率低,你用h1来训练, ...

  3. mac 上安装lua

    mac 安装lua google了好个看起来都不怎么好操作,这个是在命令行下操作的很简单. http://www.lua.org/download.html curl -R -O http://www ...

  4. css ul dl dt 表格分页 文本框样式

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  5. HDU 2859 Phalanx(对称矩阵 经典dp样例)

    传送门: http://acm.hdu.edu.cn/showproblem.php?pid=2859 Phalanx Time Limit: 10000/5000 MS (Java/Others)  ...

  6. Python基础—14-邮件与短信

    邮件与短信 邮件发送 简介: 邮件服务器.账户.密码 相关协议:SMTP.POP3.IMAP 默认TCP协议端口:25 用途:经常用在一个网站的注册激活.通知.找回密码等场景 库:smtplib 示例 ...

  7. JSP静态包含和动态包含

    JSP中有两种包含: 静态包含:<%@include file="被包含页面"%>: 动态包含:<jsp:include page="被包含页面&quo ...

  8. view添加毛玻璃效果两种方法

    第一种方法: UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; UIVisualEffectV ...

  9. harbor中碰到的问题

    harbor部署整体比较简单,但是就是这么简单的东西稍微改变点配置文件就会有不小的问题 1.问题1 部署harbor1.6发现web界面删除的镜像在push一遍上去后,镜像大小为0 且无法删除,这个问 ...

  10. linux下进程的最大线程数、进程最大数、进程打开的文件数

    linux下进程的最大线程数.进程最大数.进程打开的文件数   ===========最大线程数============== linux 系统中单个进程的最大线程数有其最大的限制 PTHREAD_TH ...