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 ):
#!/bin/bash
# call ./script.sh 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 || :
DELETE="$1"
echo "Getting old directories..."
ncftpls -u 'ftp-user-name' -p 'ftp-password' -x "-t" ftp://ftp.your-server.com${BASE} > /tmp/ftp.out
LIST="$(grep ${DELETE} /tmp/ftp.out)"
echo -n "Starting removal for ${DELETE}..."
for dir in $LIST
do
rdir="${BASE}/${dir}"
# echo "Processing ${dir}..."
ncftp -L -u 'ftp-user-name' -p 'ftp-password' ftp.your-server.com <<EOF
cd $rdir
rm *
rmdir $rdir
quit
EOF
done
Run the script as follows to remove all backup for Dec-2007, enter:
$ ./script.sh 12-2007
Related: Generate backup ftp script using php based wizard
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop










![Sending Email With Attachments From Unix / Linux Command [ Shell Prompt ]](http://s0.cyberciti.org/images/rp/1/19.jpg)

{ 5 comments… read them below or add one }
why not using the ISO date format yyyy-mm-dd? It is way more convenient.
You can easily change script to match your local or ISO format.
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.
Why not use the date function in linux to name the directory?
It with your script could be placed in a crontab.
Thanks for the script. Would you please amend it to accommodate rotation based on days? This is much better than month.