For a system administrator, we need to delete the old backup files or upload files. We can finish this task manually if you only have a few server backup, but as the number of server grows, we will need automate this.


In this example, the backup for server (named monitoring, a virtual machine sitting in Hyper-v) is backuped on weekly basis on Saturday and named as the the date format “” under the machines/monitoring folder in FTP server. we only keep the most recent 3 copies,

The script is like this:


YEAR="$(date +"%Y")"
MONTH="$(date +"%m")"
###Use GNU date, we can get the date of 21 days ago by following command
DAY="$(date +"%d" -d "21 days ago")"
names='monitoring logging db'

for name in $names


    ftp -n $HOST << END_SCRIPT

    quote user $USER 

    quote PASS $PASSWD

    mdelete machines/monitoring/$FILE quit 



exit 0

Script explained:

  1. We save the hostname, username, password into variables.
  2. store year, month, and day in variables.
  3. FTP log on from script:Getting the password to the ftp server without having the ftp client program read the password from /dev/tty requires two tricks:
    1. Using the -n option on the ftp client program to prevent the ftp client from trying to log in immediately. That way, the ftp client does not ask for a user ID and password. No use of /dev/tty.
    2. Use the ftp client program command quote to send user ID and password to the ftp server.
  4. ftp -n $HOST << END_SCRIP means, from next line until the line “END_SCRIPT” are FTP commands.
  5. mdelete will delete the files.

Then add the script to crontab, and make it work on Saturday after the backup, therefore, we keep 3 backups.


To be improved

This script only delete the file which is 3 weeks old, does not delete the older files, hence we need to delete the older ones manually, but luckily only onece.

Tried to list the file names in the backup folder on FTP server by ls command, but was getting a line of file info ( permission, created date,etc) , needs to figure out how to only grab the files names and then we can loop through those files and delete the older ones.


Bash – Get Time: