Home

Checking If A File Or Directory Exists In Bash

Check For Files (multi-line)

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

Check For Files (single line)

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

Using an else

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

Using the "not" operator

bash
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:

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

Or to check if a directory doesn't exist:

bash
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

~ fin ~

References