Book HomeBook TitleSearch this book

4.4. Indirect Variable References (namerefs)

Most of the time, as we've seen so far, you manipulate variables directly, by name (x=1, for example). The Korn shell allows you to manipulate variables indirectly, using something called a nameref. You create a nameref using typeset -n, or the more convenient predefined alias, nameref. Here is a simple example:

$ 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

The getday function uses awk to print the first field, which is the day of the week. The result of this operation, which is done inside command substitution (described later in this chapter), is assigned to the local variable day. But day is a nameref; the assignment actually updates the global variable today. Without the nameref facility, you have to resort to advanced tricks like using eval (see Chapter 7) to make something like this happen.

To remove a nameref, use unset -n, which removes the nameref itself, instead of unsetting the variable the nameref is a reference to. Finally, note that variables that are namerefs may not have periods in their names (i.e., be components of a compound variable). They may, though, be references to a compound variable.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.