Last active
December 21, 2015 14:39
-
-
Save kwikwag/6320820 to your computer and use it in GitHub Desktop.
simple script to backup a directory as a tar.gz archive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
OUT_DIR=/opt/DUMP | |
VERBOSE=0 | |
NAME= | |
show_help() { | |
cat <<HELP | |
Backs up a directory. | |
Usage: $0 [-h -?] [-n name] [-o outdir] <directory> [...tar options] | |
-h, -? Show this help. | |
-n name Use 'name' as the prefix for the backup archive. | |
-o outdir Output archive to 'outdir'. Default: $OUT_DIR. | |
tar options Passed as-is to tar. | |
HELP | |
} | |
while getopts "h?vo:n:" OPT; do | |
case "$OPT" in | |
h|\?) | |
show_help | |
exit 0 | |
;; | |
v) | |
VERBOSE=1 | |
;; | |
o) | |
OUT_DIR=$OPTARG; | |
;; | |
n) | |
NAME=$OPTARG | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
DIR=$1 | |
shift 1 | |
if [ -z $NAME ]; then | |
NAME=`echo $DIR | sed 's/[^a-zA-Z0-9]\+/-/g' | sed 's/\(^-\|-$\)//g'` | |
fi | |
# delete old backups (older than two days) | |
PREFIX=$OUT_DIR/${NAME}-backup- | |
find ${PREFIX}*.gz -mtime +2 -exec rm "{}" \; | |
# find name for new backup | |
FN=${PREFIX}`date +'%Y-%m-%d'` | |
if [ -f $FN.gz ]; then | |
J=1 | |
while [ -f $FN-$J.gz ]; do | |
J=$((J+1)) | |
done | |
FN=$FN-$J.gz | |
else | |
FN=$FN.gz | |
fi | |
tar czf $FN $DIR "$@" | |
chmod 640 $FN |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment