Making directory in linux

Linux: How to Make a Directory Command

H ow do I make directory under Linux operating systems using the command prompt or bash shell?

You need to use the mkdir command to create new folders or directories under Linux operating systems. A directory (also known as folder in MS-Windows/macOS ) is nothing but a container for other directories and files. This page explains the basics of using the mkdir command on Linux.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements mkdir on Linux
Est. reading time 3 mintues

mkdir command Syntax

The mkdir command has the following syntax:
mkdir dirname
mkdir dirname1 dirname2
mkdir [option] dieNameHere
mkdir -p dir1/dir2/dir3

Examples

Let us see some commann useful examples.

How to create a new director

Open a terminal and then use the mkdir command to create empty directories. The following command would create a directory called foo:
$ mkdir foo
To list directories, enter:
$ ls
$ ls -l
The following command would create two directories within the current directory:
$ mkdir tom jerry
$ ls -l

How to create Directories in Linux

The -p option allows you to create parent directories as needed (if parent do not already exits). For example, you can create the following directory structure:
$ mkdir -p

/public_html/images/trip
Verify it:
ls -l

/public_html/
ls -l

/public_html/images/
ls -R -l

How to create directories in Linux with verbose option

Pass the -v as follows to display a message for each created directory:
mkdir -v dir1
ls -l

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Setting up permissions when creating a directory

To set directory mode (permission) pass the -m option as follows:
mkdir -m dirName
The -m option is same as giving permissions using the chmod command. For examples:
mkdir data
chmod 0700 data
We can do the same with a single command and save typing time at the command-line:
mkdir -v -m 0700 data
ls -ld data

Setting up SELinux context with mkdir on RHEL or CentOS

The syntax is follows to set up system_u:object_r:httpd_sys_content_t:s0 as SELinux context for foo dir:

How to Create a Directory in Linux with mkdir Command with SELinux

Sample mkdir demo command

Animated gif 01: mkdir in action under Linux / Unix like operating systems

Summing up

The mkdir command in Linux is used to make new directories as per your needs. We create a new directory in current directory or given path:
mkdir my-dir-name-here
ls -l
Also make directories recursively which is useful for creating nested dirs on Linux. For instance:
mkdir -p path/to/dir1/dir2

Getting help

Make sure you read the following man pages:
man mkdir
man ls
mkdir —help

Options summary

Option Description Example
-m ( —mode=MODE ) Set file mode (as in chmod command), not a=rwx – umask. mkdir -m 0644 sales
-p ( —parents ) No error if existing, make parent directories as needed. mkdir -p one/two/three
-v ( —verbose ) Print a message for each created directory. mkdir -v detla
-Z Set SELinux security context of each created directory to the default type. mkdir -Z dir1
—context[=CTX] Like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX. See above
—help Display this help and exit. mkdir —help
—version output version information and exit. mkdir —version

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How to make a folder in Linux or Unix

How to make a folder in Linux

The procedure is as follows:

  1. Open the terminal application in Linux
  2. The mkdir command is is used to create new directories or folders.
  3. Say you need to create a folder name dir1 in Linux, type: mkdir dir1

Let us see examples and other usage in details. The syntax is:

Now you know the syntax. Let us explore how to create new folders and directories on Linux or Unix-like system using the command line option.

How to create a new folder named foo in Unix

Open the Terminal app and type the following command:
mkdir foo
To see directory listing use the ls command:
ls
ls -l
You can simultaneously create any number of folders/directories:
mkdir dir1 dir2 dir3 dir_4
Verify it:
ls -l

Fig.01: How to create Folders/Directories In Linux/Unix with the mkdir command

More on file mode

The entry type character describes (the first character d rwxr-xr-x ) the type of file, as follows:

  1. : Regular file.
  2. b : Block special file.
  3. c : Character special file.
  4. d : Directory.
  5. l : Symbolic link.
  6. p : FIFO.
  7. s : Socket.
  8. w : Whiteout.

So basically d character in above entry tell us that it is a directory/folder. The next three fields are three characters ach: owner permissions, group permissions, and other permissions. Each field has three character positions:

Источник

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.

Источник

Как создавать каталоги в 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 .

Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.

Источник

Читайте также:  Windows universal crt что это
Оцените статью