Sebastien
Sebastien

Reputation: 2679

Bash script to backup files to remote FTP. Deleting old files

I'm writing a bash script to send backups to a remote ftp server. The backup files are generated with a WordPress plugin so half the work is done for me from the start.

The script does several things.

  1. It looks in the local backup dir for any files older than x and deletes them
  2. It connects to FTP and puts the backup files in a dir with the current date as a name
  3. It deletes any backup dirs for backups older than x

As I am not fluent in bash, this is a mishmash of a bunch of scripts I found around the net.

Here is my script:

#! /bin/bash 

BACKDIR=/var/www/wp-content/backups

#----------------------FTP Settings--------------------#

FTP=Y

FTPHOST="host"
FTPUSER="user"
FTPPASS="pass"
FTPDIR="/backups"
LFTP=$(which lftp)      # Path to binary

#-------------------Deletion Settings-------------------#

DELETE=Y

DAYS=3 # how many days of backups do you want to keep?

TODAY=$(date --iso) # Today's date like YYYY-MM-DD
RMDATE=$(date --iso -d  $DAYS' days ago') # TODAY minus X days - too old files

#----------------------End of Settings------------------#

if  [ -e $BACKDIR ]
then

if  [ $DELETE = "Y" ]
then
    find $BACKDIR -iname '*.zip' -type f -mtime +$DAYS -delete
    echo "Old files deleted."
fi

if  [ $FTP = "Y" ]
then

    echo "Initiating FTP connection..."

    cd $BACKDIR

    $LFTP << EOF
    open ${FTPUSER}:${FTPPASS}@${FTPHOST}
    mkdir $FTPDIR
    cd $FTPDIR
    mkdir ${TODAY}
    cd ${TODAY}
    mput *.zip
    cd ..
    rm -rf ${RMDATE}
    bye

EOF

echo "Done putting files to FTP."

fi

else
    echo "No Backup directory."
    exit
fi

There are 2 specific things I can't get done:

  1. The find command doesn't delete any of the old files in the local backup dir.
  2. I would like mput to only put the .zip files that were created today.

Thanks in advance for the help.

Upvotes: 1

Views: 8848

Answers (2)

To send only zip files that were created today:

MPUT_ZIPS="$(find $BACKDIR -iname '*.zip' -type f -maxdepth 1 -mtime 1 | sed -e 's/^/mput /')"

[...]
$LFTP << EOF
open ${FTPUSER}:${FTPPASS}@${FTPHOST}
mkdir $FTPDIR
cd $FTPDIR
mkdir ${TODAY}
cd ${TODAY}
${MPUT_ZIPS}
cd ..
rm -rf ${RMDATE}
bye

EOF

Hope this helps =)

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74108

2) If you put todays backup files in a separate directory or link them to a separate directory, you can cd today and just transfer these files.

Upvotes: 0

Related Questions