Simple Array Example in Shell Script

Array stores the number of values having the same data type. Instead of creating number of variables to store values, one array can be created and multiple values can be stored in that particular array. Integers and Strings are two different data types thus ’1′ and ‘Chris’ cannot be in a same array. Newer version of Bash supports array. If you are new to shell scripting, first visit our shell scripting category. In this tutorial, I am going to show you how to work with an array.

Let’s take an very simple example:

arrayName=(freshtutorial linux tips tricks)

Here “arrayName” is the name of an array. The words inside the small brackets are called elements. Each element are stored in a location called a array index. Array index always starts from 0. Thus in the above array:

arrayName[0]=freshtutorial

arrayName[1]=linux

arrayName[2]=tips

arrayName[3]=tricks

Now that we have created an array, let’s see how it works. I am going to retrieve the element from the array we created. While retrieving the element we need to specify the array index. The syntax is:

echo ${arrayName[array_index]}

The full script is:

#!/bin/sh
arrayName=(freshtutorial linux tips tricks)
echo ${arrayName[1]}

Yes, this script will print “linux” as “linux” have the array index 1. The output is:

array output

 

0saves
Posted in Shell Scripting | Tagged , , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>