Created
December 24, 2013 21:31
-
-
Save Gen2ly/8117973 to your computer and use it in GitHub Desktop.
Backup files with sequential numbering and optional tag
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/sh | |
# Backup files with sequential numbering and optional tag | |
# Display usage if given the incorrect number of parameters | |
if [ $# -ne 2 -a $# -ne 3 ]; then | |
echo "${0##*/} [file] [dir] [*tag]- Backup files with sequential numbering, opt. tag" | |
exit 1; fi | |
# Test if first and second parameters are a file and a directory | |
if [ ! -e "$1" ]; then | |
echo "${0##*/}: non-file: "$1"" | |
error=1; fi | |
if [ ! -d "$2" ]; then | |
echo "${0##*/}: non-dir.: "$2"" | |
error=1; fi | |
[ -n "$error" ] && exit 1 | |
# Filename: path, dirname, name, basename (name w/o number, tag, ext.), ext. | |
fpth="$(realpath "$1")" | |
fdnm="${fpth%/*}" | |
fnme="${fpth##*/}" | |
fbse="${fnme%.*}"; fbse="${fbse%_[0-9][0-9]*}" | |
fext="${fnme##*.}" | |
if [ "$fext" = "$fnme" ]; then | |
fext="" | |
else | |
fext=".$fext";fi | |
# Set sequential number (parse out number previous, add to for number next) | |
fpre=$(ls -1 "$fdnm"/"$fbse"_[0-9][0-9]* 2> /dev/null) # File backups previous | |
if [ $? -eq 0 ]; then | |
npre=$(echo "${fpre##*/}" | tail -n 1 | grep -o ^"$fbse"_[0-9][0-9] | grep \ | |
-o [0-9][0-9] ) | |
nnxt=$(printf "%02u" $((++npre))) | |
else | |
nnxt=00 | |
fi | |
# Define admin. program if write permission is needed | |
if [ ! -w "$2" ]; then | |
[ ! hash sudo 2>&- ] && { echo "${0##*/}: program required: sudo"; exit 1; } | |
sudo=sudo; fi | |
# Assign tag | |
[ -n "$3" ] && \ | |
tag="-$3" && \ | |
tag="$(printf "%q" "$tag")" | |
# Backup file | |
$sudo cp -av "$fpth" "$fdnm"/"$fbse"_"$nnxt""$tag""$fext" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment