How to access array elements by index?

QuestionsQuestions8 SkillsProDec, 12 2025
0124

Hello! In shell scripting, you can access individual elements of an array using their index. The syntax for accessing an array element is:

${array_name[index]}

Here's a breakdown:

  • array_name: This is the name you gave to your array.
  • index: This is the numerical position of the element you want to access. In most programming languages, including Bash, array indices start from 0. So, the first element is at index 0, the second at index 1, and so on.

Let's look at an example:

# Define an array named 'fruits'
fruits=("apple" "banana" "cherry")

# Access the first element (index 0)
echo "First fruit: ${fruits[0]}"

# Access the second element (index 1)
echo "Second fruit: ${fruits[1]}"

# Access the third element (index 2)
echo "Third fruit: ${fruits[2]}"

When you run this, the output would be:

First fruit: apple
Second fruit: banana
Third fruit: cherry

Remember that trying to access an index that doesn't exist in the array will typically result in an empty string being returned.

This is a fundamental concept for working with arrays, and you'll be using it a lot! Let me know if you have any other questions.

0 Comments

no data
Be the first to share your comment!