Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only mkdir if it does not exist [duplicate]

Tags:

bash

unix

In my bash script I do:

mkdir product;

When I run the script more than once I get:

mkdir: product: File exists

In the console.

So I am looking to only run mkdir if the dir doesn't exist. Is this possible?

like image 478
More Than Five Avatar asked Sep 30 '22 18:09

More Than Five


People also ask

How do you mkdir only if a directory does not already exist?

You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory. You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.

What happens if you mkdir a directory that already exists?

mkdir WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.

Does mkdir overwrite existing directories?

1 Answer. Show activity on this post. The mkdir command will create any folders that do not exist in the specified path, unless extensions are disabled ( setLocal enableExtensions ) - regardless, it will not destroy a directory and create a new one with the same name.

What is P flag in mkdir?

-p: A flag which enables the command to create parent directories as necessary. If the directories exist, no error is specified.


1 Answers

Do a test

[[ -d dir ]] || mkdir dir

Or use -p option:

mkdir -p dir
like image 284
konsolebox Avatar answered Oct 17 '22 06:10

konsolebox