开发者

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

开发者 https://www.devze.com 2023-02-28 23:00 出处:网络
I\'m trying t开发者_开发百科o loop through an array and append a prefix to each value in the array. Simplified version of the code:

I'm trying t开发者_开发百科o 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.


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


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


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


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. ...

0

精彩评论

暂无评论...
验证码 换一张
取 消