views:

188

answers:

1

I'm trying to port a script from BASH to ASH (Almquist SHell) and am running into a problem with indirect references. The following function

cmd() {
    # first argument is the index to print (ie label)
    arg=$1
    # ditch the first argument
    shift
    # print the label (via indirect reference)
    echo "${!arg}"
}

should produce the following output

cmd 1 one two three
one
cmd 2 one two three
two
cmd 3 one two three
three

This works as expected under BASH, but generates a "syntax error: Bad substitution" when run under ASH (or DASH). Should this work? If not, is there an alternative to using indirect references?

A: 

You could try eval:

cmd() {
    arg=$1
    shift
    eval "echo \$$arg"
}
Chas. Owens
This is almost exactly what I came up with just after posting echo "$(eval echo \$$arg)"
ctuffli