Skip to content

Instantly share code, notes, and snippets.

@nilox94
Created June 13, 2018 16:30
Show Gist options
  • Save nilox94/841007c6687cdf572a53a1bf048082f6 to your computer and use it in GitHub Desktop.
Save nilox94/841007c6687cdf572a53a1bf048082f6 to your computer and use it in GitHub Desktop.
Commands to backup and unbackup files rotating its names
#!/usr/bin/bash
function bak() {
name=${1%/}
prefix=${name%.bak}
if [[ $prefix == $name ]]; then
backup $name
else
unbackup $name
fi
}
function backup() {
local name=${1%/} n=${2:--1} cur_name next_name
if (( $n == -1 )); then
if [[ ! (-f $name || -d $name) ]]; then
echo $name is invalid or does not exist
return 1
fi
cur_name=$name
next_name=$name.bak
elif (( $n == 0 )); then
cur_name=$name.bak
next_name=$name.bak.1
else
cur_name=$name.bak.$n
next_name=$name.bak.$((n+1))
fi
if [[ -f $next_name || -d $next_name ]]; then
backup $name $((n+1))
if (( $? )); then
return $?
fi
fi
mv $cur_name $next_name
}
function unbackup() {
local name=${1%.bak?(/)}
local cur_name=$name next_name=$name.bak n=0
if [[ ! (-f $next_name || -d $next_name) ]]; then
echo $next_name is invalid or does not exist
return 1
fi
while [[ -f $next_name || -d $next_name ]]; do
(( n++ ))
mv $next_name $cur_name
cur_name=$next_name
next_name=$name.bak.$n
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment