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

by Vivek Gite on November 16, 2008 · 3 comments

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

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

We're here to help you make the most of sysadmin work. So, subscribe!

{ 3 comments… read them below or add one }

1 aneesh November 18, 2008

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

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 vignesh December 14, 2011

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

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 10 + 3 ?
Please leave these two fields as-is:
Are you a human being? Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: