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"
$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
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 5 comments… read them below or add one }
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]}can u plz tell me all syntex and contitions for c , c++ program……
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
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 :)
Thanks for the heads up!