Iterate over and replace element in array

Viewed 17805

I am trying to replace the word "Apples" with "Cantaloupe" in my 'copy' array. What I am doing now is not throwing errors, but no change occurs in the copy array.

#!/bin/bash

fruits=("Oranges" "Apples" "Bananas" "Grapes")
echo "Original list:"
echo "${fruits[@]}"

copy=("${fruits[@]}")

for i in ${copy[@]}
do
        if [[ copy[$i] == "Apples" ]]; then
                copy[$i]="Canteloupe"
        fi
done

echo "Copied list:"
echo "${copy[@]}"

My output:

Original list:
Oranges Apples Bananas Grapes
Copied list:
Oranges Apples Bananas Grapes
2 Answers

The solution explained in the accepted answer to this similar question might be preferable:

array=("${array[@]/Apples/Canteloupe}")

This depends on your general attitude towards Bash trickery. In technical terms, there are no downsides to manually iterating over the elements.

Related