1

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[@]}
2
  • What is your bash version? Commented Jul 13, 2017 at 21:51
  • GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) Commented Jul 13, 2017 at 21:52

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

declare -n array=$1 works fine. thanks
1

Make the [@] part of your indirection:

a=(1 2 3)

myfunction() {
  array="$1[@]"
  echo "${!array}"
}

myfunction a

2 Comments

I have so many arrays in my script. So set -- a may not scale well in my case :) But I get the logic behind your commands. Thanks.
@pdna This is just how you set $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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.