- How to Use mkdir Command to Make or Create a Linux Directory
- What is the mkdir Command in Linux?
- mkdir Command Syntax in Linux
- How to Make a New Directory In Linux
- How to Create Multiple Directories with mkdir
- How to Make Parent Directories
- How to Set Permissions When Making a Directory
- How to Verify Directories
- mkdir Command Options and Syntax Summary
- Is there a way to create multiple directories at once with mkdir?
- 8 Answers 8
- Short answer
- Как создавать каталоги в Linux (команда mkdir)
- Синтаксис команды Linux mkdir
- Как создать новый каталог
- Как создать родительские каталоги
- Как установить разрешения при создании каталога
- Как создать несколько каталогов
- Выводы
- Create Folder in Linux Create Directory in Linux [mkdir Command]
- mkdir command [Make Directory Command]
- Make directory command options
- How to Create Directory in Linux
- Creating multiple directories
- Creating a parent directory
- Setting permission for directory while creating the directory
- Verifying the directories
- How to Create Folder in Linux? [Step By Step Guide]
- rmdir command/rm command to Remove the Directory/Folder in Linux
- Conclusion
How to Use mkdir Command to Make or Create a Linux Directory
Home » SysAdmin » How to Use mkdir Command to Make or Create a Linux Directory
What is the mkdir Command in Linux?
The mkdir command in Linux/Unix allows users to create or make new directories. mkdir stands for “make directory.”
With mkdir , you can also set permissions, create multiple directories (folders) at once, and much more.
This tutorial will show you how to use the mkdir command in Linux.
- Linux or UNIX-like system.
- Access to a terminal/command line.
- A user with permissions to create and change directory settings.
mkdir Command Syntax in Linux
The basic command for creating directories in Linux consists of the mkdir command and the name of the directory. As you can add options to this command, the syntax looks like this:
To understand better how to use mkdir , refer to the examples we provide in the rest of the guide.
Tip: Use cd to navigate to the directory where you want to create a sub-directory. You can also use the direct path. Use ls to list the directories in the current location.
How to Make a New Directory In Linux
To create a directory using the terminal, pass the desired name to the mkdir command.
In this example, we created a directory Linux on the desktop. Remember commands in Linux and options are case sensitive.
If the operation is successful, the terminal returns an empty line.
To verify, use ls .
Note: To create a hidden directory, follow our guide on how to show and create hidden files in Linux.
How to Create Multiple Directories with mkdir
You can create directories one by one with mkdir, but this can be time-consuming. To avoid that, you can run a single mkdir command to create multiple directories at once.
To do so, use the curly brackets <> with mkdir and state the directory names, separated by a comma.
Do not add any spaces in the curly brackets for the directory names. If you do, the names in question will include the extra characters:
How to Make Parent Directories
Building a structure with multiple subdirectories using mkdir requires adding the -p option. This makes sure that mkdir adds any missing parent directories in the process.
For example, if you want to create “dirtest2” in “dirtest1” inside the Linux directory (i.e., Linux/dirtest1/dirtest2), run the command:
Use ls -R to show the recursive directory tree.
Without the -p option, the terminal returns an error if one of the directories in the string does not exist.
How to Set Permissions When Making a Directory
The mkdir command by default gives rwx permissions for the current user only.
To add read, write, and execute permission for all users, add the -m option with the user 777 when creating a directory.
To create a directory DirM with rwx permissions:
To list all directories and show the permissions sets: -l
The directory with rwx permissions for all users is highlighted. As you can see on the image above, two other directories by default have rwx permission for the owner, xr for the group and x for other users.
How to Verify Directories
When executing mkdir commands, there is no feedback for successful operations. To see the details of the mkdir process, append the -v option to the terminal command.
Let’s create a Details directory inside Dir1 and print the operation status:
By getting the feedback from the process, you do not have to run the ls command to verify the directory was created.
mkdir Command Options and Syntax Summary
Option / Syntax | Description |
---|---|
mkdir directory_name | Creates a directory in the current location |
mkdir | Creates multiple directories in the current location. Do not use spaces inside <> |
mkdir –p directory/path/newdir | Creates a directory structure with the missing parent directories (if any) |
mkdir –m777 directory_name | Creates a directory and sets full read, write, execute permissions for all users |
mkdir –v directory_name(s) | Creates a directory in the current location |
Note: Learn to fully manage directories by learning to move a directory in a system running a Linux distribution.
This guide covered all commands you need to create directories in Linux.
Now you understand how to use the Linux mkdir command. It’s straightforward and simple to use.
If you have the necessary permissions, there should be no error messages when you follow the instructions in this article.
Источник
Is there a way to create multiple directories at once with mkdir?
If I wanted to create multiple directories (on the same level) and then feed it a comma seperated list of directory names (or something to that effect)?
8 Answers 8
You can use lists to create directories and it can get pretty wild.
Some examples to get people thinking about it:
- 50 directories from sa1 through sa50
- same but each of the directories will hold 50 times sax1 through sax50 (-p will create parent directories if they do not exist.
- 26 directories from a12345 through z12345
- comma separated list makes dirs 1, 2 and 3.
- 10 directories from test01 through test10 .
- same as 4 but with the current date as a directory and 1,2,3 in it.
- same as 4 but with the current user as a directory and 1,2,3 in it.
So, if I understood it correctly and you want to create some directories, and within them new directories, then you could do this:
and get sa1, sa2. sa10 and within each dirs 1, 2 and 3.
Short answer
mkdir takes multiple arguments, simply run
It’s very simple, lets you want to create a directory structure such as:
You can do it in a single command like this:
Be careful not to enter any spaces
Make a list of the names for your desired directories using line breaks instead of commas as a separator. Save that list.
You should now have all the directories named in your list.
Something like this? (thanks to muru for the printf tip)
You can wrap it into a function for ease of use:
So you want comma separated list of directory names ? That can be done.
Shell + coreutils
Since everybody is posting oneliners, here’s mine as well ( mkdir + parameter substitution plus + shell redirection ).
AWK
AWK is a text processing language, but it has very nice system() function which will call the default shell , and run command[s] enclosed in parenthesis ( which must be a string).
Or you could remove , with gsub() function, and call system(«mkdir «$0) but that may be a problem if you want to create directories with spaces in their name
Источник
Как создавать каталоги в Linux (команда mkdir)
В системах Linux вы можете создавать новые каталоги либо из командной строки, либо с помощью файлового менеджера вашего рабочего стола. Команда, позволяющая создавать каталоги (также известные как папки), — это mkdir .
В этом руководстве рассматриваются основы использования команды mkdir , включая повседневные примеры.
Синтаксис команды Linux mkdir
Синтаксис команды mkdir следующий:
Команда принимает в качестве аргументов одно или несколько имен каталогов.
Как создать новый каталог
Чтобы создать каталог в Linux, передайте имя каталога в качестве аргумента команды mkdir . Например, чтобы создать новый каталог newdir вы должны выполнить следующую команду:
Вы можете убедиться, что каталог был создан, перечислив его содержимое с помощью команды ls :
При указании только имени каталога без полного пути он создается в текущем рабочем каталоге.
Текущий рабочий каталог — это каталог, из которого вы запускаете команды. Чтобы изменить текущий рабочий каталог, используйте команду cd .
Чтобы создать каталог в другом месте, вам необходимо указать абсолютный или относительный путь к файлу родительского каталога. Например, чтобы создать новый каталог в каталоге /tmp вы должны ввести:
Если вы попытаетесь создать каталог в родительском каталоге, в котором у пользователя недостаточно прав, вы получите сообщение об ошибке Permission denied :
Параметр -v ( —verbose ) указывает mkdir печатать сообщение для каждого созданного каталога.
Как создать родительские каталоги
Родительский каталог — это каталог, который находится над другим каталогом в дереве каталогов. Чтобы создать родительские каталоги, используйте параметр -p .
Допустим, вы хотите создать каталог /home/linuxize/Music/Rock/Gothic :
Если какой-либо из родительских каталогов не существует, вы получите сообщение об ошибке, как показано ниже:
Вместо того, чтобы создавать недостающие родительские каталоги один за другим, вызовите команду mkdir с параметром -p :
Когда используется опция -p , команда создает каталог, только если он не существует.
Если вы попытаетесь создать каталог, который уже существует, а параметр -p не mkdir , mkdir выведет сообщение об ошибке File exists :
Как установить разрешения при создании каталога
Чтобы создать каталог с определенными разрешениями, используйте параметр -m ( -mode ). Синтаксис для назначения разрешений такой же, как и для команды chmod .
В следующем примере мы создаем новый каталог с разрешениями 700 , что означает, что только пользователь, создавший каталог, сможет получить к нему доступ:
Когда опция -m не используется, вновь созданные каталоги обычно имеют права доступа 775 или 755 , в зависимости от значения umask .
Как создать несколько каталогов
Чтобы создать несколько каталогов, укажите имена каталогов в качестве аргументов команды, разделенные пробелом:
Команда mkdir также позволяет создать сложное дерево каталогов с помощью одной команды:
Приведенная выше команда создает следующее дерево каталогов :
Выводы
Команда mkdir в Linux используется для создания новых каталогов.
Для получения дополнительной информации о mkdir посетите страницу руководства mkdir .
Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.
Источник
Create Folder in Linux Create Directory in Linux [mkdir Command]
Looking to create folder in Linux/create directory in Linux? Then this post will give you detailed insights on the mkdir command and to execute this process.
List of content you will read in this article:
Everyone who is a beginner or advanced Linux administrator somehow is looking to create folder in Linux/create directory in Linux.
Linux is widely adopted and used due to its stability and flexibility in carrying out various tasks in an easier way. One of the key features of Linux is the terminal where you can run any command to run various tasks from making changes to the system to download any required software.
In this article, we will be highlighting the commands with various options for creating directories or folders in the Linux system. Linux offers an easy command for that- mkdir command that stands for “make directory”. Also, the “mkdir” command will allow you to set permissions, create multiple directories using the single command, and do many other tasks.
Before you run the mkdir command, make sure to complete the prerequisites such as-
- Linux or Unix-like OS.
- Access to the command-line terminal for executing the commands.
- The user should be having the right access to creating the directory.
mkdir command [Make Directory Command]
If you want to create a new directory, you can make use of the “mkdir” command for creating single or multiple directories within the Linux system. You can use this command along with various options for applying various functionality. The syntax can you can use for the “mkdir” command is as follows-
mkdir [option] dir_name
Make directory command options
Option / Syntax
Description
This command will create a directory within the current directory location
This command will help in creating multiple directories in the current directory location. Make sure that you do not use the spaces inside the <>
mkdir –p dir/path/new_dir
This command will allow you to create a directory structure with the missing parent directories (if there is any)
mkdir –m777 dir_name
This command will help in creating a directory and allow you to provide full read, write, execute permissions for every user
mkdir –v dir_name(s)
This command will help in creating a directory in the current location along with the details of the mkdir command.
How to Create Directory in Linux
To run the “mkdir” command, go to the terminal and open it with the admin access if you have, otherwise, you just need to have the right and appropriate access to execute the “mkdir” command.
Always, remember that the options in Linux are case-sensitive so use them correctly else the meaning will change. As per the below example, we have created a directory “Sam”.
mkdir Sam
This command will result in the creation of the directory in the current working directory. If the directory has been created successfully then you will get an empty line on the terminal. If you want to verify the result of the creation of the directory, you can use the “ls” command.
Creating multiple directories
If you want to create several directories in the same directory, you can use the “mkdir” for creating them separately. But it will take time to run individual commands. So to save your time by running separate commands, you can use a single “mkdir” command along with the directory names separated by a comma.
Consider the following example for creating multiple directories at once.
mkdir
There is no need to add space between the directory names in the brackets. But, if you add the space then the name will take an extra character.
Creating a parent directory
If you want to create a structure with multiple subdirectories, then you can use the “mkdir” command along with the “-p: option. Using this option will make sure that the missing parent directory will be added in the process.
Here, we are considering the example where we want to add the “dirtest2” directory within the “dirtest1” directory in the Linux directory, then we have to provide the complete path with the “mkdir” command as shown below.
mkdir –p Linux/dirtest1/dirtest2
Once you run the “mkdir” command with the complete path, then to confirm the creation of the directory, you can run the “ls” command along with the “-R” option. This option will help in showing the recursive directory tree that will display the contents of each directory present in the provided path.
But, if you miss the “-p” option, the terminal will display an error that the directory that you have provided does not exist. You can see the below example.
In the above example, the terminal will show an error that the dirtest3 does not exist rather than creating the parent directory.
Setting permission for directory while creating the directory
If you create any directory in the Linux system, then by default the directory will get the “rwx” permission but only for the user who created that directory. If you want to change the permission for the directory for all the users, then you can use the “-m” option along with the “mkdir” command.
In the below example, we are providing the permission to the directory as “777” that is any user will be able to read, write, or execute that file if required.
mkdir -m
mkdir -m 777 alpha
ls -l
If you want to check the details of the created directory along with their permissions, then you need to get the long listing of the directories. For this, you can run the “ls” command along with the “-l” option.
Verifying the directories
So far, you have noticed that after running the “mkdir” command, you will not get any feedback or the result showing if the creation is successful or not. If you want see the details of the “mkdir” command, then you can use the “-v” option with the “mkdir” command.
Considering the below example with the “-v” option, you will get the details of the command.
Now that you get the complete details of the creation of the directory, you do not have to run the “ls” command to creak the created directory.
How to Create Folder in Linux? [Step By Step Guide]
Follow the below-given steps to create a folder in Linux easily.
Step 1: In Linux, first open the terminal.
Step 2: then enter mkdir dir1 command to build a folder with the name dir1.
Let’s take a closer look at certain cases and other applications. The syntax to create a directory in Linux is as follows:
mkdir folder
mkdir [option] folderName
mkdir directory
By using the ls command to list the contents of the directory, you can confirm that it was created:
This will show the list of all the current directories.
mkdir’s -v (—verbose) option instructs it to print a message for each directory it creates.
mkdir: created directory ‘folder’
The file is generated in the current working directory when only the directory name is provided without the complete path. The latest working directory is the location where the commands are being executed. The cd command is used to modify the actual working directory.
To build a directory in a different region, you’ll need to specify the parent directory’s absolute or relative file direction. To construct a new directory in the /xyz directory, for example, type:
You’ll get a Permission denial error if you want to build a directory in a parent directory where the user doesn’t have enough permissions.
After executing the command you will get output like this:
mkdir: cannot create directory ‘/root/newdirectory’: Permission denied
You can create a parent folder using the following command:
mkdir -p dir11/dir12
mkdir -p parent1/child1
mkdir -p pictures1/memories1
This will list all the directories present in the parent and child folder, respectively to verify it you have to follow the below listed given command.
ls -l
ls -l pictures1
rmdir command/rm command to Remove the Directory/Folder in Linux
Here, we are removing a folder called directory1, so we will execute the below command:
rm -rf directory1
Conclusion
This is all about how to create folder in Linux by using mkdir command. With this guide, you will be able to understand the working of the “mkdir” command. You can use the “mkdir” command along with various options that we have mentioned and explained their usage, how they impact the working of the normal “mkdir” command and how it changes the output. Make sure to use the right option in the right scenario for getting the correct result. The options are case-sensitive, so make sure to use the right option else you will end up with the error
If you feel there is any other option available in Linux to create directories and folders, Please suggest with the comment box, We will try to include your suggestion.
Источник