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"
word[@]
.