mkdir if directory does not exist

How to mkdir Only if Directory Does Not Exist

Sometimes you may need to create directory only if it doesn’t exist in Linux. You can easily do this using mkdir command. In this article, we will learn how to create directory if it doesn’t exist.


How to mkdir Only if Directory Does Not Exist

Generally, if you create directory that already exists, you will get an error. Here is an example.

$ mkdir var/data/backup
mkdir: cannot create directory ‘data/backup’: File exists

If you are running a script that requires creation of directory, then this kind of error can make your script stop running.

mkdir command provides -p option that automatically checks if the parent folder exists. It is used to crate multilevel nested directories by checking parents. You can also use this command to check if the directory exists, before creating it. In this case, if the specified directory already exists, mkdir command will skip it.

Here is an example.

$ mkdir -p var/data/backup

Alternatively, you can suppress this error by redirecting the error message to /dev/null.

$ mkdir /var/data/backup >/dev/null 2>&1

You can also use -d flag to check if a directory exists, and create directory only if it doesn’t exist. Here is an example. We have used an OR conditional operator with first condition checking if the directory exists or not. If the directory does not exist, it will return False and then the second condition is executed.

[ -d /var/data/backup ] || mkdir var/data/backup

On the other hand, if directory exists, the first condition evaluates to True and the second condition is not executed.

In this article, we have learnt how to create directory only if it doesn’t exist.

Also read:

How to Create Nested Directory in Linux
How to Create CA Bundle from CRT Files for SSL certificates
How to Copy Files from Linux to Windows
How to Copy Files from Linux to S3 Bucket
How to Fix Permission Denied Error While Using Cat Command

Leave a Reply

Your email address will not be published. Required fields are marked *