How to Check If Directory Exists or Not in Bash? [5 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

To check if a directory exists or not in Bash, use the code below:

if [ -d /path/to/directory ]; then
  echo "Directory exists."
else
  echo "Directory doesn't exist."
fi

In Bash scripting, checking the existence of a directory in Bash involves evaluating the presence of a directory in a specified path. You can perform various test operations within ‘if’ conditional statements to check whether a directory exists or not in Bash. Moreover, you can make a directory by using the “mkdir -p” command when it doesn’t exist in Bash.

In this article, I will demonstrate 5 ways to check if a directory exists in Bash.

5 Ways to Check If a Directory Exists in Bash

To check if a directory exists in Bash, you can use several methods such as using “test” command or “[ ]” construct, “[[ ]]” construct, “ls” command, “find” command, “-L” operator with “-d” operator. You can also check if multiple directories exist by using the loop iteration process and logical operators in Bash.

Note: You cannot check a directory’s existence if you don’t have read permissions for that directory in Bash. However, you will get a Permission denied error.

1. Using “-d” Option

The “-d” test operator in Bash is used to check if a directory exists in the defined path. If the specified directory exists, it returns an exit status of zero (0) i.e. a true expression. Otherwise, it returns a non-zero exit status.

Here’s an example to verify the existence of a directory in Bash by using the “-d” construct:

#!/bin/bash

#Checking if the directory exists
if [ -d /home/nadiba/var_dir ]; then #Providing information in /path/to/directory
echo "'var_dir' directory exists."
fi

EXPLANATION

The ‘if’ conditional in this script, checks if the given path corresponds to an existing directory or not. If the condition is satisfied, it returns a true expression and the script displays ‘var_dir’ directory exists.’. Otherwise, it returns nothing.

Checking if a directory exists using "-d" operator with "[ ]" construct

From the image, you can see that the directory var_dir exists in my ‘home’ directory.

Note: You can use [[  ]] instead of [ ] in the above script.

2. Using “test” Command

To check if a directory exists using the test command in Bash, you can use the -d option followed by the directory path. Here’s how you can do it:

#!/bin/bash

my_directory="/home/nadiba/template" 

if [[ -d "$my_directory" ]]; then
echo "The directory ‘template’ exists."
fi

EXPLANATION

Here, if [[ -d "$my_directory" ]]; checks whether the path corresponds to the specific directory exists or not in user’s system. If the script test expression finds the directory it returns a successful exit status.

Checking if a directory exists using "-d" operator with "[[ ]]" construct

In this image, you can see that the directory template exists in my ‘home’ directory.

Note: Make sure to insert the spaces between the [ ] or [[ ]] constructs and a semicolon at the end of the brackets.

3. Using the “-L” Operator to Check Symlinks to a Directory

The “-L” is a file test operator in Bash that checks whether a specified path exists and is a symbolic link (symlink). You can combine this “-L” operator with the “-d” operator to verify if the symlink points to a directory or any file. This is an indirect process to check the existence of a directory corresponding to symlinks.

Explore the script below to check the existence of a directory in Bash using “-L” operator:

#!/bin/bash

#Checking if the symlink 'xyz' points to a directory
if [[ -L "xyz" && -d "xyz" ]]; then
  echo "The symlink 'xyz' points to a directory."
fi

EXPLANATION

In this script, the ‘if’ conditional checks if ‘xyz’ is both a symbolic link and directory using the && operator. If both conditions are satisfied, then the script returns a true expression and  displays an output message. But if any of these conditions is false, the script returns nothing.

Checking the existence of a directory pointed by a symlink by using the "-L" and "-d" operators

From the above image, you can see that xyz is a symbolic link and it points to a directory as well.

4. Using “ls” Command

The “ls” command in Bash does not check the existence of a directory directly. It is mainly used to list the contents of a directory. However, it can be used along with the ‘if’ conditional statements to indirectly check the existence of the directories in Bash.

Go through the following script to verify the existence of a directory in Bash by using the “ls” command:

#!/bin/bash

if ls "/home/nadiba/Desktop/linuxsimply" >/dev/null 2>&1; then #Providing information in /path/to/directory
  echo "The directory exists."
fi

EXPLANATION

In the script, the conditional expression checks if the ls command lists all the contents of the directory linuxsimply inside ‘/home/nadiba/Desktop’ where the output (stdout) is redirected to /dev/null. In addition, 2>&1 redirects the error output (stderr) to the same place as the standard output. However, the combination >/dev/null 2>&1 is used to suppress both output and error messages that the “ls” command generates. Finally, if the “ls” command succeeds, the conditional expression evaluates to true and executes ‘The directory exists.’.

Checking if a directory exists using "ls" command

In the image, the directory linuxsimply exists in the ‘Desktop’ directory of my system.

5. Using “find” Command

The “find” command in Bash is used to search for files and directories within a specified directory hierarchy based on various criteria. It’s highly flexible when checking a directory that matches a particular pattern.

To check if a directory exists in Bash using “find” command, you can follow the below script:

#!/bin/bash

directory_path="/home/nadiba/Documents/ubuntu" #Providing information in /path/to/directory

if find "$directory_path" -type d -print -quit | grep -q .; then
  echo "The directory 'ubuntu' exists."
fi

EXPLANATION

First, the find command within the ‘if’ statement searches for the directories within the specified path where the -print -quit helps the “find” command to print the first directory found in the path and then quit the search. Then, the output of the “find” command is redirected to the grep command and the -q flag with the “grep” command only sets the exit status for the match where ‘.’ indicates the pattern being searched for. If the condition is true, it displays a successful output.

Checking if a directory exists using "find" command

In the snapshot above you can see that the directory ubuntu exists in the ‘Documents’ directory of my system.

How to Check If Multiple Directories Exist in Bash?

When you have several directories and you want to verify the existence of each one, then Bash helps you to accomplish the task using a loop. You can use the for loop with ‘if’ statement to iterate through all the directory paths and perform the conditional test.

Navigate through the script below to check if multiple directories exist in Bash:

#!/bin/bash

#Defining directory paths with an array
multi_directories=("/home/nadiba/Pictures" "/home/nadiba/Documents" "/home/nadiba/Downloads")

#Looping through each directory path to check the existence
for directory in "${multi_directories[@]}"; do
  if [[ -d "$directory" ]]; then
    echo "Directory '$directory' exists."
  fi
done

EXPLANATION

Here, the for loop iterates through each directory in the multi_directories array and inside the loop, the ‘if’ conditional statement evaluates whether the current directory specified by $directory exists. If the directory exists, the script executes a true expression by printing each output message for each directory.

Checking the existence of multiple directories using 'for' loopIn the image, all the directories Pictures, Documents and Downloads exist in the ‘home’ directory of my system.

How to Check If a Directory Doesn’t Exist in Bash?

If you want to check if a directory does not exist, use the NOT (!) operator and negate the conditional expressions i.e. it inverts the output expression of the conditional statements.

Check out the script below to verify if a directory doesn’t exist in Bash:

#!/bin/bash

directory_path=/home/music

if [ ! -d "$directory_path" ]; then
echo "The directory 'music' does not exist."
fi

EXPLANATION

Here, if [ ! -d "$directory_path" ]; checks whether the directory ‘music’ does not exist in the specified path. If the directory doesn’t exist, the script returns a true expression. But if the directory exists, it returns nothing.

Checking if a directory does not exist using NOT (!) operatorYou can see from the image that there is no directory named music in my ‘home’ directory.

How to Create a Directory If It Doesn’t Exist in Linux?

To create a directory if it doesn’t exist in Linux, use mkdir command with -p option. The “-p” option along with mkdir command, it allows you to create a directory if it doesn’t exist and the necessary parent directories if required.

Here’s how you can make a directory if it doesn’t exist in Bash:

#!/bin/bash

directory_path="/home/nadiba/Documents/music" 

if [ ! -d "$directory_path" ]; then
  mkdir -p "$directory_path"
  echo "The directory is created."
fi

EXPLANATION

Here, the conditional expression if [ ! -d "$directory_path" ] checks whether the directory ‘music’ exists in the specified path. If the directory doesn’t exist, the script returns a true expression and makes that specific directory in the defined path.

Creating a directory when it doesn't exist in Bash by using the 'mkdir -p' commandAs you can see from the image, the directory music has been created inside ‘/home/nadiba/Documents’, which did not exist previously.

Conclusion

So far, you have learned several ways to check the existence of a directory in Bash scripting. You are now free to choose any method that suits you best and ensure reliable operations and efficient error handling.

People Also Ask

How can I check if a directory exists in Bash?

To check if a directory exists, use the test command in Bash, you can use the -d option followed by the directory path. Here’s how you can do it:

if test -d "/path/to/directory"; then
  echo "Directory exists."
else echo "Directory does not exist."
fi

Replace “/path/to/directory” with the actual path to the directory you want to check. If the directory exists, the script will print “Directory exists.”; otherwise, it will print “Directory does not exist.”.

Is it necessary to check directory existence before performing actions in a script?

Yes, it is necessary to check directory existence before performing actions in a script. Otherwise, you might encounter potential errors within Bash scripts.

Is there a risk of false positives or false negatives when checking directory existence?

Yes, there are risks of false positives or false negatives when checking directory existence in Bash such as permission issues, concurrency issues, symlink issues, etc. Elaborately saying,

  • False positive occurs when the script reports the existence of a directory, but, the directory does not exist or is not accessible due to incorrect permissions, symbolic links issues, etc.
  • False negative occurs when the script reports that a directory does not exist, but it exists in the script due to permission conflicts, misleading path issues, etc.

What is symlink in Linux directory?

A symlink (Symbolic link) in Linux directory is the reference that provides a way to create shortcuts to files or directories in a file system in Bash. Generally, you cannot perform operations for symlinks like regular directories as they are different from regular files and directories.

How do I handle edge cases like spaces or special characters in directory names?

You can handle edge cases like spaces or special characters in directory names by following some best practices such as

    1. Quoting variables with double quotes to prevent word splitting and globbing.
    2. Escaping when dealing with directory names with special characters.
    3. Using arrays when dealing with multiple directories.

Can directory existence checks be nested within conditional statements in Bash?

Yes, directory existence checks can be nested within conditional statements in Bash. For example:

#!/bin/bash

directory="/path/to/directory_name"
subdirectory="sub_directory"

#Checking if the directory exists
if [ -d "$directory" ]; then
  echo "The directory '$directory' exists."
#Checking if the subdirectory within the main directory exists
  if [ -d "$directory/$subdirectory" ]; then
    echo "The subdirectory '$subdirectory' exists within '$directory'."
  else
    echo "The subdirectory '$subdirectory' does not exist within '$directory'."
  fi
else
  echo "The directory '$directory' does not exist."
fi

Related Articles


<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment