9

I dislike Vim cluttering my working directory with backup and swap files, but I don't want to turn them off in case something crashes. I found that adding lines like:

set backupdir=./.backup
set directory=./.backup

in the Vim .vimrc configuration file tells Vim to put those files in a hidden directory. This is great except that if I do not manually create these hidden directories, it seems Vim does not create backup or swap files. I saw somewhere else lines like:

set backupdir=./.backup,/tmp,.
set directory=./.backup,/tmp,.

and thought that this would tell Vim to use the other locations, /tmp or ., if it cannot use ./.backup, but Vim does not seem to do so.

How would I make Vim either:

  1. create the needed ./backup directory, or
  2. use the working directory if the ./backup directory does not exist?
1

4 Answers 4

6

I have these in my .vimrc to create a directory if it doesn't exist:

silent !mkdir ~/.vim/backups > /dev/null 2>&1

I'm sure you can modify to suit your needs, most likely:

silent !mkdir ./.backup > /dev/null 2>&1
2
3

Add those to your ~/.vimrc:

set backup
if !isdirectory($HOME."/.vim/backupdir")
    silent! execute "!mkdir ~/.vim/backupdir"
endif
set backupdir=~/.vim/backupdir
"not generate .swap
set noswapfile

You'll find the backup in your directory ~/.vim/backupdir.

1

This works for me.

:h 'backupdir' and :h 'directory' seem to indicate that your solution should work.

To check:

  1. Add set directory=./.backup,/tmp,. to your ~/.vimrc.
  2. Close Vim.
  3. Make sure ~/.backup does not exist.
  4. Reopen your ~/.vimrc in Vim.
  5. Check for .vimrc.swp in /tmp. (ls -la /tmp | grep .vimrc.swp)
1

Use mkdir -p which doesn't mind if the directory exists, and it can create paths so you can do stuff like:

mkdir -p .vim/backups

and it will always create the dir and never complain. No muss, no fuss.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.