Created
June 20, 2017 01:03
-
-
Save markreid/f1af3ace867874d0c1b1a5d0b1749661 to your computer and use it in GitHub Desktop.
backup.sh
This file contains 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 | |
set -e | |
# backup.sh | |
# makes a copy of a file, appending a datestamp and incrementing a counter | |
# if it's needed. | |
# | |
# ie, running this 3 times: | |
# backup.sh /foo/bar.qux /foo/backups | |
# will create: | |
# /foo/backups/bar.2017-06-20.qux | |
# /foo/backups/bar.2017-06-20.1.qux | |
# /foo/backups/bar.2017-06-20.2.qux | |
if [ $# -ne 2 ] | |
then | |
echo "2 arguments required: source filename and target directory" | |
echo "backup.sh /foo/bar/qux.sqlite /foobackups" | |
exit 1 | |
fi | |
source=$1 | |
targetdir=$2 | |
path=$(basename "$source") | |
extension="${path##*.}" | |
filename="${path%.*}" | |
targetfilename=$filename.$(date +%F) | |
mkdir -p $targetdir | |
if [[ -e $targetdir/$targetfilename.$extension ]] ; then | |
i=1 | |
while [[ -e $targetdir/$targetfilename.$i.$extension ]] ; do | |
let i++ | |
done | |
targetfilename=$targetfilename.$i | |
fi | |
cp $source $targetdir/$targetfilename.$extension | |
echo "Backed up $source to $targetdir/$targetfilename.$extension" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment