[PLUG] Re: bash question: can variable contain a variable?

Wil Cooley wcooley at nakedape.cc
Fri Jan 28 23:46:02 UTC 2005


On 2005-01-28, Eric House <fixin at peak.org> wrote:
> I want to write a bash function that takes a parameter containing the
> name of a variable, to test that that variable is bound to a path to
> an existing file, and to print an error with the variable name if it's
> not found.  If bash's vars were like perl's, it'd look like this:
>
> function checkispath {
>     if [ ! -f $$1 ]; then echo "path $$1 in var $1 not found"; exit 1; fi
> }
>
> APATH=/tmp/somedir/somefile.txt
> checkdir APATH                          # NOT checkdir "$APATH"
>
> But the $$1 (and ${$1}, etc.) doesn't work in bash.  Is this even
> possible in bash?  If so, what's the syntax?  

See G3: http://www.faqs.org/faqs/unix-faq/shell/bash/

I'm not using ${!var} syntax because I didn't know about it until the other
day; I've been using plain-old 'eval', like this:

#
# path_append - Appends a path element to any PATH-like variable.
#
# Pass it the name of the PATH-like variable and the string to append.
#
function path_append {
    if [ $# -ne 2 ]; then
        printf 'path_append <PATH_LIKE> <path_element>\n'
        return 1
    fi
    
    local x
    eval x=\$$1
    
    if [ -n "$x" ]; then
        eval $1=$x:$2
    else
        eval $1=$2
    fi
}
###


> For bonus credit, what the
> heck do you google for to answer a question like this? :-)

faqs.org is a good place to start.  The newsgroup comp.unix.shell (which you
can search through Google Groups) has lots of this kind of thing; there are
other FAQs that are posted there regularly.

Wil
-- 
Wil Cooley                                 wcooley at nakedape.cc
Naked Ape Consulting                        http://nakedape.cc
* * * * Linux, UNIX, Networking and Security Solutions * * * *




More information about the PLUG mailing list