Roman M Roman M - 1 month ago 5x
Bash Question

Bash - Passing arguments by reference

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:

Void boo (int & myint) { myint= 5; }

main (){
int t= 4;
printf t; // t->4
boo (t);
printf t; // t ->5

So then in BASH I want to do something like:

Function boo ()

var1=$1 # now var1 is global to the scrip but using it outside
# this function makes me loose 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
echo $SOME_VAR # -> old
boo "$SOME_VAR"
echo $SOME_VAR # -> new

Any thoughts would be appreciated.


I have found a way to do this but I am not sure how correct this is:

    local var1="$1"
    eval $var1=2
    # or can do eval $1=2 if no local var

echo  var is $var    # $var = 1
newfun 'var'         # pass the name of the variable…
echo now var is $var # $var = 2

So we pass the variable name as opposed to the value and then use eval ...