Returning Values from Bash Functions
转自: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的更多相关文章
- [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+ ...
- Zend API:深入 PHP 内核
Introduction Those who know don't talk. Those who talk don't know. Sometimes, PHP "as is" ...
- [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 ...
- [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 ...
- Introduction to Writing Functions in R
目录 在R中编写函数 args(函数名) 创建一个函数的步骤 1.default args Passing arguments between functions Checking arguments ...
- 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 ...
- 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 ...
- bash5.0参考手册
Bash Reference Manual a.summary-letter { text-decoration: none } blockquote.indentedblock { margin-r ...
- 关于OC中的小数精确计算---NSDecimalNumber
NSDecimalNumber 翻译补充自:http://rypress.com/tutorials/objective-c/data-types/nsdecimalnumber 感谢乐于分享的大神 ...
随机推荐
- 网络体系结构的概念 - 网络协议TCP - 红黑联盟
https://i.cnblogs.com/EditPosts.aspx?opt=1 网络体系结构的概念 计算机网络就是一组通过一定形式连接起来的计算机系统,它需要四个要素的支持,即通信线路和通信设 ...
- HDU 1077 Catching Fish(用单位圆尽可能围住多的点)
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1077 Catching Fish Time Limit: 10000/5000 MS (Java/Oth ...
- 第13章 GPIO输入—按键检测
本章参考资料:<STM32F76xxx参考手册>.库帮助文档<STM32F779xx_User_Manual.chm>. 按键检测使用到GPIO外设的基本输入功能,本章中不再赘 ...
- CSS3 小会
-webkit-perspective:800px; 其子元素获得3D元素支持,这里是设置子元素距离试图的位置:若设为0 则不支持子元素获得3d效果,不支持透视. 常与transform:rota ...
- CSS&JS定位器
一.CssSelector定位器 1.概述 CssSelector是效率很高的元素定位方法,Selenium官网的Document里极力推荐使用CSS locator,而不是XPath来定位元素,原因 ...
- 重写equals方法(未完)
equals方法是我们日常编程中很常见的方法,Object中对这个方法的解释如下: boolean equals(Object obj) 指示其他某个对象是否与此对象“相等”. 查看该方法的底层代码如 ...
- LeetCode 中级 - 路径总和2(113)
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径. 说明: 叶子节点是指没有子节点的节点. 示例:给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 ...
- noip2018 洛谷 P1969积木大赛
1 //一定不要忘记这句话 “连续区间 ”!! #include<bits/stdc++.h> using namespace std; int main(){ int n, h;//n是 ...
- ABAP术语-ABAP Editor
ABAP Editor 原文链接:http://www.cnblogs.com/qiangsheng/archive/2007/12/08/987498.html Program editor in ...
- springboot 集成kaptcha验证码Demo
验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人 ...