In Bash, array elements are accessed using zero-based indexing. Here’s how you can do it:
Declaring and Initializing an Array:
You can declare an array using parentheses ().
NAMES=("Alice" "Bob" "Charlie")
Accessing Array Elements:
To access elements, use the syntax ${array_name[index]}.
-
Access the First Element:
echo "First name: ${NAMES[0]}" # Outputs: Alice -
Access the Second Element:
echo "Second name: ${NAMES[1]}" # Outputs: Bob -
Access the Third Element:
echo "Third name: ${NAMES[2]}" # Outputs: Charlie
Example:
Here’s a complete example:
#!/bin/bash
NAMES=("Alice" "Bob" "Charlie")
echo "First name: ${NAMES[0]}"
echo "Second name: ${NAMES[1]}"
echo "Third name: ${NAMES[2]}"
Summary:
- Use
${array_name[index]}to access elements. - Indexing starts at
0.
Let me know if you need further assistance!
