【发布时间】:2010-10-07 02:52:08
【问题描述】:
我想问是否可以通过引用将参数传递给脚本函数:
即在 C++ 中做一些看起来像这样的事情:
void boo(int &myint) { myint = 5; }
int main() {
int t = 4;
printf("%d\n", t); // t->4
boo(t);
printf("%d\n", t); // t->5
}
那么在 BASH 中我想做类似的事情:
function boo ()
{
var1=$1 # now var1 is global to the script but using it outside
# this function makes me lose encapsulation
local var2=$1 # so i should use a local variable ... but how to pass it back?
var2='new' # only changes the local copy
#$1='new' this is wrong of course ...
# ${!1}='new' # can i somehow use indirect reference?
}
# call boo
SOME_VAR='old'
echo $SOME_VAR # -> old
boo "$SOME_VAR"
echo $SOME_VAR # -> new
任何想法将不胜感激。
【问题讨论】:
标签: bash shell scripting pass-by-reference