Search code examples
linuxbashbackuprsync

Loop through directories and rsync contents


I'm looking to rsync only specific files and directories from a cpanel backup to a remote server.

The basic structure is:

/backup/cpbackup/daily/USERNAME

from within USERNAME directory I want to backup

../USERNAME/mysql/USERNAME.sql

and also a folder (containing files and subfolders)

../USERNAME/homedir/siteassets

so I end up on my remote server with:

/USERNAME/mysql/USERNAME.sql
/USERNAME/homedir/siteassets

I could use wildcards

rsync /backup/cpbackup/daily/*/mysql/*.sql  [email protected]:servername/

but this won't give me the USERNAME folder remotely and will mean all the files end up getting merged. I assume this is possible by iterating through folders with bash or something like tht but thats not my strong point


Solution

  • Answered it myself:

    #!/bin/bash
    
    src="/backup/cpbackup/daily"
    
    for dir in `ls "$src/"`
    do
      if [ -d "$src/$dir" ]; then
    
            # look for mysql directory      
            mypath="$src/$dir/mysql"
            if [ -d $mypath ]; then
                    mysqlfile=$mypath/$dir".sql"
                    rsync -vau --progress --stats --rsh=ssh $mysqlfile [email protected]:servername/$dir
            fi
    
            # look for images directory      
            impath="$src/$dir/homedir/siteassets"
            if [ -d $impath ]; then
                    rsync -vau --progress --stats --rsh=ssh $impath [email protected]:servername/$dir
            fi
    
      fi
    done