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
TimeN/A
$IFS variable is commonly used with read command, parameter expansions and command substitution.

ADVERTISEMENTS

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
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
6 comments… add one
  • bAsh Dec 14, 2012 @ 21:29

    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 Dec 18, 2012 @ 9:32

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

  • fufo Dec 16, 2012 @ 17:13

    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 Dec 20, 2012 @ 17:21

    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 :)

  • todds Sep 29, 2015 @ 12:33

    As the guy above me said, space,tab,newline are the default delimiters.
    If your input string is already separated by spaces, bash will automatically put it into an array:
    ex.
    array=( H E L L O ) # you don’t even need quotes
    array[0] $ = H

    if you wanted to accept other ascii chars (say you’re converting to hex for some reason)
    array=(H E L L O “#” “!” ) #some chars you’ll want to use the quotes

    cat test.txt
    test1 test2 test3

    array=($( cat test.txt ))
    array[0] = test1

    array=($( ls directory/ )) #ls by default will output each dir on a new line, so each subdir or whatever ls returns becomes an array element

    array[0] = /home/user

    One last thing: array=( ${array[@]} “test” ) will add “test” string to an array. Say if you wanted to add the result of a bunch of different directories…
    array=( ${array[@]} “`ls /home/`” “`ls /home/user`” “`ls /proc/sys/`” ) and so on, note the ` backtics ` this time.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.