[shell] How to mkdir only if a directory does not already exist?

I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the mkdir command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that mkdir throws when it tries to create an existing directory.

How can I best do this?

This question is related to shell scripting ksh aix mkdir

The answer is


mkdir does not support -p switch anymore on Windows 8+ systems.

You can use this:

IF NOT EXIST dir_name MKDIR dir_name

directory_name = "foo"

if [ -d $directory_name ]
then
    echo "Directory already exists"
else
    mkdir $directory_name
fi

This should work:

$ mkdir -p dir

or:

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$dir already exists but is not a directory" 1>&2
fi

which will create the directory if it doesn't exist, but warn you if the name of the directory you're trying to create is already in use by something other than a directory.


Referring to man page man mkdir for option -p

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

which will create all directories in a given path, if exists throws no error otherwise it creates all directories from left to right in the given path. Try the below command. the directories newdir and anotherdir doesn't exists before issuing this command

Correct Usage

mkdir -p /tmp/newdir/anotherdir

After executing the command you can see newdir and anotherdir created under /tmp. You can issue this command as many times you want, the command always have exit(0). Due to this reason most people use this command in shell scripts before using those actual paths.


mkdir foo works even if the directory exists. To make it work only if the directory named "foo" does not exist, try using the -p flag.

Example:

mkdir -p foo

This will create the directory named "foo" only if it does not exist. :)


This is a simple function (Bash shell) which lets you create a directory if it doesn't exist.

#----------------------------------
# Create a directory if it doesn't exist
#------------------------------------
createDirectory() {
    if [ ! -d $1 ]
        then
        mkdir -p $1
    fi
}

You can call the above function as:

createDirectory /tmp/fooDir/BarDir

The above creates fooDir and BarDir if they don't exist. Note the "-p" option in the mkdir command which creates directories recursively.


mkdir -p sam
  • mkdir = Make Directory
  • -p = --parents
  • (no error if existing, make parent directories as needed)

Defining complex directory trees with one command

mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

Or if you want to check for existence first:

if [[ ! -e /path/to/newdir ]]; then
            mkdir /path/to/newdir
fi

-e is the exist test for KornShell.

You can also try googling a KornShell manual.


The old tried and true

mkdir /tmp/qq >/dev/null 2>&1

will do what you want with none of the race conditions many of the other solutions have.

Sometimes the simplest (and ugliest) solutions are the best.


Simple, silent and deadly:

mkdir -p /my/new/dir >/dev/null 2>$1

Use the -p flag.

man mkdir
mkdir -p foo

If you don't want to show any error message:

[ -d newdir ] || mkdir newdir

If you want to show your own error message:

[ -d newdir ] && echo "Directory Exists" || mkdir newdir

You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory.

  1. dir=/home/dir_name

    if [ ! -d $dir ]
    then
         mkdir $dir
    else
         echo "Directory exists"
    fi
    
  2. You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.

    mkdir -p $dir
    

    mkdir -p also allows to create the tree structure of the directory. If you want to create the parent and child directories using same command, can opt mkdir -p

    mkdir -p /home/parent_dir /home/parent_dir/child1 /home/parent_dir/child2
    

if [ !-d $dirName ];then
     if ! mkdir $dirName; then  # Shorter version. Shell will complain if you put braces here though
     echo "Can't make dir: $dirName"
     fi
fi

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to scripting

What does `set -x` do? Creating an array from a text file in Bash Windows batch - concatenate multiple text files into one Raise error in a Bash script How do I assign a null value to a variable in PowerShell? Difference between ${} and $() in Bash Using a batch to copy from network drive to C: or D: drive Check if a string matches a regex in Bash script How to run a script at a certain time on Linux? How to make an "alias" for a long path?

Examples related to ksh

How can I find a file/directory that could be anywhere on linux command line? Shell Script: How to write a string to file and to stdout on console? Send password when using scp to copy files from one server to another Reading file line by line (with space) in Unix Shell scripting - Issue How to get the second column from command output? Get exit code for command in bash/ksh Check if file exists and whether it contains a specific string In a unix shell, how to get yesterday's date into a variable? How to set the From email address for mailx command? How to mkdir only if a directory does not already exist?

Examples related to aix

Changing an AIX password via script? Find files in created between a date range How to ignore conflicts in rpm installs Create a copy of a table within the same database DB2 ORA-00060: deadlock detected while waiting for resource How to get the command line args passed to a running process on unix/linux systems? How to mkdir only if a directory does not already exist? What is the unix command to see how much disk space there is and how much is remaining?

Examples related to mkdir

How to create nested directories using Mkdir in Golang? Bash mkdir and subfolders How to create a directory and give permission in single command Recursive mkdir() system call on Unix How to create new folder? How to mkdir only if a directory does not already exist? mkdir -p functionality in Python Is there a way to make mv create the directory to be moved to if it doesn't exist?