Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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