What Command Creates a Subdirectory Under a Directory?

Learn how to make new directories under an existing subdirectory.

So you’ll know how to use the *mkdir *command to make a directory on the command line but what command creates a subdirectory under a directory? The simple answer is, you can use the *mkdir *command to create subdirectories as long as you specify the full path when creating the subdirectory. Check out the Command Line Essentials FREE course to improve your command line skills. This 11 part course will teach you all the essential skills you need to use the command line within your Junior Developer role. Learn more here.

What Command Creates a Subdirectory Under a Directory?

Let’s take a look at a quick example. To create a standard directory/folder on its own you use the *mkdir *command followed by the name of the directory you want to create:

mkdir project

So to achieve our task of creating a subdirectory, you specify the name of the subdirectory after the parent like so:

mkdir project/images

The parent *project *folder doesn’t need to exist for this to work it will simply create this folder along with the subdirectory *images *that we specified in the path. There is a limit to this though. Say for example we were to try and create another subdirectory inside the images folder _before _either the images or project folder had been created we would get an error on the command line:

mkdir: cannot create directory ‘project/images/header’: No such file or directory

I’m not 100% sure why the command line would allow you to create immediate subdirectories and not sub-subdirectories. Possibly because of the command line not knowing about the structure of subdirectories that haven’t been created yet? I don’t know. However, we can get around this problem by specifying an option to the *mkdir *command. A quick look at the help documentation for the *mkdir *command shows us the options:

Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
-p, --parents no error if existing, make parent directories as needed
-v, --verbose print a message for each created directory
-Z set SELinux security context of each created directory
to the default type
--context[=CTX] like -Z, or if CTX is specified then set the SELinux
or SMACK security context to CTX
--help display this help and exit
--version output version information and exit

The -p option, therefore, allows us to create parent directories if creating multiple, nested subdirectories that may not exist. Got any other command line tips and tricks? Share them in the comments below!