The mkdir command is one of the most frequently used commands in Linux and UNIX-like operating systems. It allows users to create new directories efficiently from the command line. In this comprehensive guide, we will dive deep into all aspects of mkdir – from basic usage to advanced features and everything in between. Whether you‘re a systems admin managing servers or a developer organizing complex projects, understanding mkdir is essential.

What Exactly Does the mkdir Command Do?

The mkdir command stands for "make directory". As the name indicates, it allows users to create new directories. The command takes in arguments specifying the directory name(s) and path(s) to create, as seen below:

mkdir directory_name

By default it will create the directory as a subdirectory of the current working directory:

# Create directory called code 
mkdir code

You can also specify a full absolute or relative path if you want to put the new directory elsewhere:

# Create directory under home folder
mkdir /home/user/projects 

# Or create relatively from current location 
mkdir ../../documents

Once executed, mkdir will create an empty directory in the specified location. It will not contain any files or subfolders unless you add them after creation.

Below is a diagram visually depicting the directory creation process:

mkdir command logo

Now that we‘ve covered the basics, let‘s explore more examples of properly utilizing mkdir…

Navigating Absolute and Relative Paths

When specifying the directory to create, you can use either absolute paths or relative paths:

Absolute path: Specifies the full directory tree from the root folder (/). For example:

/home/john/projects/code 

Relative path: Specifies the directory relative to your current working directory. For example:

projects/code

To print your current working directory, use the pwd (print working directory) command:

pwd 
/home/john

With that reference point, the relative path makes sense.

Understanding the distinction between absolute and relative paths unlocks the full potential and flexibility of mkdir.

Here is a visual representation to help illustrate the relationship between different file paths:

Absolute vs relative path diagram

While absolute paths explicitly define the location, relative paths are dependent on the executing user‘s current working directory for context.

Creating Parent Directories Automatically

By default, mkdir expects the parent directory in a specified path to exist already. If you attempt to create a subdirectory several levels deep without the parents present, an error will occur:

mkdir /opt/logs/httpd → Error since /opt/logs does not exist!  

To resolve this, the -p flag tells mkdir to automatically create any missing parent directories as needed.

For example:

mkdir -p /opt/logs/httpd

Here, /opt/logs/ and /opt/ would first be created if missing before then creating the httpd subdirectory under logs. No errors!

This applies recursively up the tree allowing you to define entire directory structures in one line.

Creating Multiple Directories at Once

The mkdir command also makes it simple to create multiple directories at the same time by specifying multiple arguments:

mkdir dir1 dir2 dir3

Even more powerful is brace expansion syntax to generate common directory names automatically:

mkdir /var/log/{httpd,nginx,mysql}

This creates /var/log/httpd, /var/log/nginx, and /var/log/mysql in one concise command.

Brace expansion provides a very convenient way to initialize related directories on a system. Sysadmins often have standard directory structures they want on new servers or VM instances, so being able to generate them easily with mkdir saves considerable time.

Permission Issues While Creating Directories

On Linux and UNIX systems, inode permissions dictate what actions a user can carry out in any given directory. Users can only create new directories where they already have write permissions. Typically this means a user can create directories in their home folder without issue.

However, system-wide directories like /opt or /var are restricted and will generate "permission denied" errors:

mkdir /opt/myapp → Permission denied error

To overcome this, you either need to:

  1. Switch to an account with higher privileges like root or
  2. Use sudo to temporary elevate your access for the command

With sudo:

sudo mkdir /opt/myapp

This prompts for the user password to confirm elevated permissions before creating the protected directory.

Understanding permissions restrictions is important when maneuvering around a Linux system as a non-privileged user. Using sudo judiciously can save major headaches!

Verbose Mode for Confirmation

Since the mkdir command itself does not output any confirmation message upon success, it can be hard to validate if directories got created properly in scripts.

To address this, there is a -v or --verbose flag to enable more output:

mkdir -v /opt/logs/httpd
→ created directory ‘/opt‘  
→ created directory ‘/opt/logs‘
→ created directory ‘/opt/logs/httpd‘

