AKA*_*KA4 3 bash variable associative-array
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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[@]}"
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)