You should know Arrays in Bash Scripting | 2022
You should know Arrays in Bash Scripting | 2022
What is an array?
An array is a collection of similar data elements stored at contiguous memory locations OR an Array is a way to store multiple values in the same variable.
Why do we need an array?
Suppose we are working on something where we have to store 100 names, is it going to be right to create 100 different variables and store the name into them, Obviously not we are going to use an array.
Declaring an Array
Declaring an array follows some steps:-
- Name of the array.
- Equal to sign followed by the array name. ( Note:- It should not have spaces around )
- Your array should be in Parenthesis ()
- Write the elements in quotes without giving comas.
myarray=('Element 1' 'Element 2' 'Element n')
Accessing the elements
As now we have declared the array we have to now access it, the simplest way to access all the elements of the array is:-
echo ${myarray[@]}
Where the myarray shows the name of the array and @ shows to echo of all the elements present in the array.
bash bashscript.sh
You can also echo the individual elements of the array. By providing their index values. In most programming languages, the index starts with 0.
So suppose I have to echo the 2nd Element, then I have to provide the index no 1 because the index starts with 0, Element 1 is at index 0 and element 2 is at index 1. I hope that makes sense.
echo ${myarray[1]}
There are some other ways to print the elements of the array which I am not going to cover now. We we see that in the later blogs.
Adding an Element
we can also add elements to our existing array or append an element.We have to replace Element n in our array with Element 3.
myarray[2]="Element 3"
To replace an element:-
- Name of the array.
- Followed by the index we have to replace.
- Followed by the equal to sign without gaps.
- Give the elements in the quotes.
#! /bin/bash
myarray=('Element 1' 'Element 2' 'Element n')
echo ""
echo "Array before change is:- "
echo ${myarray[@]}
echo ""
echo "Array after change is:- "
myarray[2]="Element 3"
echo ${myarray[@]}
echo ""
myarray=('Element 1' 'Element 2' 'Element n')
echo ""
echo "Array before change is:- "
echo ${myarray[@]}
echo ""
echo "Array after change is:- "
myarray[2]="Element 3"
echo ${myarray[@]}
echo ""
You don't need to add the empty echo statements I just added them for readable output.
Conclusion:-
- What is an array:- we learned array is a collection of similar data arranged in contiguous memory locations.
- Why do we need an array:- Importance of using the array and how it can save our time and efforts.
- Declaring an Array
- Accessing the elements of the array
- Replacing the elements of the array.