Bash Script Arrays
In Bash Script, an array is a special type of variable that contains multiple values. The following string variable, ‘PNAME’, has been defined and initialised with the name ‘Bob’.
PNAME=Bob
If multiple names need to be stored, instead of having a different variable for each, an array could be used.
PNAME[0]="Bob" PNAME[1]="George" PNAME[2]="Fred" PNAME[3]="Alan"
Each element in an array has an index number, which is used above to populate the four elements. Notice that the first index number is a zero and not a one. It should also be noted that if the index number already exists in the array, then this would have the effect of updating that element.
The initialisation of an array can be shortened by combining into one statement.
PNAME=("Bob" "George" "Fred" "Alan")
As well as being able to use the index number to populate a particular element in an array, it can also be used to extract the value of an element in an array, in order to carry out a particular task, or simply just to display it.
echo ${PNAME[2]}
Here, the element with an index number of two would be displayed, in this case “Fred”.
In order to display all of the elements in an array a ‘for’ loop can be used.
for I in ${PNAME[@]} do echo "$I" done
The variable 'I' is used to hold the current value of the array as the ‘loop iterates over it, which is displayed in the terminal.
Bob George Fred Alan
If it is required to find out the number of elements within an array, this can be achieved as follows.
echo ${#PNAME[@]}
Due to index numbers starting at zero, this can be used to add a new element on to the end of the array.
PNAME[${#PNAME[@]}]="Alice"
As well as being able to add values to the end of an array using the next available index number, it is also possible to achieve the same results using the '+=' operator. This can be used to add single or multiple values to the end of the array.
PNAME+=("Alice")
PNAME+=("Andrew" "Eve")
One final use of the index number is in removing the corresponding value, in conjunction with the 'unset' command.
unset PNAME[2]
This will remove the third element from the array.