我想从Bash函数返回一个字符串。
我将用java写这个例子来说明我想做什么:
public String getSomeString() {
return "tadaa";
}
String variable = getSomeString();
下面的示例可以在bash中工作,但是是否有更好的方法来做到这一点?
function getSomeString {
echo "tadaa"
}
VARIABLE=$(getSomeString)
我想从Bash函数返回一个字符串。
我将用java写这个例子来说明我想做什么:
public String getSomeString() {
return "tadaa";
}
String variable = getSomeString();
下面的示例可以在bash中工作,但是是否有更好的方法来做到这一点?
function getSomeString {
echo "tadaa"
}
VARIABLE=$(getSomeString)
当前回答
Bash自2014年2月4.3版(?)起,除了“eval”之外,还明确支持引用变量或名称引用(namerefs),具有相同的性能和间接效果,并且在你的脚本中可能更清晰,也更难“忘记'eval'而不得不修复此错误”:
declare [-aAfFgilnrtux] [-p] [name[=value] ...]
typeset [-aAfFgilnrtux] [-p] [name[=value] ...]
Declare variables and/or give them attributes
...
-n Give each name the nameref attribute, making it a name reference
to another variable. That other variable is defined by the value
of name. All references and assignments to name, except for⋅
changing the -n attribute itself, are performed on the variable
referenced by name's value. The -n attribute cannot be applied to
array variables.
...
When used in a function, declare and typeset make each name local,
as with the local command, unless the -g option is supplied...
还有:
PARAMETERS A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see the descriptions of declare and local below) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is⋅ referenced or assigned to, the operation is actually performed on the variable specified by the nameref variable's value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to⋅ the function. For instance, if a variable name is passed to a shell function as its first argument, running declare -n ref=$1 inside the function creates a nameref variable ref whose value is the variable name passed as the first argument. References and assignments to ref are treated as references and assignments to the variable whose name was passed as⋅ $1. If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be⋅ established for each word in the list, in turn, when the loop is executed. Array variables cannot be given the -n attribute. However, nameref variables can reference array variables and subscripted array variables. Namerefs can be⋅ unset using the -n option to the unset builtin. Otherwise, if unset is executed with the name of a nameref variable as an argument, the variable referenced by⋅ the nameref variable will be unset.
例如(EDIT 2:(谢谢你Ron)在函数内部变量名的命名空间(前缀),以最小化外部变量冲突,这最终应该正确地回答了Karsten在评论中提出的问题):
# $1 : string; your variable to contain the return value
function return_a_string () {
declare -n ret=$1
local MYLIB_return_a_string_message="The date is "
MYLIB_return_a_string_message+=$(date)
ret=$MYLIB_return_a_string_message
}
测试这个例子:
$ return_a_string result; echo $result
The date is 20160817
请注意,bash“declare”内置在函数中使用时,默认情况下会使声明的变量为“local”,并且“-n”也可以与“local”一起使用。
我更喜欢区分“重要的声明”变量和“无聊的本地”变量,因此以这种方式使用“声明”和“本地”作为文档。
编辑1 -(对Karsten下面的评论的回应)-我不能再在下面添加评论了,但Karsten的评论让我思考,所以我做了以下测试,工作良好,AFAICT - Karsten如果你读了这篇文章,请从命令行提供一组准确的测试步骤,显示你假设存在的问题,因为以下步骤工作得很好:
$ return_a_string ret; echo $ret
The date is 20170104
(我刚刚将上面的函数粘贴到bash术语中后运行了这个程序——正如您所看到的,结果运行得很好。)
其他回答
没有比这更好的方法了。Bash只知道写入标准输出的状态码(整数)和字符串。
你可以使用一个全局变量:
declare globalvar='some string'
string ()
{
eval "$1='some other string'"
} # ---------- end of function string ----------
string globalvar
echo "'${globalvar}'"
这给了
'some other string'
虽然有很多很好的答案,但它们都不是我想要的方式。下面是我的解决方案,要点如下:
帮助健忘的程序员
至少我会努力记住错误检查之后,像这样:
允许用换行字符\n赋值
有些解决方案不允许这样做,因为有些解决方案忘记了要赋值周围的单引号。正确的方法:eval "${returnVariable}='${value}'"或者更好:参见下面的下一点。
使用printf代替eval
只需尝试使用类似myFunction "date && var2"的东西来解决这里的一些假定的解决方案。Eval会执行给它的任何东西。我只想分配值,所以我使用printf -v "${returnVariable}" "%s" "${value}"代替。
对变量名冲突的封装和保护
如果一个不同的用户或至少是对函数了解较少的人(这可能是几个月后的我)正在使用myFunction,我不希望他们知道他必须使用全局返回值名称或禁止使用某些变量名称。这就是为什么我在myFunction的顶部添加了一个名称检查:
if [[ "${1}" = "returnVariable" ]]; then
echo "Cannot give the ouput to \"returnVariable\" as a variable with the same name is used in myFunction()!"
echo "If that is still what you want to do please do that outside of myFunction()!"
return 1
fi
注意,如果你需要检查很多变量,这也可以放在函数本身中。 如果我仍然想使用相同的名称(这里:returnVariable),我只是创建了一个缓冲变量,给myFunction,然后复制值returnVariable。
就是这样:
myFunction ():
myFunction() {
if [[ "${1}" = "returnVariable" ]]; then
echo "Cannot give the ouput to \"returnVariable\" as a variable with the same name is used in myFunction()!"
echo "If that is still what you want to do please do that outside of myFunction()!"
return 1
fi
if [[ "${1}" = "value" ]]; then
echo "Cannot give the ouput to \"value\" as a variable with the same name is used in myFunction()!"
echo "If that is still what you want to do please do that outside of myFunction()!"
return 1
fi
local returnVariable="${1}"
local value=$'===========\nHello World\n==========='
echo "setting the returnVariable now..."
printf -v "${returnVariable}" "%s" "${value}"
}
测试用例:
var1="I'm not greeting!"
myFunction var1
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "var1:\n%s\n" "${var1}"
# Output:
# setting the returnVariable now...
# myFunction(): SUCCESS
# var1:
# ===========
# Hello World
# ===========
returnVariable="I'm not greeting!"
myFunction returnVariable
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "returnVariable:\n%s\n" "${returnVariable}"
# Output
# Cannot give the ouput to "returnVariable" as a variable with the same name is used in myFunction()!
# If that is still what you want to do please do that outside of myFunction()!
# myFunction(): FAILURE
# returnVariable:
# I'm not greeting!
var2="I'm not greeting!"
myFunction "date && var2"
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "var2:\n%s\n" "${var2}"
# Output
# setting the returnVariable now...
# ...myFunction: line ..: printf: `date && var2': not a valid identifier
# myFunction(): FAILURE
# var2:
# I'm not greeting!
myFunction var3
[[ $? -eq 0 ]] && echo "myFunction(): SUCCESS" || echo "myFunction(): FAILURE"
printf "var3:\n%s\n" "${var3}"
# Output
# setting the returnVariable now...
# myFunction(): SUCCESS
# var3:
# ===========
# Hello World
# ===========
你可以让这个函数把一个变量作为第一个参数,然后用你想要返回的字符串修改变量。
#!/bin/bash
set -x
function pass_back_a_string() {
eval "$1='foo bar rab oof'"
}
return_var=''
pass_back_a_string return_var
echo $return_var
打印“foo bar rab oof”。
编辑:在适当的地方添加引用,以允许字符串中的空白地址@Luca Borrione的评论。
编辑:作为演示,请参阅下面的程序。这是一种通用的解决方案:它甚至允许您将字符串接收到局部变量中。
#!/bin/bash
set -x
function pass_back_a_string() {
eval "$1='foo bar rab oof'"
}
return_var=''
pass_back_a_string return_var
echo $return_var
function call_a_string_func() {
local lvar=''
pass_back_a_string lvar
echo "lvar='$lvar' locally"
}
call_a_string_func
echo "lvar='$lvar' globally"
这个打印:
+ return_var=
+ pass_back_a_string return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local lvar=
+ pass_back_a_string lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally
编辑:演示原始变量的值在函数中可用,正如@Xichen Li在评论中错误地批评的那样。
#!/bin/bash
set -x
function pass_back_a_string() {
eval "echo in pass_back_a_string, original $1 is \$$1"
eval "$1='foo bar rab oof'"
}
return_var='original return_var'
pass_back_a_string return_var
echo $return_var
function call_a_string_func() {
local lvar='original lvar'
pass_back_a_string lvar
echo "lvar='$lvar' locally"
}
call_a_string_func
echo "lvar='$lvar' globally"
输出如下:
+ return_var='original return_var'
+ pass_back_a_string return_var
+ eval 'echo in pass_back_a_string, original return_var is $return_var'
++ echo in pass_back_a_string, original return_var is original return_var
in pass_back_a_string, original return_var is original return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local 'lvar=original lvar'
+ pass_back_a_string lvar
+ eval 'echo in pass_back_a_string, original lvar is $lvar'
++ echo in pass_back_a_string, original lvar is original lvar
in pass_back_a_string, original lvar is original lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally
最直接和健壮的解决方案是使用命令替换,就像其他人写的那样:
assign()
{
local x
x="Test"
echo "$x"
}
x=$(assign) # This assigns string "Test" to x
缺点是性能,因为这需要一个单独的过程。
本主题中建议的另一种技术,即传递要赋值的变量的名称作为参数,有副作用,我不推荐它的基本形式。问题是,你可能需要函数中的一些变量来计算返回值,可能发生的情况是,用于存储返回值的变量的名称会干扰其中一个:
assign()
{
local x
x="Test"
eval "$1=\$x"
}
assign y # This assigns string "Test" to y, as expected
assign x # This will NOT assign anything to x in this scope
# because the name "x" is declared as local inside the function
当然,您可以不将函数的内部变量声明为局部变量,但您确实应该始终这样做,否则另一方面,如果存在同名的父作用域,则可能会意外地覆盖父作用域中不相关的变量。
一个可能的解决方法是显式声明传递的变量为全局变量:
assign()
{
local x
eval declare -g $1
x="Test"
eval "$1=\$x"
}
If name "x" is passed as an argument, the second row of the function body will overwrite the previous local declaration. But the names themselves might still interfere, so if you intend to use the value previously stored in the passed variable prior to write the return value there, be aware that you must copy it into another local variable at the very beginning; otherwise the result will be unpredictable! Besides, this will only work in the most recent version of BASH, namely 4.2. More portable code might utilize explicit conditional constructs with the same effect:
assign()
{
if [[ $1 != x ]]; then
local x
fi
x="Test"
eval "$1=\$x"
}
也许最优雅的解决方案是为函数返回值和保留一个全局名称 在您编写的每个函数中一致地使用它。