How to access array elements dynamically?

QuestionsQuestions4 SkillsProDec, 12 2025
0175

That's a great question, and it introduces a powerful concept for working with arrays! You can access array elements dynamically by using a variable for the index.

Here's the general idea: instead of directly putting a number like 0 or 1 inside the square brackets, you put a variable that holds that number. To make sure Bash interprets the variable's value as an index, you need to use $ before the variable name inside the brackets.

The syntax looks like this:

${array_name[$variable_holding_index]}

Let's illustrate with an example:

#!/bin/bash

# Define an array
colors=("red" "green" "blue" "yellow" "purple")

# Define a variable to hold the index
index=2

# Access an element dynamically using the 'index' variable
echo "The color at index $index is: ${colors[$index]}"

# You can also change the index dynamically, for instance, in a loop
echo "--- Loop through array elements dynamically ---"
for i in 0 1 2 3 4; do
  echo "Color at index $i: ${colors[$i]}"
done

# Or get user input for the index
echo -n "Enter an index (0-4) to see a color: "
read user_index

# Check if the user input is a valid number and within bounds for a more robust script
if [[ "$user_index" =~ ^[0-9]+$ ]] && (( user_index >= 0 )) && (( user_index < ${#colors[@]} )); then
    echo "You chose: ${colors[$user_index]}"
else
    echo "Invalid index. Please enter a number between 0 and $(( ${#colors[@]} - 1 ))."
fi

Explanation:

  1. index=2: We set a variable index to 2.
  2. echo "The color at index $index is: ${colors[$index]}": When Bash evaluates this, it first resolves $index to 2, so the expression effectively becomes ${colors[2]}, which accesses the third element ("blue").
  3. Loops: Dynamic access is incredibly useful in loops (like the for loop shown), where you want to iterate through each element of an array without knowing its exact size beforehand. The loop variable i changes with each iteration, dynamically providing a different index.
  4. User Input: You can even take user input, store it in a variable, and then use that variable to access array elements dynamically.

This dynamic access is crucial for writing flexible and powerful shell scripts that interact with data stored in arrays.

Do you want to try applying this concept to the arrays.sh file we just created?

0 Comments

no data
Be the first to share your comment!