Open In App

Array Basics in Shell Scripting | Set 1

Last Updated : 18 Nov, 2025
Comments
Improve
Suggest changes
20 Likes
Like
Report

When you need to store multiple, related values like a list of 100 filenames or 10 server names you could create 100 different variables. This is messy and impossible to manage.

The solution is an array. An array is a single variable that can hold multiple values as an ordered list.

You will use arrays to:

  • Store a list of items (e.g., servers, files, users).
  • Loop over that list to perform the same action on each item.
  • Pass a collection of data to and from a function.
  • Manage complex data in a structured way.

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.

Declare Array in Shell Scripting

Arrays can be declared in a shell script using various approaches:

1. Compound Assignment

This is the most common and readable method. You create the array with all its values at once.

my_array=("value1" "value2" "value3")

You can also span it across multiple lines :

files=(
"/etc/hosts"
"/etc/passwd"
"/var/log/syslog"
)

2. By Specific Index

You can add values one by one. This is good for building an array in a loop.

my_array[0]="apple"
my_array[1]="banana"
my_array[2]="cherry"

Note: Arrays can be "sparse," meaning you can skip an index. my_array[10]="orange" is valid.

3. Explicit Declaration

You can declare an empty array using declare -a.

declare -a my_array
my_array[0]="first"

How to Access Array Elements

This is the most critical part of using arrays. The curly braces ({}) are required.

  • my_array (no brackets): This is the same as ${my_array[0]}. It only gives you the first element. This is a common bug.
  • ${my_array[1]}: Access one element by its index (e.g., the 2nd item).
  • ${my_array[@]}: Access all elements, with each as a separate string.
  • ${#my_array[@]}: Get the number of elements in the array (the length).
  • ${#my_array[0]}: Get the length of a single element's string.

How to Manage Array Elements

We will discuss various operations that we can perform on arrays.

1. Add an Element

Use the += operator. This appends items to the end of the array.

servers=("web-01" "db-01")
echo "Original: ${servers[@]}"

servers+=("app-01")
servers+=("worker-01" "cache-01")

echo "Updated: ${servers[@]}"

Output:

Original: web-01 db-01
Updated: web-01 db-01 app-01 worker-01 cache-01

2. Delete an Element

Use the unset command. This removes the element from the array.

servers=("web-01" "db-01" "app-01")
echo "Original: ${servers[@]}"

unset servers[1] # Delete 'db-01'

echo "Updated: ${servers[@]}"

Output:

Original: web-01 db-01 app-01
Updated: web-01 app-01

3. Slicing an Array

You can get a "slice" of the array. :${offset} = Get all elements from this offset. :${offset}:${length} = Get length elements from this offset.

my_array=(a b c d e f)

# Get all from index 2 (c) onward
echo "${my_array[@]:2}" # Output: c d e f

# Get 3 elements, starting from index 1 (b)
echo "${my_array[@]:1:3}" # Output: b c d

4. Search and Replace

You can do simple search and replace on all elements: ${array[@]/search/replace}

servers=("web-01" "web-02" "db-01")

# Replace 'web' with 'http'
echo "${servers[@]/web/http}"

Output:

http-01 http-02 db-01

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:

1. Array Declaration: An array named arr is declared, containing six elements. These elements are strings: "prakhar", "ankit", "1", "rishabh", "manish", and "abhinav".

2. 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.

3. 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.

4. 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).

5. 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.

6. 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.
457
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:

1. Array Declaration:

  • An array named arr is declared, containing six elements.
  • These elements are strings: "Jayesh", "Shivang", "1", "rishabh", "Vipul", and "Nishtan".

2. 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.

3. Printing Array Length:

  • The length of the entire array is calculated using ${#arr[@]}.
  • This length is stored in the variable array_length.

4. 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.

5. 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.

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

7. 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.
458
Array Basics

Array Operations Table:

SyntaxWhat It Does
arr=(a b c)Define: Create a new array.
declare -a arrDefine: Declare an empty array.
${arr[1]}Access: Get one element (e.g., index 1).
"${arr[@]}"(Correct Access) Get all elements as separate, quoted strings.
${#arr[@]}Length: Get the total number of elements.
${#arr[0]}Length: Get the string length of the first element.
${!arr[@]}Keys: Get all the indices (keys) (e.g., 0 1 2).
arr+=("d")Add: Append one or more elements to the end.
unset arr[1]Delete: Remove the element at index 1.
${arr[@]:1:3}Slice: Get 3 elements, starting from index 1.

Explore