Shell: How to add a prefix during a loop through an array?

I am trying to loop through an array and add 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 adds a prefix to the first value in the array - the values ​​it executes are as follows:

live_db1 db2 db3 stage_db1 db2 db3

Any thoughts? Thank.

+5
source share
4 answers
databases=( db1 db2 db3 )
for i in ${databases[@]/#/live_} ${databases[@]/#/stage_}
do
    ....
done
+15
source

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
+1
source
for i in $( for d in ${databases[@]}; do echo "live_$d stage_$d"; done )
do
    ....
done
+1

. :

bash man page β†’ β†’

... #, ....

0

All Articles