≡ Menu

shell script if 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

With the help of BASH shell and IF command it is possible to find out if file exists or not. Generally, this is known as conditional expressions. Conditional expressions are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons. General syntax:

[ parameter FILE ]
OR
test parameter FILE

Where parameter can be any one of the following:

  • -e: Returns true value if file exists
  • -f: Return true value if file exists and regular file
  • -r: Return true value if file exists and is readable
  • -w: Return true value if file exists and is writable
  • -x: Return true value if file exists and is executable
  • -d: Return true value if exists and is a directory

Examples

Find out if file /etc/passwd file exists or not

Type the following commands:
$ [ -f /etc/passwd ] && echo "File exists" || echo "File does not exists"
$ [ -f /tmp/fileonetwo ] && echo "File exists" || echo "File does not exists"

Find out if directory /var/logs exists or not

Type the following commands:
$ [ -d /var/logs ] && echo "Directory exists" || echo "Directory does not exists"
$ [ -d /dumper/fack ] && echo "Directory exists" || echo "Directory does not exists"

You can use conditional expressions in a shell script:

#!/bin/bash
FILE=$1
 
if [ -f $FILE ];
then
   echo "File $FILE exists"
else
   echo "File $FILE does not exists"
fi
 

Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf

You can use this technique to verify that backup directory and backup source directory exits See example script for more information.