How do I use ksh for loop to iterate thought array values under UNIX / Linux / BSD operating systems?
You can define array as follows:
set -A arrayName value1 value2 value3For example, create an array called characters with three values as follows:
set -A characters Mugen Jin FuuTo print first value, enter:
echo ${characters[0]}
To print 3rd and last value, enter:
echo ${characters[2]}
To print all values, enter:
echo ${characters[@]}
To count number of items in an array called characters, enter:
echo ${#characters[@]}
You can use for loop as follows to iterate through all values:
for i in ${characters[@]}; do echo "Samurai Champloo character - $i"; done
Sample outputs:
Samurai Champloo character - Mugen Samurai Champloo character - Jin Samurai Champloo character - Fuu
You can add two more items as follows to exiting array:
characters[3]="Sunflower-Samurai" characters[4]="Detective-Manzo"
Sample Shell Script
#!/bin/ksh # set array called nameservers set -A nameservers 192.168.1.1 192.168.1.5 202.54.1.5 # print all name servers for i in ${nameservers[@] 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













{ 4 comments… read them below or add one }
If i need to print the next value in the array if a certain condition is verified
for example:
for i in “${array[@]}”
do
if(….) then
echo $(i+1)
fi
done
$(i+1) is wrong what can i do?
Hi Nisrine,
I hope my necromancing is welcome here, in case your issue is still relevant.
$(ì+1) should actually be $((i+1)), since double parentheses evaluate mathematical expressions.
I hope this helps someone!
Jason
Thank you for ur reply! working!
Excellent just what i needed for looping through an array