Commands.page Logo

How to Create Directory Only If It Does Not Exist in Ubuntu

In Ubuntu and other Linux distributions, managing file systems often requires creating new folders without overwriting or causing errors if they are already present. This article explains the most efficient methods to create a directory only if it does not already exist using the terminal. We will cover the standard mkdir command with specific flags and simple conditional scripts to ensure your workflow remains error-free.

Using the mkdir -p Command

The most common and recommended way to create a directory safely is using the mkdir command with the -p flag. This option tells the system to create parent directories as needed and suppresses any error messages if the directory already exists.

mkdir -p /path/to/your/directory

If the directory exists, the command does nothing and returns successfully. If it does not exist, the system creates it. This is ideal for most scripting and manual tasks where you simply need to ensure the folder is present.

Using Conditional Logic

If you need to execute specific commands only when a new directory is actually created, you should use a conditional check. This method verifies the existence of the folder before attempting to make it.

if [ ! -d "/path/to/your/directory" ]; then
    mkdir "/path/to/your/directory"
    echo "Directory created"
else
    echo "Directory already exists"
fi

The -d flag checks if the path exists and is a directory. The ! negates the condition, meaning the mkdir command runs only if the directory is not found.

Using a One-Line Conditional

For shorter scripts or quick terminal commands, you can use the logical OR operator ||. This approach attempts to check the directory and creates it only if the check fails.

[ -d "/path/to/your/directory" ] || mkdir "/path/to/your/directory"

This command checks if the directory exists. If it does, the command stops. If it does not exist, the check fails, and the mkdir command executes to create the folder. This provides a concise solution for ensuring directory existence without verbose scripting.

Conclusion

For most use cases in Ubuntu, mkdir -p is the safest and simplest option. However, if your workflow requires distinct actions based on whether the directory was newly created or already present, using conditional logic with [ -d ] provides the necessary control. Choose the method that best fits your scripting requirements.