Tuesday, November 18, 2008

How to check whether the directory is exist or not in Linux

General syntax to see if a directory exists or not

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

Find out if /tmp directory exists or not

Type the following command:
$ [ ! -d /tmp ] && echo 'Directory /tmp not found'
$ [ -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