mkdir – create a directory

mkdir command is one of the basic Unix commands which allows you to create new directories.

Basic mkdir usage

In its simplest form, mkdir takes one or more directory names as command line parameters.

Creating only one directory:

bash-2.05b$ mkdir /tmp/newdir

Creating a few directories at a time:

bash-2.05b$ mkdir /tmp/newdir2 /tmp/newdir3

It’s very easy to verify that these commands have been successful, but getting the list of directories matching the newdir mask in /tmp:

bash-2.05b$ ls -d /tmp/newdir*

/tmp/newdir  /tmp/newdir2  /tmp/newdir3

Troubleshooting mkdir errors

Sometimes you get the mkdir cannot create directory error, usually that’s because specified directory exists or some element of path is missing or restricts you with file/directory permissions.

mkdir and non-existent parent directories

Sometimes you want to create a whole branch of directories tree, with a number of (initially empty) branched directories.

For example, if you decided to create a /tmp/mydir/newdir, and there is no /tmp/mydir directory present in /tmp, you will get an error:

bash-2.05b$ mkdir /tmp/mydir/newdir

mkdir: cannot create directory `/tmp/mydir/newdir': No such file or directory

The reason you get an error is because /tmp/mydir directory does not exist, so your request to create a newdir subdirectory in /tmp/mydir is invalid. The normal approach would be to create /tmp/mydir first, and then issue the same command again:

bash-2.05b$ mkdir /tmp/mydir

bash-2.05b$ mkdir /tmp/mydir/newdir

However, there is a special command line option in mkdir for taking care of non-existent parent directories like this: it’s -p parameter.

Here is the full example of using it, first you see that without the -p you would get an error, and then we verify that the /tmp/mynewdir parent directory was created as part of the mkdir -p command line:

bash-2.05b$ mkdir /tmp/mynewdir/newdir
mkdir: cannot create directory `/tmp/mynewdir/newdir': No such file or directory
bash-2.05b$ mkdir -p /tmp/mynewdir/newdir
bash-2.05b$ ls -d /tmp/mynewdir/
/tmp/mynewdir/
bash-2.05b$ ls -d /tmp/mynewdir/newdir/
/tmp/mynewdir/newdir/

See Also




Contact Me

Follow me on Facebook, Twitter or Telegram:
Recommended
I learn with Educative: Educative
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!
Recent Articles
03 Sep 2024

macOS Sequoia 15.0

02 Sep 2024

Video: Has This Worked Before?

24 Mar 2024

Homelab: Mac Pro 2013 32GB

Recent Tweets