ctuffli
ctuffli

Reputation: 3580

ASH variable indirect reference

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?

Upvotes: 3

Views: 3304

Answers (1)

Chas. Owens
Chas. Owens

Reputation: 64939

You could try eval:

cmd() {
    arg=$1
    shift
    eval "echo \$$arg"
}

Upvotes: 3

Related Questions