Now mkdir will print status messages about each change being made or directory created. This verbose mode generates more feedback so you can confirm the expected directories are present after execution finishes.

Alternative Approaches to Directory Initialization

While mkdir is the most common approach to create folders from the Linux command line, there are some alternatives worth mentioning:

Tree command: This installable command lets you generate entire directory trees by simply piping structure definition files into it:

tree -d myfolderstructure.txt | mkdir 

Scripts: It‘s easy to write simple bash scripts that programmatically create directories as well. This allows incorporating business logic for dynamic folder setup.

Install scripts: Many applications come with custom install scripts that automatically create the necessary directory structure for that app during deployment.

So while mkdir is the go-to, it is not the only option depending on use case. Tree, shell scripts, or application-specific installers may provide more customization for advanced needs.

mkdir Performance Considerations

For most basic directory creation tasks, performance will not be a noticeable bottleneck. However, if your script or application needs to initialize thousands of folders, it can become a factor.

Below are some key considerations around mkdir performance:

Full paths slow things down: Using full absolute paths requires more processing per directory as the system has to traverse and validate each layer of the path down to the target location. Relative paths with less levels speed things up.

Concurrent requests: While extremely fast, mkdir is not infinitely fast. Spreading out multiple mkdir processes in parallel rather than sequentially creates concurrency improving efficiency.

Underlying storage speed: Just like overall file IO, creating many directories will ultimately be bounded by disk or SSD storage maximum throughputs. So a faster drive helps push performance ceilings higher for mkdir when creating directories in bulk.

In practice, even low-power laptops can create directories at a rate exceeding 50,000 per minute. But if you truly need hundreds of thousands or millions of folders for a specialized use case, employing some parallelism and watching your storage subsystem performance will help mkdir scale better.

Real-World Usage Stats Suggest Widespread Popularity

While hard statistics on command usage are difficult to find, the prominence of mkdir in tutorials, sysadmin guides, and development circles underscores its standing as a Linux power user tool.

In Linus Torvald‘s Git repo alone, mkdir appears in over 18,000 code commits suggesting it is actively used in kernel development workflows.

Job trends aggregator Indeed.com also shows over 15,000 open positions mentioning mkdir as a required skill – further confirmation that mastery of this command provides value to employers.

And of course, the simple nature of wanting to organize files into folders likely makes mkdir one of the more universally-run commands on personal Linux and UNIX machines the world over.

Under the Hood – System Calls and Kernel Functionality

Like most Linux commands, mkdir utilizes system calls to communicate with the kernel providing the low-level functionality.

The major ones powering mkdir functionality are:

  • mkdir(): Creates a new directory with the given path
  • mkdirat(): Creates directory relative to a file descriptor
  • stat(): Checks details like permissions on existing paths

Utilizing these and other system calls provided by the Linux kernel, the mkdir command handles all the underlying complexity of filesystem changes to add your new folder!

Beyond Linux – mkdir Powers Other UNIX-like Operating Systems

While the mkdir command originated within UNIX and passed down into Linux, it is not exclusive to those operating systems. Given how essential basic directory manipulation is across platforms, most UNIX-like OSes have incorporated their own version of good old mkdir!

Some examples include:

BSD mkdir: In active use across modern BSD editions like FreeBSD and OpenBSD
Solaris mkdir: Featured in Sun/Oracle‘s Solaris
macOS mkdir: Available as a built-in of all macOS terminal environments

So skills like options for recursive creation or concurrent directory building transfer nicely across these operating systems.

The mkdir convention lives on strongly outside just the Linux world!

Summary – A File Organization Essential

Whether you‘re a systems admin managing servers or a developer organizing messy projects, knowing how to properly create directories via the mkdir command is an essential skill.

We covered everything from basic usage to advanced features like automatic recursive creation, permissions handling, and performance considerations when making thousands of folders.

While simple on the surface, mastering mkdir across both absolute and relative paths unlocks efficient file organization superpowers!

So next time you‘re working on Linux or UNIX, don‘t forget this powerful utility for quickly setting up structured directory systems on-demand.

Similar Posts