通过引用传递参数 [英] Passing arguments by reference

查看:62
本文介绍了通过引用传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问问是否可以通过引用将参数传递给脚本函数:

I want to ask if it is possible to pass arguments to a script function by reference:

即做一些在C ++中看起来像这样的事情:

i.e. to do something that would look like this in 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中,我想做类似的事情:

So then in BASH I want to do something like:

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

任何想法都会受到赞赏.

Any thoughts would be appreciated.

推荐答案

现在是2018年,这个问题值得更新.至少在Bash中,从Bash 4.3-alpha开始,您可以使用 namerefs 通过引用传递函数参数:

It's 2018, and this question deserves an update. At least in Bash, as of Bash 4.3-alpha, you can use namerefs to pass function arguments by reference:

function boo() 
{
    local -n ref=$1
    ref='new' 
}

SOME_VAR='old'
echo $SOME_VAR # -> old
boo SOME_VAR
echo $SOME_VAR # -> new

这里的关键部分是:

  • 将变量的名称传递给boo,而不是其值: boo SOME_VAR ,而不是 boo $SOME_VAR .

  • Passing the variable's name to boo, not its value: boo SOME_VAR, not boo $SOME_VAR.

在函数内部,使用 local -n ref=$1 $1命名的变量声明 nameref ,这意味着它不是对$1的引用本身,而是保留名称为 $1的变量,即本例中的SOME_VAR.右侧的值应该只是一个命名现有变量的字符串:字符串的获取方式无关紧要,因此local -n ref="my_var"local -n ref=$(get_var_name)之类的东西也可以工作. declare也可以在允许/需要的情况下替换local.有关更多信息,请参见有关Shell参数的章节信息.

Inside the function, using local -n ref=$1 to declare a nameref to the variable named by $1, meaning it's not a reference to $1 itself, but rather to a variable whose name $1 holds, i.e. SOME_VAR in our case. The value on the right-hand side should just be a string naming an existing variable: it doesn't matter how you get the string, so things like local -n ref="my_var" or local -n ref=$(get_var_name) would work too. declare can also replace local in contexts that allow/require that. See chapter on Shell Parameters in Bash Reference Manual for more information.

这种方法的优点是(可以说)更好的可读性,并且最重要的是避免使用eval,它的安全隐患很多并且有据可查.

The advantage of this approach is (arguably) better readability and, most importantly, avoiding eval, whose security pitfalls are many and well-documented.

这篇关于通过引用传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