Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

bash

shell

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.

like image 746
andrewtweber Avatar asked Apr 27 '11 19:04

andrewtweber


2 Answers

databases=( db1 db2 db3 )
for i in ${databases[@]/#/live_} ${databases[@]/#/stage_}
do
    ....
done
like image 162
John Kugelman Avatar answered Nov 15 '22 06:11

John Kugelman


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
like image 36
muffinista Avatar answered Nov 15 '22 06:11

muffinista