Modifying array elements in Shell is quite straightforward. You can update an existing element, add a new one, or even append to the entire array.
Here are the most common ways to modify array elements:
1. Update a Specific Element
To change the value of an existing element, just assign a new value to its index:
# Change the first element (index 0) to "Alice"
NAMES[0]="Alice"
2. Add an Element at a Specific Index
You can add an element anywhere by specifying the index, even if it's not the next number in sequence:
# Add "Bob" at index 5
NAMES[5]="Bob"
3. Append to the End of the Array
The easiest way to add an element to the end of an array without knowing its length is using the += operator:
# Adds "Charlie" to the end of the NAMES array
NAMES+=("Charlie")
4. Delete an Element
If you want to remove an element, use the unset command:
# Removes the element at index 1
unset NAMES[1]
Note: After unsetting, index 1 will be empty. The array does not automatically "shift" other elements to fill the gap.
5. Replace Patterns in All Elements
You can modify the values of the entire array using search and replace (this creates a new list):
# Replace 'a' with 'A' in all names
NAMES=("${NAMES[@]//a/A}")
Pro Tip for your current Lab:
In your arrays.sh file, if you wanted to change the first name in your list, you would add:
NAMES[0]="NewName"
Would you like to try adding one of these modification lines to your script to see how the output changes?