I'm looking to write a bourne shell which loops through an array of hosts and performs an rsync for each. Something like:

HOSTS=("host1.domain.com", "host2.domain.com")

for HOST in $HOSTS
do
    HOST_DIR_NAME = ${HOST//./-}
    rsync backup_user@$HOST:/backup/blah/blah /backup/$HOST_DIR_NAME/blah/blah
done

The issue is, however, it appears that the array above is not working as expected, as upon looping through the array I see the following output:

wwcprod.plyinc.com,

Every online guide I find says that I'm defining the array correctly, but its obviously not working. Help!

Thanks!

link|improve this question

feedback

1 Answer

up vote 3 down vote accepted

Your ideal solution is far simpler than a bash array (and far more portable to non-bash bourne-style shells):

HOSTS="one two three four"
for H in $HOSTS ; do
    [... whatever for ${H} ...]
done

The for will split on whitespace within a string :-)

link|improve this answer
Thank you! Also, just so that I know how -- how would I correctly define an array of strings? – Skone Feb 9 '10 at 21:08
I'm pretty sure your array definition syntax is correct above, but the elements need to be addressed the same way C-style arrays are (not sure if you can for over them the way you're trying to or not - looks like you'd need a perl-style foreach kind of construct). I don't do much bash-specific stuff personally because I try to keep things portable, but tldp.org/LDP/abs/html/arrays.html seems like a good reference – voretaq7 Feb 9 '10 at 21:39
Because you can iterate over whitespace or newline seperated values you hardly ever need an array in BASH. When you do need a more complicated structure you often end up having requirements that favor something like Perl or Python. To iterate over a BASH loop I usually use a C style for loop with a counter, but it can also be done with "for HOST in ${HOSTS[@]}; do echo ${HOST}; done". – CarpeNoctem Feb 9 '10 at 22:52
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.