What's the best way to update a variable indirectly, e.g. when its name is
passed to an update function?  Since I wrote the functions below some time
ago and I've wondered whether there might be a better way.  It would be
nice if indirect parameter assignment was as easy as indirect parameter
access, i.e. if {!name} could be used on the lhs.  Values/elements with
embedded whitespace must not be broken.

Here are the convenience functions I use now:

# simple_set VARIABLE_NAME VALUE...
# sets the named variable to the specified value/list
simple_set() {
    local -r name="${1}" ; shift
    eval "${name}='${*}'"
}

#simple_array ARRAY_NAME ELEMENT...
# sets named variable to an array of the specified elements
simple_array() {
    local -r vals=( "${@:2}" )
    eval "$1=(\"\${va...@]}\")"
}

Now that BASH supports associative arrays I will need to write something
to set those indirectly too.

Thanks for your suggestions,

_Greg

J. Greg Davidson


Reply via email to