The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Checking If A File Or Directory Exists In Bash

TODO: Pull subtitle into page object

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

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Checking If A File Or Directory Exists In Bash


-- h2

Check For Files (multi-line)

-- code
-- bash

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


-- h2

Check For Files (single line)

-- code
-- bash

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



-- h2

Using an else

-- code
-- bash

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


-- h2

Using the "not" operator

-- code
-- bash

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


-- h2

Checking For Directories

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

-- code
-- bash

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

-- p

Or to check if a directory doesn't exist:

-- code
-- bash


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


-- p

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

-- ref
-- url: https://stackoverflow.com/a/59839/102401


-- categories
-- Command Line 
-- Bash

-- metadata
-- date: 2013-02-11 20:16:43
-- id: 017k5zkb
-- status: published
-- type: post
-- site: aws