How to use array in bash script
An array is a data structure used to store a sequence or series of data elements in one variable. Data elements in an array can be accessed or modified via indexing.
In this shot, we will learn how to use arrays in bash scripting.
Indexing is used to enable speedy and efficient look ups. Without indexing, the entire array would have to be traversed to gain access to the last element.
To run a bash script, you must save the text-file containing your code as a .sh file and add the following line at the beginning of your program:
#!/bin/bash
Bash stands for the Bourne-Again Shell, which will be used to execute this program.
Syntax
To declare an array, the following syntax is used:
declare -a array_name
The declare keyword is used to create variables in the Bourne-Again Shell. The -a directive specifies that our array will be indexed. array_name serves as the identifier of our array.
Array operations
After an array has been declared, insertions can be made to it.
Insertions can be performed via indexing. The following code snippet inserts the character "A" into the 0th index of the array named sample_array.
sample_array[0]="A"
Insertions can also be performed directly. The following snippet inserts the characters "A" and "B" at the 0th and 1st index of sample_array, respectively.
sample_array=("A" "B")
Array elements can be printed using the echo function. The piece of code below prints the value at the 0th index of sample_array.
echo ${sample_array[0]}
Example
We can either perform insertion via indexing or by directly inserting all the data elements together.
Here is a live demo to demonstrate how to declare an array and insert the values shown in the list in a real, working program with and without indexing.
To print array values, we use echo. We can either print data elements one by one through indexing, or we can pass @ instead to print all the values of the array.
Indexes usually start with 0, which refers to the first element, and end with
length(array)-1, which refers to the last element in the array:
#!/bin/bashdeclare -a filled_with_indexing #declares first arrayfilled_with_indexing[0]="A" #fills array using indexingfilled_with_indexing[1]="B" #fills array using indexingfilled_with_indexing[2]="C" #fills array using indexingfilled_with_indexing[3]="D" #fills array using indexingdeclare -a filled_without_indexing #declares second arrayfilled_without_indexing=("A" "B" "C" "D") #fills it all at onceecho "Printing all the values of the array filled without using indexing using @."echo ${filled_without_indexing[@]} #prints all values at onceecho "Printing all the values of the array filled using indexing one by one."echo ${filled_with_indexing[0]} #prints values one by oneecho ${filled_with_indexing[1]}echo ${filled_with_indexing[2]}echo ${filled_with_indexing[3]}
Free Resources