160

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?

More Than Five
  • 9,959
  • 21
  • 77
  • 127

5 Answers5

293

Do a test

[[ -d dir ]] || mkdir dir

Or use -p option:

mkdir -p dir
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • 3
    I can't find the source on the fly, but for Makefiles `mkdir -p` is discouraged b/c there may be race conditions in concurrent execution. So, depending on what your script does and in which environment it lives the first option given is this answer should be preferred. Also, you could just `mkdir product 2>/dev/null` and not care. – user1129682 Sep 04 '13 at 20:47
  • 6
    @user1129682: The first option also has a potential race condition; the directory could be created by some other process between the `-d` test and the `mkdir`. I suspect `mkdir -p` makes this time window for this race condition slightly shorter. – Keith Thompson Sep 04 '13 at 21:29
  • 1
    Beside the race condition in the innecessary testing, there is also the possibility that `dir` does exist **but is not a directory**, but a file or a device entry or a unix-domain socket or a named pipe, or _whatever_ ... – wildplasser Sep 04 '13 at 22:10
  • 1
    @wildplasser Yes and that would already be in the coder's option how he/she would handle the situation. One could send a message to the user and ask for input, abort, or do other things if `[[ -e dir && ! -d dir ]]` is valid. – konsolebox Sep 04 '13 at 22:17
  • 1
    Useful and concise, +1 :) – zx81 Jul 21 '14 at 09:29
  • Anyway, you should just have in mind @andy-lester 's remark in the answer below. – Lomefin Dec 27 '20 at 18:49
152
if [ ! -d directory ]; then
  mkdir directory
fi

or

mkdir -p directory

-p ensures creation if directory does not exist

sr01853
  • 6,043
  • 1
  • 19
  • 39
12

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.
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
5

mkdir -p

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

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
5

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
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331