≡ Menu

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 <space><tab><newline>. You can print it with the following command:
cat -etv <<<"$IFS"
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsGNU/Bash + Unix
Estimated completion timeN/A

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

Syntax

Create a variable called ns as follows:

 
ns="ns1.cyberciti.biz ns2.cyberciti.biz ns3.cyberciti.biz"
 

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

 
OIFS="$IFS"
IFS=' '
read -a dnsservers <<< "${ns}"
 IFS="$OIFS"
 

OR use one liner as follows:

 
IFS=' ' read -a dnsservers <<< "${ns}"
 

To display values stored in an array, enter:

 
echo ${dnsservers[0]}
 

Sample outputs:

ns1.cyberciti.biz

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"
done
 
Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?

{ 5 comments… add one }

  • bAsh December 14, 2012, 9:29 pm

    You could also do:

    ns=(ns1.cyberciti.biz ns2.cyberciti.biz ns3.cyberciti.biz)
    # ${ns} becomes an array:
    echo ${ns[1]}  ${ns[2]}  ${ns[3]}
    
    • RAJ December 18, 2012, 9:32 am

      can u plz tell me all syntex and contitions for c , c++ program……

  • fufo December 16, 2012, 5:13 pm

    ns=”ns1.cyberciti.biz ns2.cyberciti.biz ns3.cyberciti.biz”

    n=0

    A=()

    for i in $ns;do A[$n]=$i; ((n++));done

    echo ${A[0]}
    ns1.cyberciti.biz
    echo ${A[1]}
    ns2.cyberciti.biz
    echo ${A[2]}
    ns3.cyberciti.biz
    echo ${A[3]}
    ns3.cyberciti.biz

  • Roger December 20, 2012, 5:21 pm

    Just FYI:

    “The default value is .”

    That stmt got messed-up in the html-formatting of your article.
    I can see in the html-code, you meant to write:
    “The default value is (space)(tab)(newline).”
    which is correct :)

Leave a Comment