How can I create a folder, if it doesn't exist, from .vimrc?

I think this is operating system independent:

if !isdirectory("/my/directory")
    call mkdir("/my/directory", "p")
endif

You can put this into your .vimrc:

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

This will attempt to create the ~/.vim_backup each time you start vim. If it already exists, mkdir will signal an error, but you'll never see it.


I much prefer the one-liners already posted. However, I thought I'd share what I've been using:

function! EnsureDirExists (dir)
  if !isdirectory(a:dir)
    if exists("*mkdir")
      call mkdir(a:dir,'p')
      echo "Created directory: " . a:dir
    else
      echo "Please create directory: " . a:dir
    endif
  endif
endfunction

call EnsureDirExists($HOME . '/.vim_backup')

Tags:

Vim