#!/bin/bash # # 2006-12: Written by Steven J. DeRose, sderose@acm.org. # 2008-01-23 sjd: Add -A so we notice hidden files. # 2010-03-16 sjd: Use $HOME env var. # 2010-03-22 sjd: Make link to latest dir to make easier to find. # # Help if [ "$1" = "-h" ]; then echo "Usage: backup [options] [filenames]" echo "Copy file(s) to a time-stamped subdirectory in \$BACKUP_DIR." echo " With -n name, append 'name' to the subdir name (or defaults)." echo " Options for cp are ok, for example: backup -r foo." if [ "$BACKUP_DIR" = "" ]; then echo " Currently, your back directory is '$BACKUP_DIR'." else echo " You have not set \$BACKUP_DIR. Default is \$HOME/backups." fi exit fi # Find/make a backups dir if [ "$BACKUP_DIR" = "" ]; then export BACKUP_DIR="$HOME/backups"; fi # Support option to append name to subdir timestamp if [ "$1" = "-n" ] || [ "$1" = "-name" ]; then shift suffix=$1 shift else suffix=`echo "$*" | sed -e 's/ .*$/.../' -e 's/[^-_.a-zA-Z0-9]/_/g'` #echo "Suffix calculated from '$*' as '$suffix'." fi subdir="$BACKUP_DIR/"`date +%Y\-%m\-%dT%H.%M.%S`".$suffix"; # See if at least the first file listed exists if ! [ -e $1 ]; then echo "backup: Can't find file '$1'." exit; fi # Make sure they've named something to back up todo=`ls -A $* 2>/dev/null | wc -l` if [ "$todo" -lt "1" ]; then echo "backup: *** No files found ***" exit fi # Make the target dir if ! [ -d $subdir ]; then mkdir -p $subdir; if ! [ -d $subdir ]; then echo "backup: Can't find or mkdir backup subdirectory '$subdir'."; exit fi fi # Make a note, to preserve source info: notefile="$subdir/_backup_note.txt" echo "Backup command was:" >$notefile echo " $0 $*" >>$notefile echo "PWD at the time was:" >>$notefile echo " $PWD" >>$notefile # Do the actual backup cp $* $subdir/ found=`ls -A $subdir | wc -l` if [ -e $notefile ]; then let found="$found - 1" fi ln -s $subdir "$BACKUP_DIR/latest" # Report results if [ $found = 0 ]; then echo "backup: *** No files backed up ***" else echo "backup: $found file(s) copied to $subdir (linked from 'latest')." fi exit;