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# The following three lines are identical as $IFS=" "
 2# if $IFS="," then the line with brackets around it would generate an array
 3# which isn't suitable for an input for this example.
 4VAR=("Test 1","Test 2","Test 3","Test 4")
 5VAR="Test 1","Test 2","Test 3","Test 4"
 6VAR="Test 1,Test 2,Test 3,Test 4"
 7
 8# Set the field separator to a comma,
 9# and echo the variables contents into the stdin of read
10# tell read to produce a variable of type array
11IFS=',' read -ra items <<< $VAR
12
13# Iterate over the the indexes of the array, not the items
14# This works with for, because for will split on spaces and
15# the indexes don't have spaces in them, eg 1 2 3 4 5
16for index in "${!items[@]}"
17do
18    # Dereference the index of the array,
19    # This way, we get our correct value even if it has spaces in it.
20    echo "Testing CSV for loop: ${items[index]}"
21done

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.

 1IFS=',' read -ra ip <<< "{appServers.serverIps}"
 2IFS=',' read -ra fqn <<< "{appServers.serverFqns}"
 3IFS=',' read -ra name <<< "{appServers.serverNames}"
 4
 5for i in "${!ip[@]}"
 6do
 7    echo ${name[$i]}
 8    echo ${ip[$i]}
 9    echo ${fqn[$i]}
10done