≡ Menu

linux directory exists

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

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