FUNDAMENTALS A Complete Guide for Beginners
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.
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
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.
From the image, you can see that the directory var_dir exists in my ‘home’ directory.
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
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.
In this image, you can see that the directory template exists in my ‘home’ directory.
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
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.
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
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.’.
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
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.
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
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.
In 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
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.
You 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
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.
As 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
-
- Quoting variables with double quotes to prevent word splitting and globbing.
- Escaping when dealing with directory names with special characters.
- 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
- Mastering 10 Essential Options of If Statement in Bash
- How to Check a Boolean If True or False in Bash [Easy Guide]
- Bash Test Operations in ‘If’ Statement
- Check If a Variable is Empty/Null or Not in Bash [5 Methods]
- Check If a Variable is Set or Not in Bash [4 Methods]
- Check If Environment Variable Exists in Bash [6 Methods]
- Bash Modulo Operations in “If” Statement [4 Examples]
- How to Use “OR”, “AND”, “NOT” in Bash If Statement [7 Examples]
- Evaluate Multiple Conditions in Bash “If” Statement [2 Ways]
- Using Double Square Brackets “[[ ]]” in If Statement in Bash
- 6 Ways to Check If a File Exists or Not in Bash
- How to Check If a File is Empty in Bash [6 Methods]
- Negate an “If” Condition in Bash [4 Examples]
- Check If Bash Command Fail or Succeed [Exit If Fail]
- How to Write If Statement in One Line? [2 Easy Ways]
- Different Loops with If Statements in Bash [5 Examples]
- How to Use Flags in Bash If Condition? [With Example]
- Learn to Compare Dates in Bash [4 Examples]
<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial