Deano
Deano

Reputation: 12190

bash assign variable to array elements

I'm having a trouble getting this working in bash, I have the following array

server-farm=("10.0.10.1" 10.0.10.2")

I would like to loop through this array and assign uniq variable to each element.

Desired results.

srv1 = 10.0.10.1 
srv2 = 10.0.10.2 

Is this possible?

This is what I have tried so far, but couldn't get it to work.

  for i in "${server_farm[@]}"
    do
            echo $i
  done

Thank you

Upvotes: 2

Views: 5879

Answers (1)

anubhava
anubhava

Reputation: 784958

You can use this script:

server_farm=("10.0.10.1" "10.0.10.2")

for ((i=0, j=1; i< ${#server_farm[@]}; i++, j++)); do
   declare "srv$j"="${server_farm[$i]}"
done

Test:

echo "$srv1"
10.0.10.1
echo "$srv2"
10.0.10.2

Upvotes: 1

Related Questions