Vim's swap, backup, and undo file storage
Page created: 2023-05-04Vim’s various temporary files look like this:
foo.txt <-- original file .foo.txt.swp <-- Vim's swap file .foo.txt.un~ <-- Vim's undo file foo.txt~ <-- Vim's backup file
I think it’s best to allow Vim to create these files, but it doesn’t have to be in the same directory as the original file.
The locations can be changed. To see what they currently are, view the Vim options:
:set backupdir :set directory :set undodir
The confusing one to remember is directory
for swap files (e.g. .foo.txt.swp
).
The other two are pretty self-explanitory.
By default, the paths for each of these will include .
(the current directory).
You can have Vim write these files anywhere, but an appropriate place to put these files in the
year 2023 is in .local/state
in your home directory:
~/.local/state/vim/backup/ ~/.local/state/vim/swap/ ~/.local/state/vim/undo/
These directories will probably not already exist and Vim will not create them for you. Making them manually should be as easy as:
$ mkdir -p ~/.local/state/vim/backup $ mkdir -p ~/.local/state/vim/swap $ mkdir -p ~/.local/state/vim/undo
or one-liner:
$ mkdir -p .local/state/vim/{backup,swap,undo}
(Where the -p
option creates parent directories and doesn’t complain if
the target directory already exists.)
To change the paths in Vim, you can put the following in your .vimrc
(or equivalent).
:set backupdir=~/.local/state/vim/backup// :set directory=~/.local/state/vim/swap// :set undodir=~/.local/state/vim/undo/
Note that the directory
path has two path separator slashes at the end.
That tells Vim to create a unique filename for every file (otherwise, two
foo.txt
files in different directories would have the same swap file!)
As of Vim version 8.1.0251, you can now put a double slash after backupdir
for the same effect. Prior versions did not support this (the double slash
shouldn’t cause any harm, though).
You do not need the double slash for undodir
. It always uses a unique filename.
Back to vim.