【发布时间】:2016-11-19 21:14:33
【问题描述】:
我只是在 bash 函数中苦苦挣扎,并试图返回字符串值,同时在函数内部修改了一些全局变量。一个例子:
MyGlobal="some value"
function ReturnAndAlter () {
MyGlobal="changed global value"
echo "Returned string"
}
str=$(ReturnAndAlter)
echo $str # prints out 'Returned value' as expected
echo $MyGlobal # prints out the initial value, not changed
这是因为 $(...)(如果使用 `...` 代替)会导致函数拥有自己的环境,因此全局变量永远不会受到影响。
我发现了一个非常肮脏的解决方法,将值返回到另一个全局变量并仅使用其名称调用该函数,但认为应该有一种更简洁的方法来做到这一点。
我的肮脏解决方案:
MyGlobal="some value"
ret_val=""
function ReturnAndAlter () {
ret_val="Returned string"
MyGlobal="changed value"
}
ReturnAndAlter # call the bare function
str=$ret_val # and assign using the auxiliary global ret_val
echo $str
echo $MyGlobal # Here both global variables are updated.
有什么新想法吗?调用我缺少的函数的某种方式?
【问题讨论】:
标签: bash global-variables return-value