3

When i write a script named array_call_self.sh as follows

#!/bin/bash
declare -A num word
word=(
 [a]='index_a'
 [b]='index_b'
 [c]='index_c'
)
num=(
 [a]=1
 [b]=2
 [c]=3
)
array=${$1[@]}
for i in ${$array[@]};do
  echo $i
done

when i run bash array_call_self.sh word it return me

test.sh: line 13: ${$1[@]}: bad substitution
test.sh: line 14: ${$array[@]}: bad substitution
3
  • 1
    The error messages don't seem to match the code. I get the output word[@].
    – Bodo
    May 10 at 13:55
  • @Bodo Because they show a slightly modified script compared to what outputs the errors. You would get those errors by adjusting the expansions on lines 13 and 14 to the way shown in the errors.
    – Kusalananda
    May 10 at 14:13
  • 1
    @HunterLiu, you're asking for help from unpaid strangers in the internet: the least you could do to make helping you easier, would be to post code that shows your issue and matches the results/errors you say you get. I fixed that for you, this once.
    – ilkkachu
    May 10 at 14:35

1 Answer 1

5

It looks like you may want to use a name reference variable (available in bash release 4.3 or later):

#!/bin/bash

declare -A num word

word=(
 [a]='index_a'
 [b]='index_b'
 [c]='index_c'
)

num=(
 [a]=1
 [b]=2
 [c]=3
)

declare -n var="$1"

printf '%s\n' "${var[@]}"

This declares the variable var as a name reference variable, referencing the variable named by the first argument to the script. If the first argument is not a valid name of a variable, or if it's the name var, then you will get an error.

After declaring var and assigning it the variable's name, accessing the value(s) of var is done as you would ordinarily access the values of the named variable.

Note that supplying the name of a variable on the command line of a script is highly unusable and that you instead might want to hide such implementation details and restrict the valid arguments to a limited list, possibly through doing proper command-line parsing. The code above allows the script user to output any of the script's variables.

A simplistic way of restricting the values to a limited list:

case $1 in
        (word|num) ;; # ok
        (*)
                echo 'error' >&2
                exit 1
esac

declare -n var="$1"
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.