Do you think IIT Guwahati certified course can help you in your career?
No
Introduction😎
In this tutorial, we will see how to use arrays in Linux, but before a discussion about arrays, let’s first get familiar with Linux.
Linux is an open-source community like the Unix operating system. The initial release of Linux was on September 17, 1991, by Linus Torvalds. Since its release, Linux has been used everywhere, whether on smartphones, watches, or supercomputers. It is quite a helpful tool for regular computer users or developers.
This article will discuss the ways of using arrays in Linux. What are the different ways of declaring and accessing an array? And at last, we will perform various operations like search, count, and delete elements from Linux Arrays.
Need of Using Arrays
In shell scripting, arrays are variables that hold multiple values of the same or different type.
Confused!!!😕 Yes, you are right that the Array holds data of a similar type. But, in Linux, everything is treated as a string, so any type of data can be stored using arrays in Linux.
The need for this data type arises when we have a large number of values to store. Let's say we have 500 different values, and if we create 500 variables for each of them, then it becomes complicated to perform operations on them. So, using arrays in such cases is considered the best choice. We can access these values via the index number of Linux arrays that starts with zero.
Let's now discuss different ways in which we can declare Linux arrays.
Defining Arrays
There are different ways of using arrays in Linux. These are:
Explicit Declaration:
First, declare the Array and assign its values later. This can be done using the 'declare' keyword, followed by the '-a' option and the array name. This will create an empty array. SYNTAX -
declare -a <array_name
Indirect Declaration:
In this type of declaration, values are assigned to a particular index number without any pre-declaration of the array. The syntax is:
<array_name>[<index_number>]=<value>
Compound Declaration:
Declare the Array with a bunch of values. You can also add new values later. SYNTAX -
We can also combine explicit and compound declarations. In this, we define an array using declare keyword and assign values. Unlike explicit declaration, this will not create an empty array. SYNTAX -
declare -a <array_name> = ( <value1> <value2> <value3> ... )
In all the above syntax, replace
<array_name> = name of array variable <index_number> = index value of the element (position) <value> = The actual element value.
After declaration, we must be familiar with the ways in which we can access the array elements. As to use to perform various operations data we must know how that data will be printed on the screen. So, below we have discussed different ways in which we can print array elements.
Print All Elements:
In shell scripting, [@] and [*] symbolizes all the elements of an array. So, to print all the elements, type:
echo ${<Array_name>[@]}
OR
echo ${<Array_name>[*]}
Print Element at Given Index:
Array elements are associated with index numbers. So, to access an element at a given index, we need to specify that index in the following way:
echo ${<Array_name>[INDEX]}
Moreover, to print the first element, we don't need to mention any index number. Just type : echo ${<Array_name>}
Print Elements in a Range:
To print elements starting from an index to 'N' number of elements. The syntax is:
To print index numbers of the array, we use the not (!) operator. The syntax is:
echo ${!<Array_name>[@]}
Example:
# Define array
array=("Coding" "Ninja" "is" "Best")
# Print all elements of array
echo "Elements using @ = ${array[@]}"
echo -e "Elements using * = ${array[*]}\n"
# Print element at a given index
echo -e "Element at index 3 : ${array[3]}\n"
# Print first element
echo -e "First Element : ${array}\n"
# Print in range, starting from index 1
echo -e "Elements in range : ${array[@]:1:2}\n"
# Get index of array
echo "Index numbers = ${!array[@]}"
Output:
Count Array Length
While using arrays in Linux, sometimes we need to calculate their length. So to calculate the length of either a particular element or a whole array, the '#' symbol is used.
At Particular Index:
To count the length of an element at a given index, the syntax is:
echo ${#<Array_name>[<index_number>]}
Whole Array:
To count the length of the whole array, the syntax is:
echo ${#<Array_name>[@]}
Example:
# Declare an array
declare -a array=("Coding" "Ninja" "is" "Best")
# Length of element at index 1
echo -e "Length of word 'NINJA' = ${#array[1]}\n"
# Length of array
echo "Length of declared array = ${#array[@]}"
Output:
Search and Replace Array Element
To search for a pattern of elements present in the array and make changes in it by replacing it with different patterns, following syntax can be used:
Only Search => /*[pattern]*/ =>
Used to search all the characters in the pattern from the given array. This returns all the words that don't match the pattern. Also, it does not alter the original array.
Search and Replace => //Search_pattern/Replace_pattern =>
Searching the elements that matches with the given search_pattern and replace it with the given replace_pattern. This does not alter the original array; instead, a new array value is created that can be stored in the same or new array.
Example:
# Declare Array
arr=("Array" "store" "Multiple" "Elements")
# Only search
echo "Elements in which 's and t' is not present : "
echo -e "${arr[@]/*[st]*/}\n"
# Search and Replace
echo -e "Array before replace : ${arr[@]}"
# Replacing ‘t’ with ‘T’ in whole array
echo -e "Array after replace : ${arr[@]//t/T}\n"
# Search and Replace a particular index
echo -e "Value at index 2 before replace : ${arr[2]}"
# Replacing ‘ple’ with ‘plus’ at particular index
echo -e "Value at index 2 after replace : ${arr[2]//ple/plus}"
Output:
Delete Array Value
The 'unset' keyword is used to delete either the element present at an index or a whole array.
The syntax to delete the element at an index:
unset <array_name>[index_number]
The syntax to delete a whole array:
unset <array_name>
Example:
# Declare array
array=("ONE" "TWO" "THREE" "FOUR")
# Delete the element at index 2
echo "Array before delete = ${array[@]}"
unset array[2]
echo "Array after delete = ${array[@]}"
# Delete the whole array
unset array
echo -e "\nAfter deletion : ${array[@]}"
Output:
Different Types of Loops
An array consists of multiple elements and sometimes we need to iterate through each element. If we use the index number of each element individually then the task becomes very complicated and lengthy. For such cases, the concept of loops came into use. In Linux, there are two types of loops. These are
For Loop: This is used for the repetition of a process. The syntax is
Example:
Let’s see an example to iterate over an array for doing the sum of array elements using for loop.
# Declare an array
arr=(1 2 3 4 5)
# Declare sum variable
sum=0
# Loop to iterate over array
for i in ${arr[@]}
do
# Add each element to sum variable
sum=`expr $sum + $i`
done
# Print resultant sum
echo "Sum of array elements = $sum"
Output:
While Loop: This loop also us to perform tasks repeatedly until and unless a particular condition occurs. The syntax for the while loop is as follows:
If the result of the command is true, the statements inside the loop will execute; otherwise, the program will jump to the line given after the ‘done’ statement.
Example:
For better understanding, let’s have a look at an example to print an array element using a while loop.
# Declare an array
arr=(1 2 3 4 5)
# Declare iterating variable
i=0
# Find length of array
len=${#arr[@]}
echo "Element in the array : "
# Start while loop until i < len
# -lt = less then command
while [ $i -lt $len ]
do
# Print array element
echo ${arr[$i]}
# Increment the value of i
i=`expr $i + 1`
done
Output:
These are the main operation performed while using arrays in Linux. Let's now discuss some frequently asked questions related to our topic.
Frequently Asked Questions
What are arrays?
In shell scripting, arrays are variables that hold multiple values of the same or different type.
Can we add more elements after the array declaration?
Yes, we can use '+=' for appending new elements. The syntax for the same is <array_name>+=<value>
What are the different operations performed while using arrays in Linux?
The primary operations performed are: Create, display, count, search, replace and delete.
Who introduced Linux, and in which year?
The initial release of Linux was on September 17, 1991, by Linus Torvalds.
What is the use of the echo command?
The ‘Echo’ command prints the given text on the screen as output.
Conclusion
In this blog, we learned different ways of using arrays in Linux. In this article, we first discussed the need to use arrays, followed by how to define, access, count their length, perform search and replace operations, and delete elements and whole arrays.
If you found this blog has helped you enhance your knowledge about using arrays in Linux, and if you want to learn articles like this, check out our articles below: