我想从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没有返回类型的概念,只有退出码和文件描述符(stdin/out/err等)。
其他回答
像上面的bstpierre一样,我使用并推荐使用显式命名输出变量:
function some_func() # OUTVAR ARG1
{
local _outvar=$1
local _result # Use some naming convention to avoid OUTVARs to clash
... some processing ....
eval $_outvar=\$_result # Instead of just =$_result
}
注意引用$的用法。这将避免将$result中的内容解释为shell特殊字符。我发现这比result=$(some_func "arg1")捕获回声的习惯用法快一个数量级。在MSYS上使用bash时,速度差异似乎更加显著,从函数调用中捕获标准输出几乎是灾难性的。
可以发送一个局部变量,因为局部变量在bash中是动态作用域的:
function another_func() # ARG
{
local result
some_func result "$1"
echo result is $result
}
为了说明我对Andy的回答的评论,使用额外的文件描述符操作来避免使用/dev/tty:
#!/bin/bash
exec 3>&1
returnString() {
exec 4>&1 >&3
local s=$1
s=${s:="some default string"}
echo "writing to stdout"
echo "writing to stderr" >&2
exec >&4-
echo "$s"
}
my_string=$(returnString "$*")
echo "my_string: [$my_string]"
不过还是很恶心。
如前所述,从函数返回字符串的“正确”方法是使用命令替换。如果函数也需要输出到控制台(如@Mani上面提到的),在函数的开头创建一个临时fd并重定向到控制台。在返回字符串之前关闭临时fd。
#!/bin/bash
# file: func_return_test.sh
returnString() {
exec 3>&1 >/dev/tty
local s=$1
s=${s:="some default string"}
echo "writing directly to console"
exec 3>&-
echo "$s"
}
my_string=$(returnString "$*")
echo "my_string: [$my_string]"
执行没有参数的脚本会产生…
# ./func_return_test.sh
writing directly to console
my_string: [some default string]
希望这能帮助到人们
安迪
最直接和健壮的解决方案是使用命令替换,就像其他人写的那样:
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"
}
也许最优雅的解决方案是为函数返回值和保留一个全局名称 在您编写的每个函数中一致地使用它。
#实现一个通用的函数返回堆栈:
STACK=()
push() {
STACK+=( "${1}" )
}
pop() {
export $1="${STACK[${#STACK[@]}-1]}"
unset 'STACK[${#STACK[@]}-1]';
}
#用法:
my_func() {
push "Hello world!"
push "Hello world2!"
}
my_func ; pop MESSAGE2 ; pop MESSAGE1
echo ${MESSAGE1} ${MESSAGE2}