Open In App

Bash Scripting – Array

Last Updated : 13 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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. 

#!/bin/usr/env bash

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

OR

#!/bin/usr/env bash

sport[0]=football
sport[1]=cricket
sport[2]=hockey
sport[3]=basketball

The value of the elements can be any integer or strings or any other form of data as desired. We can see that the array is declared in a bash script in two ways the former seems more convenient and less hectic to declare. If we want to declare the array in one go, the former is the optimum choice but if the elements are to be added in bits and pieces the latter is a good choice. 

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.

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. 

#!/bin/usr/env bash

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

for i in ${nums[@]}
do
echo -e "$i \n"
done

As we can see we have used a for loop to print the element from the array one by one. We have used the trick in the previous section of getting all the elements of the array and iterating over it one by one in the for a loop. The  “${array_name[@]}” expands into all the elements in the array and the for loop iterates over them one by one with the iterator in the example it is the variable i, inside the body of the for loop we print the variable/iterator i and thus iterate over the array.

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[@]}”.

 #!/bin/usr/env bash

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

echo "${#sport[@]}"

We thus return the size of the array by using the command “${#sport[@]}”, the # is used to get the size of the variable next to it, using the double quotes the value of the command is evaluated and we get the number of the elements in the array as desired. 

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.

#!/bin/usr/env bash

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

echo "${sport[@]}"

sport[4]="dodgeball"
sport[2]="golf"

echo "${sport[@]}"

We have added the 5th element (4th index) into the array and also modified/edited the array’s 3rd element(2nd index). The arrayname[index]=value is all the tricks to add, modify or initialize the elements of the array.

We can also add elements to an array using the += operator. 

#!/bin/usr/env bash

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

echo "${sport[@]}"
sport+=("golf" "baseball")
echo "${sport[@]}"
echo "Size : ${#sport[@]}"

As seen in the example, we can add multiple elements to the array with minimal code. We use the array_name+=(elements) to append elements to the array. 

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.

#!/bin/usr/env bash

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

unset sport[1]
echo "${sport[@]}" 
echo "${#sport[@]}" 

As we can see unset arrayname[index] will delete the element at index from the array. Also, the size of the array has been reduced to 3 from 4 which indicates that the element is entirely removed and not just replaced with whitespace. 

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.  

#!/bin/usr/env bash

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

unset sport[-3]
echo "${sport[@]}"

As we can see index 1 is also referenced as -3 from the back and hence it becomes relatively easier to reference certain elements in a large array.

Splice an Array

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

#!/bin/usr/env bash

declare -a sport

sport+=("football" "cricket" "hockey" "basketball")
sport+=("golf" "baseball")

echo "sport = ${sport[@]}"
arr="${sport[@]:1:3}"
echo "arr = ${arr[@]}"

We have taken out a chunk from the sport array i.e. the element between index 1 and 3 inclusive and assigned it to the arr variable which is also an array. The @ operator gets all the elements from the array and then we can splice the array between indices 1 and 3 so that we have the elements at 1,2and 3 (cricket, hockey, and baseball) from the sport array.

Define a static array and print the elements of the array

#To declare static Array
programmingArray=(Java Python Ruby Perl)

#In below 2 ways we can print the elements of the static array
echo "Way 1 of printing static values by using <array>[@]:0 - " ${programmingarray[@]$
echo "Way 2 of printing static values by using <array>[*]:0 - " ${programmingarray[*]$

In 2ways we can print elements of static array

Program execution

sh <filename>

So, we can give as

sh arraycheck2.sh # arraycheck2.sh is the name of the script file here

Passing the command line arguments in a script file 

#All the array elements are stored in an array called programmingArray
programmingArray=("$@")
#Index values start from 0

#If we do not specify the index, it will take up the size of first index value
echo "Size of programmingArray at 0th location..:" $(#programmingArray[0]}

echo "Size of programmingArray at 1st location..:" $(#programmingArray[1]}

The above script can be executed as

# Here Java, Python and  Ruby are command line arguments

sh arrayCheck.sh  Java Python Ruby  

Script execution steps :

programmingArray=(Java Python  Ruby)

#Java will be present at the 0th index, its size can be computed in the below way

${#programmingArray[0]}

Similarly, Python will be present at the 1st index, its size can be computed in the below way

${#programmingArray[1]}

Output:

Iterating the array values using for loop

$@ will give all the values that got passed via command-line arguments and it is stored in an array.

It can be iterated by using the “for” loop

declare -a programmingArray=("$@")

i=0

for programming in "$@"

do

  echo "Array value at index " $i " : " $programming

  i=$((i+1));

done 

Output:

Let us take a quick look of what each and every symbol represent

Syntax

  

Output
arr=()

arr[0]=3 Overwrite 1st element

arr+=(4) Append value(s)

str=$(ls) Save ls output as a string

arr=( $(ls) ) Save ls output as an array of files

${arr[@]:s:n} Retrieve n elements starting at index

#We can provide set of values

like this

arr=(one two three) 

To initialize an array
${arr[0]} To retrieve the first element. Always index starts with 0
${arr[@]}  To retrieve all elements and thereupon we can iterate in a loop
${!arr[@]}  To retrieve array indices alone
${#arr[@]}  To calculate the size of an array
arr[2]=3  To overwrite 3rd element we need to use it this way. As the index starts at 0, arr[2] is correct.
arr+=(40)  To append value(s), we can use + and then assign with = and hence += is used.
str=$(ls)  To save “ls” command  output as a string(Example 4 is shown for this output)
arr=( $(ls) ) To save “ls” output as an array of files(Example 5 is shown for this output)
${arr[@]:s:n}  To retrieve “n” elements starting at index “s”


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads