I have few arrays in my script
a=(1 2 3)
b=(3 4 5)
User inputs which list he wants to print out.
./array.sh a
How do I print the elements of array?
I have tried doing the following and couldn't print
array=$1
echo ${!array[@]}
I have few arrays in my script
a=(1 2 3)
b=(3 4 5)
User inputs which list he wants to print out.
./array.sh a
How do I print the elements of array?
I have tried doing the following and couldn't print
array=$1
echo ${!array[@]}
You can use declare -n for named reference of your variables like this:
a=(1 2 3)
b=(3 4 5)
declare -n arr="${1?need an array name}"
printf "%s\n" "${arr[@]}"
Then execute it as:
./array.sh a
1
2
3
./array.sh b
3
4
5
declare -n array=$1 works fine. thanksMake the [@] part of your indirection:
a=(1 2 3)
myfunction() {
array="$1[@]"
echo "${!array}"
}
myfunction a
set -- a may not scale well in my case :) But I get the logic behind your commands. Thanks.$1 from within the script to make it self-contained and runnable. It's easier to copy-paste and reproduce than having to create a script and run it with certain parameters. I changed it to set it via a function instead