[bash] 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 am looking to only run mkdir if the dir doesn't exist. Is this possible?

This question is related to bash unix

The answer is


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

or

mkdir -p directory

-p ensures creation if directory does not exist


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.

mkdir -p

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


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