andrewtweber andrewtweber - 1 month ago 7
Bash Question

Shell: How to append a prefix while looping through an array?

I'm trying to loop through an array and append a prefix to each value in the array. Simplified version of the code:

#!/bin/sh
databases=( db1 db2 db3 )
for i in live_${databases[@]} stage_${databases[@]}
do
....
done


However, it only prepends the prefix to the first value in the array - the values it loops through are:

live_db1 db2 db3 stage_db1 db2 db3


Any thoughts? Thanks.

Answer
databases=( db1 db2 db3 )
for i in ${databases[@]/#/live_} ${databases[@]/#/stage_}
do
    ....
done
Comments