Linux / UNIX: Find Out If a Directory Exists or Not

by on November 16, 2008 · 6 comments· LAST UPDATED November 16, 2008

in , ,

I've already written a small tutorial about finding out if a file exists or not under Linux / UNIX bash shell. However, couple of our regular readers like to know more about a directory checking using if and test shell command.

General syntax to see if a directory exists or not

[ -d directory ]
OR
test directory
See if a directory exists or not with NOT operator:
[ ! -d directory ]
OR
! test directory

Find out if /tmp directory exists or not

Type the following command:
$ [ ! -d /tmp ] && echo 'Directory /tmp not found'
OR
$ [ -d /tmp ] && echo 'Directory found' || echo 'Directory /tmp not found'

Sample Shell Script to gives message if directory exists

Here is a sample shell script:

#!/bin/bash
DIR="$1"
 
if [ $# -ne 1 ]
then
	echo "Usage: $0 {dir-name}"
	exit 1
fi
 
if [ -d "$DIR" ]
then
	echo "$DIR directory  exists!"
else
	echo "$DIR directory not found!"
fi
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 6 comments… read them below or add one }

1 aneesh November 18, 2008 at 5:29 am

Dear Friends,

We can do the same thing to check a file exist or not by modifying the “if” loop like the following.

!/bin/bash
FILE=”$1″

if [ $# -ne 1 ]
then
echo “Usage: $0 {file-name}”
exit 1
fi

if [ -f "$FILE" ]
then
echo “$FILE file exists!”
else
echo “$FILE file not found!”
fi

Reply

2 Vamsi October 27, 2010 at 9:11 am

u can use test -f to check whether filename exists or not
u can use test -d to check whether directoryname exists or not

Returns “zero” if exists and “one” if doesn’t exist.

Reply

3 Raj Shah August 28, 2013 at 11:02 am

# [ -f /path/to/dir/file_name ] && echo “File Found” || echo “File not found”

Reply

4 vignesh December 14, 2011 at 1:15 pm

i need to print the file names of all files having .txt extension of a given directory after converting to uppercase letters. The input (directory name) should be given as command line argument. The script will also check whether sufficient arguments are passed or not and whether the argument is a directory or not

i tried using this code

if [ -f $filename ]
tr “[a-z]” “[A-Z]” <$filename

but i dint get output

Reply

5 Qrious November 21, 2012 at 11:46 am

Helps me a lot !
Thanks for posting..

Reply

6 John McLean October 10, 2013 at 4:32 pm

easier method:

ls -d /some/carzy/directory/does/it/exist
ls: cannot access /some/carzy/directory/does/it/exist: No such file or directory

Reply

Leave a Comment

Tagged as: , , , , , , , , , , ,

Previous post:

Next post: