Move vi/vim editor temporary swap and backup files to another directory

vi/vim FAQ: I keep getting these vim swap/temporary/backup files in my current directory, the ones with the tilde (~) character at the end of the filename; how do I get these swap/temporary files to go into another directory?

A vim swap file (at least on Mac OS X) is named with a ".swp" file extension, and seems to exist as long as you are editing a file in vim. The vim backup/tilde file is the filename that has a "~" character appended to the end of it, and when these are left in your current directory, they're pretty annoying. You can tell vi/vim to place both of these temporary files in another directory, as shown here.

Moving vi/vim temporary/swap/tilde files on Mac OS X

Using vi and vim on my Mac OS X systems, I tell vim where to place the backup and swap files using the commands shown here:

" tell vim to keep a backup file
set backup

" tell vim where to put its backup files
set backupdir=/private/tmp

" tell vim where to put swap files
set dir=/private/tmp

I just place these commands in the .vimrc file in my home directory, and I no longer get all those junky vi/vim swap/tilde files in my current working directory. If you're using an older version of vi, you should place these commands in a file named .exrc in your home directory.

This same approach should work just fine on other Unix systems as well, though you may want to change that directory to just /tmp. That "directory" didn't work for me on Mac OS X, probably because /tmp on Mac OS X systems is actually a symbolic link to the /private/tmp folder.

vi/vim temporary/swap/tilde files on MS Windows

I don't have a Windows system I can test on at the moment, but the approach should be similar; just tell vi/vim where to place these backup/temporary/tilde files. Something like this should work, assuming you have a C:\Temp directory.

" tell vim to keep a backup file
set backup

" tell vim where to put its backup files
set backupdir=C:\\Temp

" tell vim where to put swap files
set dir=C:\\Temp

I'm guessing that you need two backslashes there, though I could be wrong. If anyone knows for sure, I'd appreciate you letting me know in a comment below.

Vim backup and swap file configuration - summary

For more information on how to use a vimrc configuration file, see my Vim vimrc example configuration file article.

I hope this vi/vim tip on moving your vi and vim temporary backup and swap files to another directory is helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.