1

is it possible to create a loop that makes associative arrays in bash?
I would like something along these lines....

number_of_servers=10;
COUNTER=1

while [  $COUNTER -le ${number_of_servers} ]; do
  declare -A "server_${COUNTER}"
  COUNTER=$((COUNTER+1))
done

many thanks !

5
  • 1
    Did you try it? It does exactly what you want. (Although you could do that rather more simply with declare -A server_{1..10} ) Commented Jul 14, 2017 at 16:43
  • thanks - that helps a lot - before I was declaring 100 arrays in a file and sourcing that !! However, is there a way to dynamically input the number_of_servers variable. I tried declare -A server_{1...${number_of_servers}} but it failed. Commented Jul 14, 2017 at 17:08
  • The curly brace notation doesn't allow for variables. If you want a variable range, you're back to using a loop. You could get around this with eval, but personally I try to steer clear of eval. Commented Jul 14, 2017 at 17:12
  • 1
    @MikeHolt (and JRD); you can do without eval. For example, declare -A $(printf 'server_%d ' $(seq 1 $number_of_servers)). (Note the space in the printf format.) But if you are going to use a loop, use a for loop: for ((i=1;i<=number_of_servers;++i)); do declare -A server_$i; done Commented Jul 14, 2017 at 17:23
  • @rici haha, you beat me to the punchline. I was just testing that exact solution on my machine to verify that it works. Had to look up how to verify that an array has successfully been declared. The usual syntax for checking if a variable is set doesn't work because bash doesn't technically create the array until the first assignment, thus declare -A foo is only assigning an attribute to the name foo. But I found declare -p for checking if something has been declared. Commented Jul 14, 2017 at 17:26

1 Answer 1

0

Your code already works:

$ for index in 1 2
> do
>     declare -A "server_${index}"
> done
$ declare -p server_1
declare -A server_1
$ declare -p server_2
declare -A server_2

You can simplify it like @rici pointed out:

$ declare -A server_{3..4}
$ declare -p server_4
declare -A server_4

Or dynamically declare it:

$ number_of_servers=10
$ declare -A $(printf 'server_%d ' $(seq "$number_of_servers"))
$ declare -p server_10
declare -A server_10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.