Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASH variable indirect reference

Tags:

shell

unix

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?

like image 752
ctuffli Avatar asked Feb 16 '26 05:02

ctuffli


1 Answers

You could try eval:

cmd() {
    arg=$1
    shift
    eval "echo \$$arg"
}
like image 187
Chas. Owens Avatar answered Feb 20 '26 01:02

Chas. Owens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!