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 exist 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

 

Linux check if a directory exists and takes 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 /rootadminz

 

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

 

Was this answer helpful? 0 Users Found This Useful (0 Votes)