Bash: Check if Directory or File Exists

Introduction

It is important to check for the existence of directories and files in Bash scripts for several reasons. Firstly, it allows the script to handle situations where the expected directories or files do not exist. This can prevent errors and unexpected behavior in the script - if a script expects a certain file to be present in a certain directory, and that file does not exist, the script will fail if it does not check for the file's existence first.

Secondly, checking for the existence of directories and files can help to ensure that the script is running in the correct environment. Some scripts are intended to run on a system with a specific directory structure or set of files. By checking for the existence of these directories and files, the script can ensure that it is running in the correct environment before attempting to execute its tasks.

Finally, checking for the existence of directories and files can help to make Bash scripts more efficient by avoiding unnecessary tasks. If a script does not need to create a new directory if it already exists, the script can check for the directory's existence first and only create it if necessary. This can save time and resources compared to blindly creating the directory every time the script is run.

In this article, we'll take a look at several most common methods you can use to check if a file or directory exists in Bash.

How to Check if a Directory Exists in Bash

There are several methods for checking for the existence of directories in Bash, and all of them are pretty similar to methods for checking for file existence. In this section, we'll take a look at several methods to do so. Each of the covered methods can be easily altered to check for the existence of files in Bash, too. But we'll go over that in the latter sections. For now, let's just focus on checking for the existence of a directory.

Method 1: The if [ -d $directory ] Command ([ Operator)

The if [ -d $directory ] command can be used to check for the existence of a directory. If the specified directory exists, the command will return an exit status of 0 (true). If the directory does not exist, the command will return a non-zero exit status (false).

Let's take a look at the general syntax of the [ -d $directory ] command:

if [ -d "$directory" ]
then
    # code to execute if $directory exists
else
    # code to execute if $directory does not exist
fi

Note: In this example, the $directory represents the name of the directory you want to check for.

As you probably guessed, if the directory exists, the code within the then block will be executed. If the directory does not exist, the code within the else block will be executed.

Now we can take a look at the practical example of how you might use this command in a Bash script:

# Check if the /my-dir directory exists
directory="/my-dir"
if [ -d "$directory" ]
then
    # The /my-dir directory exists, so print a message
    echo "The /my-dir directory exists."
else
    # The /my-dir directory does not exist, so print a message and create it
    echo "The /my-dir directory does not exist. Creating it now..."
    mkdir $directory
fi

The script first checks if the /my-dir directory exists. If it does, a message is printed to the console. If the /my-dir directory does not exist, a message is printed and the /my-dir directory is created using the mkdir command.

Note: If you need to check if a directory/file does not exist you can just add the not logical operator (!) inside the [ operator. For example: if [ ! -d "$directory" ].

Method 2: The test Command

To use the test command to check if a directory exists in Bash, you can use the following syntax:

if test -d $directory
then
    # code to execute if $directory exists
else
    # code to execute if $directory does not exist
fi

As in the previous example, the $directory represents the name of the directory you want to check for. If the directory exists, the code within the then block will be executed. If the directory does not exist, the code within the else block will be executed.

Here is an example of how you might use this command in a Bash script:

# Check if the /my-dir directory exists
directory="/my-dir"
if test -d $directory
then
    # The /my-dir directory exists, so print a message
    echo "The /my-dir directory exists."
else
    # The /my-dir directory does not exist, so print a message and create it
    echo "The /my-dir directory does not exist. Creating it now..."
    mkdir $directory
fi

Here, the script first checks if the /my-dir directory exists using the test -d command. If it does, a message is printed to the console. If the /my-dir directory does not exist, a message is printed and the /my-dir directory is created using the mkdir command.

Note: The [ operator is an alias for the test command in Bash, so you could also use the [ -d $directory ] syntax to achieve the same result.

Method 3: The [[ Operator

To use the [[ operator to check if a directory exists in Bash, you can use the syntax similar to one seen in previous methods:

if [[ -d $directory ]]
then
    # code to execute if $directory exists
else
    # code to execute if $directory does not exist
fi

You guessed it, the $directory represents the name of the directory you want to check for. As we've seen in previous sections, if the directory exists, the code within the then block will be executed. If the directory does not exist, the code within the else block will be executed.

Here is an example of how you might use [[ operator in a Bash script:

# Check if the /my-dir directory exists
directory="/my-dir"
if [[ -d $directory ]]
then
    # The /my-dir directory exists, so print a message
    echo "The /my-dir directory exists."
else
    # The /my-dir directory does not exist, so print a message and create it
    echo "The /my-dir directory does not exist. Creating it now..."
    mkdir $directory
fi
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Note: The [[ operator is a more powerful version of the [ operator, and is generally preferred in Bash scripts due to its additional features and improved syntax. However, the [ and [[ operators can generally be used interchangeably. If you are interested in a more in-depth overview of the differences between those two operators, you should read our "Bash: Difference Between [ and [[ Operators".

How to Check if a File Exists in Bash

All of the above is pretty much applicable in the case you want to check if a file exists - there are only a few trivial changes that you need to perform in order to make previous scripts compatible with the new use case. Therefore, in this section, we won't dig deep into each method, we'll just go over code snippets that show exactly how to check for the file existence in Bash. Let's start with the if [ -f $file ] command.

Method 1: The if [-f $file] Command

The if [ -f $file ] command is the equivalent of the if [ -d $directory ] command. They are pretty much the same, apart from the -f and -d arguments:

# Check if the 'my-file.txt' exists
file="/my-file.txt"
if [ -f "$file" ]
then
    # The 'my-file.txt' exists, so print a message
    echo "The 'my-file.txt exists."
else
    # The 'my-file.txt' does not exist, so print a message and create it
    echo "The 'my-file.txt' does not exist. Creating it now..."
    mkdir $file
fi

Method 2: The test Command

Also, the test command used to check for the existence of directories can be used to verify the (non)existence of a file:

# Check if the 'my-file.txt' directory exists
file="my-file.txt"
if test -f $file
then
    # The 'my-file.txt' file exists, so print a message
    echo "The 'my-file.txt' file exists."
else
    # The 'my-file.txt' file does not exist, so print a message and create it
    echo "The 'my-file.txt' file does not exist. Creating it now..."
    mkdir $file
fi

Method 3: The [[ Operator

And, finally, the [[ can also be used for the purpose of checking if a file exists in Bash:

# Check if the 'my-file.txt' file exists
file="my-file.txt"
if [[ -d $file ]]
then
    # The 'my-file.txt' file exists, so print a message
    echo "The 'my-file.txt' file exists."
else
    # The 'my-file.txt' file does not exist, so print a message and create it
    echo "The 'my-file.txt' file does not exist. Creating it now..."
    mkdir $file
fi

Conclusion

In conclusion, being able to check if a file or directory exists in Bash is a crucial skill for any Linux administrator or developer. The main methods we've discussed in this article are [ and [[ operators, as well as the test command in Bash. Additionally, the ls command can also be used to check for file or directory existence, although it is less efficient and less versatile. By understanding and utilizing these methods, you will be able to easily check for file or directory existence in Bash and take appropriate actions based on the outcome.

Last Updated: January 20th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms