Yes, absolutely! Just like Python lists use list[index], Bash arrays can be indexed directly for both reading and writing.
1. Directly Assigning/Updating (Writing)
You don't have to use += (append). You can assign a value to a specific position at any time:
# Update the second element (index 1)
NAMES[1]="Mark"
# Assign a value to a specific index, even if it skips others
NUMBERS[10]=100
Note: Bash supports "sparse" arrays, meaning you can have an item at index 0 and index 10 without having anything in between.
2. Directly Accessing (Reading)
As we touched on earlier, you use the ${ARRAY[index]} syntax to read a specific value:
echo ${NAMES[0]} # Prints: John
echo ${NUMBERS[1]} # Prints: 2
3. Direct Comparison with Python
If you were writing this in Python:
| Action | Python | Bash |
|---|---|---|
| Read | print(names[0]) |
echo ${NAMES[0]} |
| Write/Update | names[1] = "Mark" |
NAMES[1]="Mark" |
| Multi-Write | nums = [1, 2, 3] |
NUMBERS=(1 2 3) |
Why the curly braces ${} again?
Remember, if you forget the braces and try echo $NAMES[0], Bash will print the first element of the array followed by the string "[0]". Always use the braces when indexing.
Fun Fact: Negative Indexing
In modern Bash (version 4.2+), you can even use negative indexing just like Python!
# Get the last element
echo ${NAMES[-1]} # Prints: Jessica
Does this help you see how you might manipulate specific items in your script?