Linux Bash Arrays and Elements


Creating a variable is easy and very useful to make simple applications. If the variable count goes up managing variables becomes a pain. Think that if the variables count is higher than 100 how easily can be created, assigned. There is a simpler usage for multiple variables. It is called an array. An array is a variable that holds more than one value with similar types. For example, we have a script that should connect to a lot of hosts. We can use array in a single variable to hold all of the hostnames.

Creating Array inBash

Creating array is easy as variable.

$ hosts[0]="www1"
$ hosts[1]="www2"
$ hosts[2]="db"
$ hosts[3]="file"

As you see array is a variable that holds a series of data. Series are generally held in a sequential manner. There are alternative and more practical ways to define arrays. To access individual elements in an array index numbers are used. [0]is an index number that addresses the first element of the array.

$ hosts=(www1 www2 db file)

The above script will create the same array with the previous script. Spaces will be used as delimiters and 4 array elements will be added into an array with the index starting from 0. If you want to shuffle array index numbers and there is alternative syntax too. Look below

$ hosts=([2]=www1 [1]=www2 [3]=db [0]=file)

Here we create array by specifying index numbers. We set www1 element index number to 2 .

Accessing Array Data

Arrays are accessed regularly after defined. Array access is similar to variable access but there is little difference.

$ echo ${hosts[0]}

Here we access hosts arrays first element. We put an array variable and index into curly braces with dollar sign. The difference from the normal variable is we add curly braces between the dollar sign and variable name.

LEARN MORE  What is Dash / Shell / sh and How To Use It?

Getting Array Length

Arrays have multiple elements. The element count maybe 5 or 5000. Sometimes we cannot specify array element count because it is generated dynamically. So we need to know the element count.

$ echo ${#hosts[@]}
$ 4

The # and @ operators are used to get element count of an array.

Deleting Array Elements

As we see before array elements can be created in different ways. Sometimes we may need to delete specific array elements from an array. Deleting an array element is different from deleting array completely. Only specified elements are deleted and other elements stay with the same index. After deleting and element the index becomes empty.

$ unset ${names[2]}       
$ echo ${names[2]}  
$

Leave a Comment