Array Basics in Shell Scripting | Set 1
Last Updated :
08 Apr, 2024
Consider a situation if we want to store 1000 numbers and perform operations on them. If we use a simple variable concept then we have to create 1000 variables and perform operations on them. But it is difficult to handle a large number of variables. So, it is good to store the same type of values in the array and then access via index number.
Understanding Arrays in Shell Scripting
An array is a structured arrangement of similar data elements. Within shell scripting, an array is a variable that holds multiple values, whether they are of the same type or different types. It’s important to note that in shell scripting, everything is treated as a string. Arrays adhere to a zero-based index, which signifies that indexing initiates from 0.
How to Declare Array in Shell Scripting?
Arrays can be declared in a shell script using various approaches:
1. Indirect Declaration
In this method, you assign a value to a specific index of the array variable. There’s no need to declare the array beforehand.
ARRAYNAME[INDEXNR]=value
2. Explicit Declaration
With explicit declaration, you first declare the array and then assign values to it.
declare -a ARRAYNAME
3. Compound Assignment
This method involves declaring the array along with its initial set of values. You can later add additional values to the array.
ARRAYNAME=(value1 value2 .... valueN)
Alternatively, you can use index numbers to assign values explicitly:
ARRAYNAME=([1]=10 [2]=20 [3]=30)
Printing Array Values in Shell Script:
To display array elements, you have several options:
Here is a `array_test.sh`script explaining multiple options. (You can create script with any name)
#!/bin/bash
# To declare a static Array
arr=(“Jayesh” “Shivang” “1” “Vipul” “Nishant” “2”)
# To print all elements of the array
echo “All elements of the array:”
echo “${arr[@]}”
echo “${arr[*]}”
# To print the first element
echo “The first element:”
echo “${arr[0]}”
# To print a selected index element
selected_index=3
echo “Selected index element at index $selected_index:”
echo “${arr[$selected_index]}”
# To print elements from a particular index
echo “Elements from a particular index:”
echo “${arr[@]:2}” # Prints elements starting from index 2
echo “${arr[*]:2}” # Prints elements starting from index 2
# To print elements in a range
echo “Elements in a range:”
echo “${arr[@]:1:3}” # Prints elements from index 1 to 3
echo “${arr[*]:1:3}” # Prints elements from index 1 to 3
Explanation:
- Array Declaration: An array named
arr is declared, containing six elements. These elements are strings: “prakhar”, “ankit”, “1”, “rishabh”, “manish”, and “abhinav”.
- Printing All Elements:
echo "All elements of the array:": A message is printed to indicate that all elements of the array are being displayed.
${arr[@]}: This syntax is used to print each element of the array separately. It displays all elements in the array.
${arr[*]}: Similar to the previous line, this syntax prints all elements of the array as a single string.
- Printing the First Element:
echo "The first element:": A message is printed to indicate that the first element of the array is being displayed.
${arr[0]}: This syntax retrieves and displays the first element of the array. In Bash, array indexing starts at 0.
- Printing a Selected Index Element:
selected_index=3: A variable named selected_index is assigned the value 3. This variable represents the desired index in the array.
echo "Selected index element at index $selected_index:": A message is printed to indicate the selected index.
${arr[$selected_index]}: Using the value stored in selected_index, this syntax retrieves and displays the element at the specified index (index 3 in this case).
- Printing Elements from a Particular Index:
echo "Elements from a particular index:": A message is printed to indicate that elements from a specific index are being displayed.
${arr[@]:2}: This syntax extracts and displays all elements starting from index 2 in the array. It prints each element separately.
${arr[*]:2}: Similar to the previous line, this syntax displays the elements as a single string, starting from index 2.
- Printing Elements in a Range:
echo "Elements in a range:": A message is printed to indicate that elements within a specified range are being displayed.
${arr[@]:1:3}: This syntax extracts and displays elements starting from index 1 up to index 3 (inclusive). It prints each element separately.
${arr[*]:1:3}: Similar to the previous line, this syntax displays the extracted elements as a single string.

