VI and Backup Files

The following guidelines should work on computers running Linux or any sufficiently similar operating system.

You can set up vi to store backups of the file you are editing by inserting the following five lines into your .vimrc file:

  set backup
  set writebackup
  au BufWritePre * let &backupext = '%' . substitute(expand("%:p:h"), "/" , "%" , "g") . "%" . strftime("%Y.%m.%d.%H.%M.%S")
  au VimLeave * !cp % ~/.vim_backups/$(echo %:p | sed 's/\(.*\/\)\(.*\)/\2\/\1/g' | sed 's/\//\%/g')$(date +\%Y.\%m.\%d.\%H.\%M.\%S).wq
  set backupdir=~/.vim_backups/

You will need to create a subdirectory .vim_backups inside your home directory.  (Obviously, you could give it a different name and change the lines in .vimrc appropriately.)  Writing to a file with vi will then produce a file in your backup directory with a name like

riemann_hypoth_pf.tex%%home%abcdefg%Documents%Preprints%2032.04.23.15.55.00

(assuming that in the directory /home/abcdefg/Documents/Preprints you save the file riemann_hypoth_pf.tex using vi at exactly 3:55 p.m. on April 23, 2032).  The version of the file you have upon exiting vi will be similarly saved to the backup directory with a .wq suffix.

Two issues arise.  First, you will probably want to remove old files from your backup directory periodically.  This can be accomplished by inserting into your crontab file a line such as:

  0 4 * * * cd ~/.vim_backups && find -ctime +120 -execdir nice -n 19 /bin/mv '{}' /tmp/ \; >> /dev/null 2>&1

The effect will be that at 4 a.m. every day all files more than 120 days old will be moved from your .vim_backups directory to the /tmp directory (affording you an extra opportunity to retrieve them before they get deleted).  The 120-day period can, of course, be changed to your preference.  I expect a modern hard drive can easily hold 120 days’ worth of backed up text files, however compulsively one might be saving them.

The second, and more serious, issue is one of security.  If you are editing sensitive data with vi and encrypt the file when you are done, there will remain copies of the file in your backup directory.  Assuming you have the encryption software ccrypt installed on your computer, putting this Bash script in your PATH and making it executable will solve the problem.

Greg Marks