1

I am attempting to make a backup script for my websites but i am having issues with a nested for loop

BACKUP_DIR="/path/to/output"
WEB_DIR="/srv/http"
WEBSITES=($WEB_DIR/website_one $WEB_DIR/website_two)
MYSQLDBS=(database_one database_two)

for WEBSITEBACKUP in $WEBSITES
do
    # tar commands here for website directories

    for DATABASEBACKUP in $MYSQLDBS
    do
       # mysql dump commands here for databases
       break
    done
done

I was hoping that loop 1 would backup the website, then open loop 2 which would backup the database then break out of the inner loop and continue to backup website 2 but once it gets to the inner for loop the second time it backs up the first database again.

My question is, how can i get the nested loop to increment until all databases in the array have been backed up successfully, or is there another way i have overlooked?



For anyone who is wondering, the reason why the databases aren't being backed up in their own for loop is because i am getting the folder name from $WEBSITEBACKUP and i would like the store the databases in the same directory as their website.

CURRENT_BACKUP=`echo $WEBSITEBACKUP | sed "s|\$WEB_DIR||g" | tr "/" "-" | cut -b2-`
Michael
  • 21
  • 3
  • If you want to backup website1+db1 then website2+db2 it is better to have a single loop which does both (iterating over the array index). – eckes Dec 29 '14 at 23:32
  • I use two arrays one for websites and one for databases the reason why i had two loops is so i could cycle through the arrays but i think i just answered my own question, if i was to do for WEBSITEBACKUP in $WEBSITES $MYSQLDBS i could do echo {$WEBSITEBACKUP[1]} and echo {$WEBSITEBACKUP[2]} to get website dir and database name on each pass? – Michael Dec 29 '14 at 23:36
  • Yes you could also use a loop over a single array and shift each parameter, but for two arrays, see my answer. – eckes Dec 29 '14 at 23:42

1 Answers1

1

See here to iterate over the array keys. This way you do not need to nest the loops: $i will iterate over 0 1 2, you just need to make sure both arrays have the same number of elements.

#/bin/bash
WEBSITES=(A B C)
DATABASES=(X Y Z)

echo "debug: ${!WEBSITES[@]}"
for i in "${!WEBSITES[@]}"; do
  site=${WEBSITES[$i]}
  db=${DATABASES[$i]}
  echo tar $site
  echo mysqldump $db
done

results in:

debug: 0 1 2
tar A
mysqldump X
tar B
mysqldump Y
tar C
mysqldump Z
Community
  • 1
  • 1
eckes
  • 10,103
  • 1
  • 59
  • 71