Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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

Footnotes And References