Only mkdir if it does not exist

BashUnix

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

Do a test

[[ -d dir ]] || mkdir dir

Or use -p option:

mkdir -p dir

Solution 2 - Bash

if [ ! -d directory ]; then
  mkdir directory
fi

or

mkdir -p directory

-p ensures creation if directory does not exist

Solution 3 - Bash

Use mkdir's -p option, but note that it has another effect as well.

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

Solution 4 - Bash

mkdir -p

> -p, --parents no error if existing, make parent directories as needed

Solution 5 - Bash

Try using this:-

mkdir -p dir;

NOTE:- This will also create any intermediate directories that don't exist; for instance,

Check out mkdir -p

or try this:-

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$Message" 1>&2
fi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMore Than FiveView Question on Stackoverflow
Solution 1 - BashkonsoleboxView Answer on Stackoverflow
Solution 2 - Bashsr01853View Answer on Stackoverflow
Solution 3 - BashAndy LesterView Answer on Stackoverflow
Solution 4 - BashPaul RubelView Answer on Stackoverflow
Solution 5 - BashRahul TripathiView Answer on Stackoverflow