Tuesday, September 19, 2017

One of the most common task in any Linux is creating directories, and most of us spend a lot of time creating complex directory structure in UNIX. I am sure you know about mkdir command, we have been using this command in almost every operating system e..g DOS, Windows, Linux, OS/2, Solaris or many other *NIX operating system. It is one of the basic command but as important as find, grep or chmod. mkdir stands for "make directory" and this command is literally used to create directories. Suppose, you need to create a directory tree like /opt/software/java/app/config, how are you going to create these directories? One by one right? Well, yes you can use mkdir and command to create these directories one by one as shown in below example :

This would take almost 8 commands to create above directory structure, unfortunately you just can not type mkdir/opt/software/java/app/config, because parent directories does not exists.

It will simply fail, by the way there is a trick here, you can use mkdir -p command option to create intermediate directories along the way e.g. if /opt exists but /opt/software doesn't you can still use mkdir-p/opt/software/java/app/config to create exact same directory structure as shown below

mkdir command Example in UNIX

Interestingly, mkdir is one of the simplest command in UNIX, I guess only one which is close to second simple is pwd. mkdir stands for "make directory" and just has two main command line option, other than -v which stands for verbose and prints a message for each created directory.

-m stands for mode, and used to set the access mode for the new directory.

On the other hand, our -p option will create test/coding/java directory in one shot.

mkdir-p~/test/coding/java

You can create even very complex directory structure like UNIX file system (as shown in following diagram) using mkdir -p command.

mkdir command: "Permission denied" error in UNIX

By the way, sometime if you try to create a directory like this(mostly in directory you don't own) :

$ mkdir dropbox

you may see following error

mkdir: cannot create directory 'dropbox': Permission denied

As error message is suggesting, you don't have permission to create this directory in your current working directory. You can use the ls (list) command to figure out what permission you have in your current working directory.

I am sure this simple mkdir command option will save your immense time and effort while working in UNIX. It's great tool to create or replicate complex directory structure or tweak them. Ever since I have learned this trick, I don't remember creating directories one by one in UNIX. So remember, mkdir-p command allow you to create intermediate directory along the way.