2

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

2
  • 3
    Why do you want to assign each value to a different variable? There's no need to do that. Use the array directly. ${server_farm[0]} is the first entry, ${server_farm[1]} is the second, etc. Commented Feb 19, 2015 at 20:27
  • bash variables can't have hyphens in their names. So your array assignment is a bit suspect to begin with... Commented Feb 19, 2015 at 21:49

1 Answer 1

1

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

2 Comments

Thanks very much, what is the meaning of the # before server_farm? Just curious to know, thanks
${#server_farm[@]} gives us count of array elements

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.