Bash – Loop Through Variables

bashshell-script

I am writing a bash script to use rsync and update files on about 20 different servers.

I have the rsync part figured out. What I'm having trouble with is going through a list of variables.

My script thus far look like this:

#!/bin/bash
SERVER1="192.xxx.xxx.2"
SERVER2="192.xxx.xxx.3"
SERVER3="192.xxx.xxx.4"
SERVER4="192.xxx.xxx.5"
SERVER5="192.xxx.xxx.6"
SERVER6="192.xxx.xxx.7"

for ((i=1; i<7; i++))
do
    echo [Server IP Address]
done

Where [Server IP Address] should be the value of the associated variable. So when i = 1 I should echo the value of $SERVER1.

I've tried several iterations of this including

echo "$SERVER$i"    # printed the value of i
echo "SERVER$i"     # printer "SERVER" plus the value of i ex: SERVER 1 where i = 1
echo $("SERVER$i")  # produced an error SERVER1: command not found where i = 1
echo $$SERVER$i     # printed a four digit number followed by "SERVER" plus the value of i
echo \$$SERVER$i    # printed "$" plus the value of i

It has been a long time since I scripted so I know I am missing something. Plus I'm sure I'm mixing in what I could do using C#, which I've used for the past 11 years.

Is what I'm trying to do even possible? Or should I be putting these values in an array and looping through the array? I need to this same thing for production IP addresses as well as location names.

This is all in an effort to not have to repeat a block of code I will be using to sync the files on the remote server.

Best Answer

Use an array.

#! /bin/bash
servers=( 192.xxx.xxx.2 192.xxx.xxx.3
          192.xxx.xxx.4 192.xxx.xxx.5
          192.xxx.xxx.6 192.xxx.xxx.7
)

for server in "${servers[@]}" ; do
    echo "$server"
done
Related Question