Checking If A File Or Directory Exists In Bash

Check For Files (multi-line)

Code

if [ -f "$FILENAME" ]; then
	  echo "The file exists"
fi

Check For Files (single line)

Code

if [ -f "$FILENAME" ]; then echo "The file exists"; fi

Using an else

Code

if [ -f "$FILENAME" ]; then
	echo "Got it."
else
	echo "File not found!"
fi

Using the "not" operator

Code

if [ ! -f "$FILENAME" ]; then
	echo "File not found!"
fi

Checking For Directories

To check if a directory exists in a shell script you can use the following:

Code

if [ -d "$DIRECTORY" ]; then
	echo "It exists"
fi

Or to check if a directory doesn't exist:

Code

if [ ! -d "$DIRECTORY" ]; then
	echo "Directory does not exist"
fi

Symbolic links can cause issues. See the stack overflow question below for some ways to deal with that

References