One of the essential Linux commands is mkdir. The mkdir allows you to make new directories (folders in common term) in Linux.
In this beginner series, you’ll learn to use the mkdir command.
mkdir command examples
The mkdir command is one of the rare few Linux commands that doesn’t have tons of options. And that makes it really simple to use.
Here’s the syntax:
mkdir [option] directory_name_or_path
Let’s see how to use it.
Create new directories
To make a new directory, use mkdir command without any option:
This will create a new directory named new_dir in the present directory. You can check it using the ls command.
[email protected]:~/tuts$ ls [email protected]:~/tuts$ mkdir new_dir [email protected]:~/tuts$ ls -l total 4 drwxrwxr-x 2 abhishek abhishek 4096 May 14 16:15 new_dir
You may also specify the path to where you want to create the new directory.
[email protected]:~/tuts$ ls new_dir [email protected]:~/tuts$ mkdir new_dir/another_new_dir [email protected]:~/tuts$ tree . └── new_dir └── another_new_dir 2 directories, 0 files
Create multiple directories
You may also create several new directories with a single command:
mkdir new_dir_1 new_dir_2 new_dir_3
All the new directories are created at the same level. You may also create nested directories which is described in the next section.
Create nested directories
You can use the option -p to create a nested directory structure. If the parent directory doesn’t exist, it will create it for you.
This is particularly helpful when you want to create a directory structure or if you want to make sure that directory path exists.
mkdir -p dir1/dir2/dir3/dir4
This is what the above command created:
[email protected]:~/tuts$ mkdir -p dir1/dir2/dir3/dir4 [email protected]:~/tuts$ tree . ├── dir1 │ └── dir2 │ └── dir3 │ └── dir4 └── new_dir └── another_new_dir 6 directories, 0 files
You may also use the -p option with a single directory. It won’t create a new directory that already exists, but it won’t throw any errors as well:
[email protected]:~/linuxhandbook$ mkdir new_dir mkdir: cannot create directory ‘new_dir’: File exists [email protected]:~/linuxhandbook$ mkdir -p new_dir [email protected]:~/linuxhandbook$ ls -l total 8 drwxrwxr-x 3 abhishek abhishek 4096 May 14 16:39 dir1 drwxrwxr-x 3 abhishek abhishek 4096 May 14 16:16 new_dir
Create directory with specific permissions
By default, your shell’s umask controls the permission on the newly created directories. If you want different file permissions on the directory, instead of creating the directory first and then change the permission with the chmod command, you can use the -m option.
Suppose you want the permission 766 on the directory you are going to create. You can use:
mkdir -m 766 new_directory
That’s pretty much what you need to know about the mkdir command. Now that you know how to create directories, maybe you would want to learn about deleting directories in Linux command line.