27

I need to determine whether a certain path exists and points to a directory, like the -d test in the shell. I know about the filereadable() function, which does basically this for files:

filereadable({file}) *filereadable()* The result is a Number, which is TRUE when a file with the name {file} exists, and can be read. If {file} doesn't exist, or is a directory, the result is FALSE. {file} is any expression, which is used as a String. If you don't care about the file being readable you can use |glob()|. 

Is there an equivalent for directories?

1 Answer 1

39

You’re looking for the isdirectory() function:

isdirectory({directory}) *isdirectory()* The result is a Number, which is non-zero when a directory with the name {directory} exists. If {directory} doesn't exist, or isn't a directory, the result is FALSE. {directory} is any expression, which is used as a String. 

Unlike filereadable(), this function doesn’t check whether the directory is readable; it only checks whether it exists. (Correspondingly, there isn’t a single built-in function to check whether a file exists without also checking that it’s readable. This answer demonstrates how to use the glob() function to do this kind of check.)

To summarize,

  • To check whether a file or directory named name exists,

    !empty(glob(name)) 
  • To check whether a file (not a directory) named file_name exists,

    !empty(glob(file_name)) && !isdirectory(file_name) 
  • To check whether a directory (not a file) named dir_name exists,

    isdirectory(dir_name) 
  • To check whether a file (not a directory) named file_name exists and is readable,

    filereadable(file_name) 
  • I’m not sure how to check whether a directory (not a file) of a specified name exists and is readable.

For the forms that use glob(), don’t forget that certain characters like * are special and need to be escaped if they occur literally in the filename. See :help wildcard for more information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.