Array Basics
Here is a `array_test2.sh` script with few other examples. (you can create script with any name)
#!/bin/bash
# Declare a static Array
arr=(“Jayesh” “Shivang” “1” “rishabh” “Vipul” “Nishtan”)
# Count the length of a particular element in the array
element_length=${#arr[2]}
echo “Length of element at index 2: $element_length”
# Count the length of the entire array
array_length=${#arr[@]}
echo “Length of the array: $array_length”
# Search in the array
search_result=$(echo “${arr[@]}” | grep -c “Jayesh”)
echo “Search result for ‘Jayesh’: $search_result”
# Search and replace in the array
replaced_element=$(echo “${arr[@]/Shivang/SHIVANG}”)
echo “Array after search & replace: ${replaced_element[*]}”
# Delete an element in the array (index 3)
unset arr[3]
echo “Array after deletion: ${arr[*]}”
Explanation:
- Array Declaration:
- An array named
arr is declared, containing six elements.
- These elements are strings: “Jayesh”, “Shivang”, “1”, “rishabh”, “Vipul”, and “Nishtan”.
- Printing Element Length:
- The length of the element at index 2 of the array is calculated using
${#arr[2]}.
- This length is stored in the variable
element_length.
- Printing Array Length:
- The length of the entire array is calculated using
${#arr[@]}.
- This length is stored in the variable
array_length.
- Searching in the Array:
- The
grep command is used to search for occurrences of the string “Jayesh” in the array ${arr[@]}.
- The
-c flag is used to count the number of occurrences.
- The count is stored in the variable
search_result.
- Searching and Replacing in the Array:
- A search and replace operation is performed on the array
${arr[@]}.
- The string “Shivang” is replaced with “SHIVANG”.
- The updated array is stored in the variable
replaced_element.
- Deleting an Element from the Array:
- The
unset command is used to delete the element at index 3 (which is “rishabh”) from the array ${arr[@]}.
- Printing All Elements:
- The message “All elements of the array:” is echoed.
${arr[@]} syntax is used to print each element of the array separately. This displays all elements in the array.

Array Basics
Conclusion
In this article we discussed about utility of arrays in shell scripting. It underlines how arrays efficiently handle a multitude of values, replacing numerous variables. The concept of array declaration is explained through three methods: indirect, explicit, and compound assignment. The article further illustrates printing array elements using practical script examples. This discussion not only demystifies array usage but also underscores its significance in managing and manipulating data within shell scripts.
Master DevOps and also get 90% Course fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.
The most sought-after Three 90 challenge has started and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!
Similar Reads
Shell Scripting - Difference between Korn Shell and Bash shell
Korn Shell: Korn Shell or KSH was developed by a person named David Korn, which attempts to integrate the features of other shells like C shell, Bourne Shell, etc. Korn Shell allows developers to generate and create new shell commands whenever it is required. Korn shell was developed a long year back as it is older than the BASH shell and it has f
3 min read
Array Basics Shell Scripting | Set 2 (Using Loops)
It is recommended to go through Array Basics Shell Scripting | Set-1 Introduction Suppose you want to repeat a particular task so many times then it is a better to use loops. Mostly all languages provides the concept of loops. In Bourne Shell there are two types of loops i.e for loop and while loop. To Print the Static Array in Bash 1. By Using whi
3 min read
Introduction to Linux Shell and Shell Scripting
If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understanding shell scripting we have to get familiar with th
8 min read
Shell Scripting - Default Shell Variable Value
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Interactive and Non-Interactive Shell
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Shell Variables
A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing
6 min read
Shell Scripting - Restricted Shell
Shell is one of the most important and powerful tools available in GNU/Linux-based systems. One can control the entire system if used correctly, this exact feature makes the shell a double-edged sword. It can potentially harm the system if one executes a system command without knowing its underlying details and consequences. To prevent this we use
5 min read
Shell Scripting - Shell Signals Values
Prerequisites: Processes, Bash Scripting, Shell Function Library Signals help the operating system to communicate with processes and vice-versa. Signals are also generated when processes don't function properly or try to access prohibited memory. Different signals are mapped to different numbers which are referred to as signal values. The Linux OS
6 min read
Shell Script to Show the Difference Between echo â$SHELLâ and echo â$SHELLâ
In shell scripting and Linux, the echo command is used to display text on the terminal or console. When used with the $SHELL variable, which contains the path of the current user's shell program, the output of the echo command can be different depending on whether the variable is enclosed in single or double quotes. echo "$SHELL" will expand the $S
4 min read
Shell Scripting - Set Command
The `set` command in shell scripting is a powerful tool that used for controlling the behavior of the shell and the environment in which scripts run. It allows the users to modify the shell options and positional parameters which facilitates providing greater control over script execution and debugging. Understanding the `set` command is essential
6 min read