Difference between 'if -e' and 'if -f'

BashIf Statement

Bash Problem Overview


There are two switches for the if condition which check for a file: -e and -f.

What is the difference between those two?

Bash Solutions


Solution 1 - Bash

See: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

I believe those aren't "if switches", rather "test switches" (because you have to use them inside [] brackets.

But the difference is:

[ -e FILE ] True if FILE exists.

This will return true for both /etc/hosts and /dev/null and for directories.

[ -f FILE ] True if FILE exists and is a regular file. This will return true for /etc/hosts and false for /dev/null (because it is not a regular file), and false for /dev since it is a directory.

Solution 2 - Bash

$ man bash

       -e file
              True if file exists.
       -f file
              True if file exists and is a regular file.

A regular file is something that isn't a directory, symlink, socket, device, etc.

Solution 3 - Bash

The if statement actually uses the program 'test' for the tests. You could write if statements two ways:

if [ -e filename ];

or

if test -e filename;

If you know this, you can easily check the man page for 'test' to find out the meanings of the different tests:

man test

Solution 4 - Bash

-e checks for any type of filesystem object; -f only checks for a regular file.

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
QuestionAhatiusView Question on Stackoverflow
Solution 1 - BashEmil VataiView Answer on Stackoverflow
Solution 2 - BashjmanView Answer on Stackoverflow
Solution 3 - BashgitaarikView Answer on Stackoverflow
Solution 4 - BashIgnacio Vazquez-AbramsView Answer on Stackoverflow