Open In App

Array Basics in Shell Scripting | Set 1

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:

  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.

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


Article Tags :