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 感谢乐于分享的大神 ...
随机推荐
- ACM-ICPC 2017 Asia HongKong 解题报告
ACM-ICPC 2017 Asia HongKong 解题报告 任意门:https://nanti.jisuanke.com/?kw=ACM-ICPC%202017%20Asia%20HongKon ...
- P2341 [HAOI2006]受欢迎的牛 强连通
题目背景 本题测试数据已修复. 题目描述 每头奶牛都梦想成为牛棚里的明星.被所有奶牛喜欢的奶牛就是一头明星奶牛.所有奶 牛都是自恋狂,每头奶牛总是喜欢自己的.奶牛之间的“喜欢”是可以传递的——如果A喜 ...
- ES6学习笔记(对象)
1.属性的简洁表示法 const foo = 'bar'; const baz = {foo}; baz // {foo: "bar"} // 等同于 const baz = {f ...
- 学大伟业 Day 3 培训总结
今天讲的字符串: 不多说,直接看题 一.表达式求值 题目大意: 输入一行一个表达式,计算其答案 表达式包含非负整数.加减乘除.括号 两种做法 ·栈 ·表达式树 这里更推荐表达式树,因为栈是先压进去,逆 ...
- Android学习笔记_29_样式和主题
一.简单样式定义和使用: android中的样式和CSS样式作用相似,都是用于为界面元素定义显示风格,它是一个包含一个或者多个view控件属性的集合.如:需要定义字体的颜色和大小. 在Android中 ...
- mysql复制表数据,多表数据复制到一张表
对于mysql 复制表数据可以使用 insert into select 方式 示例: $sql="insert into icarzoo.provider(providerId,provi ...
- LeetCode14.最长公共前缀 JavaScript
编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow" ...
- python学习笔记--数据类型
Life is short, You need Python! 霸气的口号! 今天我也开始学python了,毕竟不懂后端的前端不是好前端.之前有过‘世界上最好的语言’和JavaScript的学习经验. ...
- 18.Shiro与Springboot整合下登陆验证UserService未注入的问题
Shiro与Springboot整合下登陆验证UserService未注入的问题 前言: 刚开始整合的情况下,UserService一执行,就会报空指针异常. 看了网上各位大神的讲解,什么不能用ser ...
- Linux上往mysql中导入SQL文件
1.首先连上你的服务器 2.进入你安装好的数据库 mysql -uroot -p****, 3.执行命令 source /xxx/xxx.sql 后面是文件的路径 4.如果你要是在本地有数据库管理 ...