Check if a File or Directory exists in Bash

This article will introduce how to check if a File or Directory exists in Bash.

1. Check if a File exists

To check if a regular file exists, not a directory, you can use -f.

Note that if it's a directory for the path, it will return False.

#!/bin/bash

File=file.txt
if [ -f "$File" ]; then  
  echo "$File exist "  
fi

Output:

$ bash example.sh
file.txt exist

1.1 other expressions

The code below works the same as the one above. Choose whichever method you prefer.

#!/bin/bash

File=file.txt  

if [[ -f "$File" ]]; then  
  echo "$File exist "  
fi  

1.2 other expressions

The code below works the same as the one above. Choose whichever method you prefer.

#!/bin/bash

File=file.txt

if test -f "$File"; then  
  echo "$File exist "
fi

2. Check if a Directory exists

To check if a directory exists other than a regular file, use -d.

If this operator is used to check a regular file, it will return False.

#!/bin/bash

Dir=mydir

if [ -d "$Dir" ]; then  
  echo "$Dir exist "  
fi

Output:

$ bash example.sh
mydir exist

3. Check if a File or Directory exists

You can use -e to check if a directory or file exists.

It will return true for a directory or file if it exists.

#!/bin/bash

File=mydir

if [ -e "$File" ]; then  
  echo "$File exist "  
fi

Output:

$ bash example.sh
mydir exist

4. File Test Operator

In addition to -f and -d, there are various file test operators.

Please refer to the following.

File Operator Description
-b File Returns 'True' if the FILE exists as a block special file.
-c File Returns 'True' if the FILE exists as a special character file.
-d File Returns 'True' if the FILE exists as a directory.
-e File Returns 'True' if the FILE exists as a file, regardless of type (node, directory, socket, etc.).
-f File Returns 'True' if the FILE exists as a regular file (not a directory or device).
-G File Returns 'True' if the FILE exists and contains the same group as the user is running the command.
-h File Returns 'True' if the FILE exists as a symbolic link.
-g File Returns 'True' if the FILE exists and contains set-group-id (sgid) flag set.
-k File Returns 'True' if the FILE exists and contains a sticky bit flag set.
-L File Returns 'True' if the FILE exists as a symbolic link.
-O File Returns 'True' if the FILE exists and is owned by the user who is running the command.
-p File Returns 'True' if the FILE exists as a pipe.
-r File Returns 'True' if the FILE exists as a readable file.
-S File Returns 'True' if the FILE exists as a socket.
-s File Returns 'True' if the FILE exists and has nonzero size.
-u File Returns 'True' if the FILE exists, and set-user-id (suid) flag is set.
-w File Returns 'True' if the FILE exists as a writable file.
-x File Returns 'True' if the FILE exists as an executable file.

5. References

codechachaCopyright ©2019 codechacha