Linux Bash Arrays and Elements

[rps-include post=6835]

Creating variable is easy and very useful to make simple applications. If the variable count goes up managing variables becomes 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 array.

An array is a variable that holds more than one value with similar types. For example we have script that should connect a lot of hosts. We can use array in a single variable to hold all of the host names.

Creating Array

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 series of data. Series are generally hold in a sequential manner. There is alternative and more practical ways to define arrays. To access individual element in an array index numbers are used. [0]is an index number that address first element of the array.

$ hosts=(www1 www2 db file)

Above script will create same array with previous script. Spaces will used as delimiters and 4 array element will be added into array with 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 array variable and index into curly braces with dollar sign.The difference from normal variable is we add curly braces between dollar sign and variable name.

LEARN MORE  Javascript Regular Expression Operation

Getting Array Length

Arrays have multiple elements. The element count may be 5 or 5000. Sometimes we cannot specify array element count because it is generated dynamically. So we need to know 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 element from array. Deleting an array element is different from deleting array completely. Only specified elements are deleted and other element stay with same index. After deleting and element the index becomes empty.

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

[rps-include post=6835]

Leave a Comment