Rotate FTP Backup Using a Shell Script

last updated in Categories Backup, Howto, Linux, RedHat/Fedora Linux, Shell scripting, Tips, Ubuntu Linux, UNIX

I’ve already written about rotating sftp / ssh backup shell script to remove directories (old backup files). However, a few of our readers would like to know more about removing old backup directories using ftp. As usual, you need accurate date and time on local system and remote backup directory must be in dd-mm-yyyy or mm-dd-yyyy format. For example daily mysql backup should be stored in /mysql/dd-mm-yyyy format.

Sample Shell Script

Here is a simple and dirty shell script to remove old backups ( download link ):

# call ./ 03-2007 - to remove all March-2007 directories in 01-03-2007, 02-03-2007, 31-03-2007 format
# you must have ncftp ftp client installed on BSD / Linux box
BASE="/mysql" # base dir below that dd-mm-yyyy
[ $# -eq 0 ] && exit 1 || :
echo "Getting old directories..."
ncftpls -u 'ftp-user-name' -p 'ftp-password' -x "-t"${BASE} > /tmp/ftp.out
LIST="$(grep ${DELETE} /tmp/ftp.out)"
echo -n "Starting removal for ${DELETE}..."
for dir in $LIST
# echo "Processing ${dir}..."
 ncftp -L -u 'ftp-user-name' -p 'ftp-password' <<EOF
 cd $rdir
 rm *
 rmdir $rdir

Run the script as follows to remove all backup for Dec-2007, enter:
$ ./ 12-2007

Related: Generate backup ftp script using php based wizard

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 5 comments/add one below):

5 comment

  1. Don’t forget to add “exit 0” at the end of bash scripts so that you can use them in conjunction with everything else. This way the OS knows whether or not the script ended correctly.

  2. Why not use the date function in linux to name the directory?

    It with your script could be placed in a crontab.

  3. Thanks for the script. Would you please amend it to accommodate rotation based on days? This is much better than month.

    Have a question? Post it on our forum!