Printing the Arrays

After declaring the array, if we wanted to display all the elements in the array we can use the @ symbol. 

#!/bin/usr/env bash

declare -a sport=(
[0]=football
[1]=cricket
[2]=hockey
[3]=basketball
)

echo "${sport[@]}"

echo "${array_name[@]}"  

We use the [@] as an index to the array to display all the elements. All the elements are printed with space-separated, The quotes around the variable expands and print all the elements in the array.

Bash Scripting – Array

Arrays are important concepts in programming or scripting. Arrays allow us to store and retrieve elements in a list form which can be used for certain tasks. In bash, we also have arrays that help us in creating scripts in the command line for storing data in a list format. In this article, we will understand the basics of arrays in bash scripting.

Similar Reads

Creating Arrays

To create a basic array in a bash script, we can use the declare -a command followed by the name of the array variable you would like to give....

Printing the Arrays

After declaring the array, if we wanted to display all the elements in the array we can use the @ symbol....

Iterating over the Array

To iterate over an array one element at a time, we can use loops and perform any operations within the body of it....

Get the number of elements in the Array

To fetch the number of the elements array we can use the # operator before the array name in the s in  “${array_name[@]}”....

Inserting an element into Array

To insert an element is quite straightforward, we need to set the element’s appropriate index followed by the value of the element you liked to give....

Deleting an element from Array

To delete an element from the array, we can use the command unset. The command takes in the name of the variable in our case the array name and the index of that element. The index can also be relative i.e. -1 indicating the last element and -2 to second last and so on....

Using relative indices

If we use indices like -1,-2, and so on, the elements are referenced from the last element, and hence we can delete or modify them with relative ordering from the back as well....

Splice an Array

We can splice(take out a potion) an array to take assign or print it to another variable/array....