Bash Access Elements in Array Using Index


Bash Access Elements in Array Using Index

In Bash scripting, accessing elements in an array using an index is useful for various tasks that require retrieving specific elements from arrays.


Syntax

array[index]

The basic syntax involves using square brackets to access the element at the specified index in the array.


Example Bash Access Elements in Array Using Index

Let's look at some examples of how to access elements in an array using an index in Bash:

1. Access First Element in Array

This script initializes an array with elements and prints the first element.

#!/bin/bash

array=("element1" "element2" "element3")
echo "The first element is: ${array[0]}"

In this script, the array variable array is initialized with the elements 'element1', 'element2', and 'element3'. The script then prints the first element, which is accessed using the index 0.

Access first element in array in Bash

2. Access Element at User-Specified Index

This script initializes an array with elements, prompts the user to enter an index, and prints the element at the specified index.

#!/bin/bash

array=("element1" "element2" "element3")
read -p "Enter the index of the element to access: " index
echo "The element at index $index is: ${array[$index]}"

In this script, the array variable array is initialized with the elements 'element1', 'element2', and 'element3'. The user is prompted to enter an index, which is stored in the variable index. The script then prints the element at the specified index, which is accessed using array[$index].

Access element at user-specified index in Bash

Conclusion

Accessing elements in an array using an index in Bash is a fundamental task for retrieving specific elements from arrays in shell scripting. Understanding how to access array elements by index can help you manage and manipulate arrays effectively in your scripts.