The mkdir
command in UNIX/Linux systems is an essential tool for managing directories. Used to create one or more directories (also known as folders in some operating systems), mkdir
helps users organize their file structure efficiently. Here’s a detailed look at various ways to use this command, along with practical examples to aid understanding.
Syntax of the Mkdir Command
The basic syntax for the mkdir
command is:
mkdir [options] directory_name
Creating a New Directory
To create a simple directory in the current working directory, use:
mkdir new_directory
This command will create a directory named new_directory
in the current working directory.
Creating Multiple Directories
To create several directories at once, list the directory names separated by spaces:
mkdir directory1 directory2 directory3
This command will create three directories: directory1
, directory2
, and directory3
.
Creating Multiple Directories Using Special Characters
If directory names include special characters, such as spaces, use quotes or the escape character \
:
mkdir "directory with spaces" directory_with_special\_characters
Creating a New Directory in a Desired Location
To create a directory in a specific location, provide the full path:
mkdir /path/to/directory/new_directory
Creating a New Directory in Two Different Locations
To create a directory in two different locations, specify each path:
mkdir /path1/new_directory /path2/new_directory
Creating Multiple Directories Using Special Characters at Your Desired Location
Similarly, special characters can be used in the path:
mkdir /path/"directory with spaces"/new_directory
Ignoring the Error if the Specified Directory Already Exists
To avoid the “File exists” error if the directory already exists, use the -p
option:
mkdir -p existing_directory
Creating a Parent Directory While Creating a New Directory
To create a directory along with all necessary parent directories, use the -p
option:
mkdir -p /path/parent/new_directory
Creating a Subdirectory Inside the Newly Created Directories
To create a subdirectory inside a newly created directory:
mkdir -p /path/directory/new_subdirectory
Printing the Directory Name While Creating
To print the directory name upon creation, combine mkdir
with echo
or printf
:
mkdir new_directory && echo "New directory created: new_directory"
Setting Permissions While Creating a New Directory
To set permissions while creating a directory, use chmod
after creation:
mkdir new_directory && chmod 755 new_directory
Conclusion
The mkdir
command in Linux is a powerful and flexible tool for directory management. Whether you need to create simple, multiple, or specifically located directories, understanding the various options and syntax can significantly improve efficiency in file and directory management. With this knowledge, Linux users can better customize their file structure according to their needs.