July 26, 2014

Tinysnip #2: Backup your important files

Time goes (too) fast. My previous tinysnip was already written more than two months ago. I bet there is no rush here, but sorry for the delay. It's hard to do everything we want, with only 24 hours per day (and sometimes without motivation).

I'm a fanatic, that's why I often try to improve my projects, my configs and my scripts (I even rewrite them from scratch, sometimes). Saving the deprecated files is very interesting (compare versions with diff). Instead of doing cp file.1{,.backup}, I've decided to write something simpler:


while true; do
	if (( N > BAK_LIM )); then
		p_err "You reached the limit (${BAK_LIM} .${BAK_EXT} files)"
	if [[ ! -f ${1}.${BAK_EXT}.${N} ]]; then
		cp -- "$1" "${1}.${BAK_EXT}.${N}"
		print -r -- "$1 copied to ${1}.${BAK_EXT}.${N}"
	(( N++ ))

I can backup the required file, using bak thefoofile. The snippet is pretty simple, actually it's like a "rotation". It tests the presence of the regular file thefoofile.BAK.1. If it exists, the name is incremented to thefoofile.BAK.2 and so on, until we are able to save it to thefoofile.BAK.X (in that case, the limit is BAK.9, but you could increase it using BAK_LIM). If you dislike the extension BAK, it's possible to change it. Now, do backups!

The snippet is jailed on git and it's waiting for you.