How To For Loop Over CSV File Which Contains Spaces

Loops over a comma separated value file that contains spaces. This is perfect for Server Groups in Attune as the server group values are stored as as CSV’s.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# The following three lines are identical as $IFS=" "
# if $IFS="," then the line with brackets around it would generate an array
# which isn't suitable for an input for this example.
VAR=("Test 1","Test 2","Test 3","Test 4")
VAR="Test 1","Test 2","Test 3","Test 4"
VAR="Test 1,Test 2,Test 3,Test 4"

# Set the field separator to a comma,
# and echo the variables contents into the stdin of read
# tell read to produce a variable of type array
IFS=',' read -ra items <<< $VAR

# Iterate over the the indexes of the array, not the items
# This works with for, because for will split on spaces and
# the indexes don't have spaces in them, eg 1 2 3 4 5
for index in "${!items[@]}"
do
    # Dereference the index of the array,
    # This way, we get our correct value even if it has spaces in it.
    echo "Testing CSV for loop: ${items[index]}"
done

Output:

Testing CSV for loop: Test 1
Testing CSV for loop: Test 2
Testing CSV for loop: Test 3
Testing CSV for loop: Test 4

Examples

The following example will print the name, IP address, and FQDN for each of the servers in the appServers server group.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
IFS=',' read -ra ip <<< "{appServers.serverIps}"
IFS=',' read -ra fqn <<< "{appServers.serverFqns}"
IFS=',' read -ra name <<< "{appServers.serverNames}"

for i in "${!ip[@]}"
do
    echo ${name[$i]}
    echo ${ip[$i]}
    echo ${fqn[$i]}
done