Only mkdir if it does not exist

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'm only looking to run mkdir if the directory does not exist. Is it possible?

+50
unix bash
Sep 04 '13 at 20:11
source share
5 answers

Take a test

 [[ -d dir ]] || mkdir dir 

Or use the -p option:

 mkdir -p dir 
+119
Sep 04 '13 at 20:12
source share
 if [ ! -d directory ]; then mkdir directory fi 

or

 mkdir -p directory 

-p provides creation if directory does not exist

+37
Sep 04 '13 at 20:16
source share

Use the mkdir -p option, but note that it has a different effect.

  -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. 
+8
Sep 04 '13 at 20:13
source share

mkdir -p

-p, --parents no error, if it exists, create parent directories if necessary

+3
Sep 04 '13 at 20:12
source share

Try using: -

 mkdir -p dir; 

NOTE. - . It will also create any staging directories that do not exist; eg,

Check out mkdir -p

or try the following: -

 if [[ ! -e $dir ]]; then mkdir $dir elif [[ ! -d $dir ]]; then echo "$Message" 1>&2 fi 
+2
Sep 04 '13 at 20:13
source share



All Articles