Bash Script – Split a Variable into an Array with Carriage Return Line Feed as the Delimiter

Once again I ran into a situation where I was working on an extremely outdated server and the read command didn’t have the -a option to send contents into an array, so this is the solution I came up with.

# Get DNS Resolvers Array Example

# This will grab nameservers while ignoring commented ones
SERVERS=$( grep 'nameserver' /etc/resolv.conf | grep -v '#' | awk -F'"' '{ print $2 }' )

# Set Internal Field Separator

# Pipes output of variable to SED, convert CRLF to spaces, put in array
SERVERS_ARRAY=($( echo $SERVERS | sed ':a;N;$!ba;s/\r\n/ /g' ))

Leave a Reply