Saturday, February 27, 2010

Passing by reference in bash

It is possible to mimic pass by reference in a bash shell.

The trick is to pass the name of the variable, not its expanded value.

Use

func out

instead of

func $out


In the function, set the value of the out parameter as

eval "$1=expr"

In the function, copy the value of the parameter to a local variable with

eval "L_VAR=\${$1}"

When using local variables, it is important that the name of the variable from the caller is not the same name as the local variable in the function. The local in the function is deleted when the function ends.

#!/bin/bash

#$1 is name of out param, $2 is name of out param
func () {
  local loc=8
  local diff=9
  local same=10
  eval "$1=$diff"
  eval "$2=$same"
}

loc=7
func out same
echo "loc = $loc"               #loc = 7
echo "out = $out"               #out = 9     
echo "same = $same"             #same = 

No comments:

Post a Comment

Followers