andrewtweber
andrewtweber

Reputation: 25529

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.

Upvotes: 5

Views: 2820

Answers (4)

mighq
mighq

Reputation: 1024

Just adding to John Kugelman's answer. Details can be found in:

bash man page -> Parameter Expansion -> Pattern substitution

... If pattern begins with #, it must match at the beginning of the expanded value of parameter. ...

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149776

for i in $( for d in ${databases[@]}; do echo "live_$d stage_$d"; done )
do
    ....
done

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361605

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

Upvotes: 15

muffinista
muffinista

Reputation: 6736

Try something like this:

#!/bin/sh
databases="db1 db2 db3"
for i in $databases
do
    x="live_$i"
    y="stage_$i"
    echo "$x $y"
done

Upvotes: 1

Related Questions