Timestamp File in Linux

I’ve been using Webmin to manage my Linux server, but I wanted the backup files to be timestamped so that subsequent backups didn’t overwrite them. Since I didn’t see an option for that, I created a simple Linux shell script that will prepend a timestamp to a filename. So for example, if the shell script is called stamp_file, then running the command

./stamp_file /var/backup/apache_config_backup.tar.gz

will make a copy of /var/backup/apache_config_backup.tar.gz file, and call it something like like /var/backup/20070323142367-apache_config_backup.tar.gz. Note that the original file is maintained, and that the copy starts with YYYYMMDDhhmmss.

Anyhow, here’s the script

#!/bin/sh
# timestamp a file
# args: <fullfilename>

echo -e "nn"

# check arguments
if [ $# -ne 1 ]; then
        echo -e "Usage: $0 <fullfilename> nn"
        echo -e "e.g. $0 /var/backups/apache_backup.tar.gz nn"
        exit 127
fi

echo -e "Timestamping $1 nn"

# get file, directory, and new filename
fname=$(basename $1)
newname="$(date +%Y%m%d%H%M%S)-$fname"
dname=$(dirname $1)

# make a copy
cp -vf $dname/$fname $dname/$newname

echo "nnDone, created $dname/$newnamenn"

Now for all my backup tasks I can just run the stamp_file script to make sure that I don’t overwrite older backups, which means I can do daily or weekly backups & go back in time when I need to. Ideas for future expansion might be to have the script make folders for each month, copy the backups into those.

0