Skip to content

Instantly share code, notes, and snippets.

@logarytm
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save logarytm/9532981 to your computer and use it in GitHub Desktop.

Select an option

Save logarytm/9532981 to your computer and use it in GitHub Desktop.
Simple backup macro for UNIX shells
# Backup
# Usage:
# backup foo bar will make a backup of foo and bar (foo.2014-03….bak)
# backup --rm foo will make a backup of foo and then delete the original file
# (useful if you, for example, rewrite a configuration file)
# Attention:
# This is not meant to be a substitute for VCS, or full backups. This is useful
# while editing a sensitive resource such as a configuration file, to have a
# fallback copy to return to.
backup()
{
# Whether to delete original files?
delete=0
# Use date as a suffix which will contain the backup creation date
suffix=".$(date +'%Y-%m-%d_%H-%M-%S').bak"
# Iterate on argument array
while [ "$1" ]; do
if [[ "$1" == '--rm' ]]; then
delete=1
# Go to next argument
shift
continue
fi
name="$1"
newname="$name$suffix"
if [ $delete = 1 ]; then
cmd='mv'
# Reset so that we won't have invalid options passed to mv
args=''
else
cmd='cp'
# cp should be used with recursive copying and permission preserving
# option
args='-rp'
fi
$cmd $args "$name" "$newname"
if [ "$?" != 0 ]; then
echo "\e[1;31m=>\e[1;37m Failed to archivize $name\e[0m"
return 1
fi
echo "\e[1;34m=>\e[1;37m $name archivized as $newname.\e[0m"
# Go to next argument
shift
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment