Update Element of an Array

To update element of an array in Bash, access the element using array variable and index, and assign a new value to this element using assignment operator.

Syntax

The syntax to update or assign a new value to an element in array at specific index is

arrayname[index]=new_value
ADVERTISEMENT

Example

In the following script, we take an array arr with three elements and update the element with index=1.

Example.sh

arr=("apple" "banana" "cherry")
arr[1]="mango"
echo ${arr[@]}

Output

apple mango cherry

Conclusion

In this Bash Tutorial, we have learnt how to update or set a new value for element of an array at specific index in Bash shell, with examples.