$ name="bill" Set initial value
$ nameref firstname=name Set up the nameref
$ print $firstname Actually references variable name
bill
$ firstname="arnold" Now change the indirect reference
$ print $name Shazzam! Original variable is changed
arnold
To find out the name of the real variable being referenced by the nameref,
use ${!variable}:
$ print ${!firstname}
name
At first glance, this doesn't seem to be very useful.
The power of namerefs comes into play when you pass a variable's name
to a function, and you want that function to be able to update the value of that variable.
The following example illustrates how it works:
$ date Current day and time
Wed May 23 17:49:44 IDT 2001
$ function getday { Define a function
> typeset -n day=$1 Set up the nameref
> day=$(date | awk '{ print $1 }') Actually change it
> }
$ today=now Set initial value
$ getday today Run the function
$ print $today Display new value
Wed
The default output of date(1) looks like this:
$ date
Wed Nov 14 11:52:38 IST 2001