Home > OS >  Bash: Is -e equivalent to -f || -d?
Bash: Is -e equivalent to -f || -d?

Time:10-26

In my projects I use the pattern

if [ -f "$path" ] || [ -d "$path" ]; then
    echo "$path exists"
fi

to check whether $path exists on the file system, regardless of whether it's a file or directory. Is this exactly equivalent to just doing

if [ -e "$path" ]; then
    echo "$path exists"
fi

? What about for special files such as symbolic links or devices? Are there any platform dependent details to be aware of? I use Bash, but I would like to know about subtle differences between shells.

CodePudding user response:

No, it's not. -e pathname only tests if pathname resolves to an existing directory entry. -f and -d, on the other hand, also tests if the entry is for a regular file and a directory, respectively.

For example, if pathname resolves to a FIFO (or a block special file, or a character device, or a socket, etc.), [ -e pathname ] returns true; but [ -f pathname ] || [ -d pathname ] returns false.

As for symbolic links, neither -e, -f, nor -d differentiates them from entries they resolve to. If pathname names a regular file, a directory, or a symbolic link to a regular file or a directory, both [ -e pathname ] and [ -f pathname ] || [ -d pathname ] return true. And if pathname names a symbolic link to an entry that doesn't exist (i.e. a broken symbolic link), both return false.

  • Related