UNIX Tutorials, Tips, Tricks and Shell Scripts

Korn Shell Arrays - Assigning and Accessing Values - Part I

Another type of variable supported by the Korn shell is the array. Briefly, an array contains a collection of values (elements) that may be accessed individually or as a group. Although newer versions of the Korn shell support more than one type of array, this tip will only apply to indexed arrays.

When assigning or accessing array elements, a subscript is used to indicate each element's position within the array. The subscript is enclosed by brackets after the array name:


The first element in an array uses a subscript of 0, and the last element position (subscript value) is dependent on what version of the Korn shell you are using. Review your system's Korn shell (ksh) man page to identify this value.

In this first example, the colors red, green, and blue are assigned to the first three positions of an array named colors:

$ colors[0]=RED
$ colors[1]=GREEN
$ colors[2]=BLUE

Alternatively, you can perform the same assignments using a single command:

$ set -A colors RED GREEN BLUE

Adding a dollar sign and an opening brace to the front of the general syntax and a closing brace on the end allows you to access individual array elements:


Using the array we defined above, let's access (print) each array element one by one:

$ print ${colors[0]}
$ print ${colors[1]}
$ print ${colors[2]}

If you access an array without specifying a subscript, 0 will be used:

$ print ${colors[]}

The while construct can be used to loop through each position in the array:

$ i=0
$ while [ $i -lt 3 ]
> do
> print ${colors[$i]}
> (( i=i+1 ))
> done

Notice that a variable (i) was used for the subscript value each time through the loop.

Do you need to learn Korn shell scripting and get practice writing & running scripts...on a REAL SERVER? If you are ready to move past the basics, either of these online courses is a good place to start...

UNIX and Linux Operating System Fundamentals contains a very good "Introduction to UNIX Shell Scripting" module, and should be taken if you are new to the UNIX and Linux operating system environments or need a refresher on key concepts.

Korn Shell Scripting is a good option if you are already comfortable with UNIX or Linux and just need to sharpen your knowledge about shell scripting and the Korn shell in general.

Both courses include access to an Internet Lab system for completing the course's hands-on exercises, which are used to re-enforce the key concepts presented in the course. Any questions you may have while taking the course are answered by an experienced UNIX technologist.

Thanks for reading, and happy scripting!!!

Has this article been helpful to you? Would it benefit others? If you answered "yes" to either question, kindly share the page.

Thank you for sharing!