How to detect if a specific file exists in Vimscript?

VimFile Exists

Vim Problem Overview


I'm looking for an elegant way in Vimscript to check if a file exists in the current directory.

I came up with the code below but I'm not sure if that's the most elegant solution (I'll set a Vim option if the file exists). Is there any way of not having to do another comparison of the filename?

Maybe use a different built-in function from Vim?

:function! SomeCheck()
:   if findfile("SpecificFile", ".") == "SpecificFile"
:       echo "SpecificFile exists"
:   endif
:endfunction

Vim Solutions


Solution 1 - Vim

With a bit of searching in vim man I've found this, which looks much better that the original:

:function! SomeCheck()
:   if filereadable("SpecificFile")
:       echo "SpecificFile exists"
:   endif
:endfunction

Solution 2 - Vim

Some of the comments express concerns about filereadable and using glob instead. This addresses the issue of having a file that does exist, but permissions prevent it from being read. If you want to detect such cases, the following will work:

:if !empty(glob("path/to/file"))
:   echo "File exists."
:endif

Solution 3 - Vim

Giving some more visibility to metaphy's comment on the accepted answer:

> if filereadable(expand("~/.vim/bundle/vundle/README.md")) let g:hasVundle = 1 endif

filereadable is what is required, but there's an extra handy step of expand, should you be using ~ in your path:

:function! SomeCheck()
:   if filereadable(expand("SpecificFile"))
:       echo "SpecificFile exists"
:   endif
:endfunction 

For example

  • :echo filereadable('~/.vimrc') gives 0,
  • :echo filereadable(expand('~/.vimrc')) gives 1

Solution 4 - Vim

Sorry if it's too late, but doing

if !empty(expand(glob("filename")))
    echo "File exists"
else
    echo "File does not exists"
endif

works fine for me

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstefanBView Question on Stackoverflow
Solution 1 - VimstefanBView Answer on Stackoverflow
Solution 2 - VimbrianmearnsView Answer on Stackoverflow
Solution 3 - Vimicc97View Answer on Stackoverflow
Solution 4 - VimaloussaseView Answer on Stackoverflow