Check if a directory exists in Linux or Unix shell

I need to check if a directory exists or not, within a shell script running on Linux or Unix-like system? How do I check if a directory exists in a shell script?

A directory is nothing but a location for storing files on the Linux system in a hierarchical format. For example, $HOME/Downloads/ would store all downloaded files or /tmp/ would store temporary files. This page shows how to see if a directory exists in Linux or Unix-like systems.

How to check if a directory exists in Linux

  1. One can check if a directory exists in a Linux shell script using the following syntax:
    [ -d "/path/dir/" ] && echo "Directory /path/dir/ exists."
  2. You can use ! to check if a directory does not exists on Unix:
    [ ! -d "/dir1/" ] && echo "Directory /dir1/ DOES NOT exists."

One can check if a directory exists in Linux script as follows:

DIR="/etc/httpd/"
if [ -d "$DIR" ]; then
  # Take action if $DIR exists. #
  echo "Installing config files in ${DIR}..."
fi

OR

DIR="/etc/httpd/"
if [ -d "$DIR" ]; then
  ### Take action if $DIR exists ###
  echo "Installing config files in ${DIR}..."
else
  ###  Control will jump here if $DIR does NOT exists ###
  echo "Error: ${DIR} not found. Can not continue."
  exit 1
fi

Always enclose “$DIR” in double-quotes to deal with directories having white/black spaces in their names. For instance:

DIR="/home/project/Data Files/"
if [ -d "$DIR" ]; then
   echo "'$DIR' found and now copying files, please wait ..."
else
   echo "Warning: '$DIR' NOT found."
fi

A note about symbolic links (symlink)

Directories with symbolic links need special consideration as follows using the -L switch:

DEST="/aws/efs/shared/nixcraft.com/"
if [ -d "$DEST" ]; then 
  if [ -L "$DEST" ]; then
    # It is a symbolic links #
    echo "Symbolic link found and doing something on it ..."
  else
    # It is a directory #
    echo "Directory found and doing nothing here ..."
  fi
fi

Linux check if a directory exists and take some action

Here is a sample shell script to see if a folder exists or not in Linux:

#!/bin/bash
d="$1"
 
[ "$d" == "" ] && { echo "Usage: $0 directory"; exit 1; }
[ -d "${d}" ] &&  echo "Directory $d found." || echo "Directory $d not found."

Run it as follows:
./test.sh
./test.sh /tmp/
./test.sh /nixCraft

Check if directory exists in bash and if not create it

Here is a sample shell script to check if a directory doesn’t exist and create it as per our needs:

#!/bin/bash
dldir="$HOME/linux/5.x"
_out="/tmp/out.$$"
 
# Build urls
url="some_url/file.tar.gz"
file="${url##*/}"
 
### Check for dir, if not found create it using the mkdir ##
[ ! -d "$dldir" ] && mkdir -p "$dldir"
 
# Now download it
wget -qc "$url" -O "${dldir}/${file}"
 
# Do something else below #

Make sure you always wrap shell variables such as $DIR in double quotes ("$DIR" to avoid any surprises in your shell scripts:

DIR="foo"
[ -d "$DIR" ] && echo "Found"
##
## this will fail as DIR will only expand to "foo" and not to "foo bar stuff" 
## hence wrap it 
##
DIR="foo bar stuff"
[ -d $DIR ] && echo "Found"

Using test command

One can use the test command to check file types and compare values. For example, see if FILE exists and is a directory. The syntax is:
test -d "DIRECTORY" && echo "Found/Exists" || echo "Does not exist"
The test command is same as [ conditional expression. Hence, you can use the following syntax too:
[ -d "DIR" ] && echo "yes" || echo "noop"

Getting help

Read bash shell man page by typing the following man command or visit online here:
man bash
help [
help [[
man test

Conclusion

This page explained various commands that can be used to check if a directory exists or not, within a shell script running on Linux or Unix-like systems. The -d DIR1 option returns true if DIR1 exists and is a directory. Similarly, the -L DIR1 option returns true if DIR1 found and is a symbolic links.


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum