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
Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!
- Email this to a friend
- Printable version
- Rss Feed
- Last Updated: Nov/16/2008

{ 1 comment… read it below or add one }
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