McWalter.org :: Passing variables by reference to bash functions


The bash shell features functions, but they're really mostly like jumped-up macros, not like real functions in a regular programming language. For example, one would like to be able to do something like:
function ff() {
  return XXX
}

FOO=ff

The code above doesn't work, as bash's return keyword is used to return status (a numerical value that's stored in the $? variable), and not a more complex value like a string or an array.

The solution to the lack of a useful return value is to pass a variable by reference to the function, and have the function set the value of that variable. This is analagous to var parameters in pascal, & references in C++, and to passing by pointer in C. The following example shows a simple function that sets the value of the variable provided as its only parameter to XXX:

#!/usr/bin/bash

function setToXXX() {
  echo changing value of $1
  eval "$1=XXX"
}

FOO=hello
BAR=goodbye

setToXXX FOO
setToXXX BAR

echo after function, FOO is $FOO
echo after function, BAR is $BAR

After this is run, both FOO and BAR will contain XXX.

Credits: I got some help on the eval part from the knowledgable folks on the Yahoo! "Unix-Shell-prog" group.