Passing arguments by reference

后端 未结 9 1962
挽巷
挽巷 2020-12-01 01:13

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

i.e. to do something that would look like this in C++:



        
9条回答
  •  佛祖请我去吃肉
    2020-12-01 02:00

    Bash doesn't have anything like references built into it, so basically the only way you would be able to do what you want is to pass the function the name of the global variable you want it to modify. And even then you'll need an eval statement:

    boo() {
        eval ${1}="new"
    }
    
    SOME_VAR="old"
    echo $SOME_VAR # old
    boo "SOME_VAR"
    echo $SOME_VAR # new
    

    I don't think you can use indirect references here because Bash automatically accesses the value of the variable whose name is stored in the indirect reference. It doesn't give you the chance to set it.

提交回复
热议问题