HowTo: Bash Shell Split String Into Array

How do I split string based on delimiter into array under Bash shell?

You need to use the $IFS. It is a special shell variable. You can change the value of IFS as per your requirements. The Internal Field Separator (IFS) that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is . You can print it with the following command:
cat -etv <<<”$IFS”

$IFS variable is commonly used with read command, parameter expansions and command substitution.

Create a variable called ns as follows:


To split $ns variable (string) into array, use the following IFS syntax:

IFS=’ ‘
read -a dnsservers <<< “${ns}”

OR use one liner as follows:

IFS=’ ‘ read -a dnsservers <<< “${ns}”

To display values stored in an array, enter:

echo ${dnsservers[0]}

Sample outputs:

Use bash for loop to iterate through array values i.e. print all elements using bash for loop syntax:

for i in “${dnsservers[@]}” do echo “$i”

Social tagging:

Comments are closed.