Shell linux create directory

Как создавать каталоги в Linux (команда mkdir)

В системах Linux вы можете создавать новые каталоги либо из командной строки, либо с помощью файлового менеджера вашего рабочего стола. Команда, позволяющая создавать каталоги (также известные как папки), — это mkdir .

В этом руководстве рассматриваются основы использования команды mkdir , включая повседневные примеры.

Синтаксис команды Linux mkdir

Синтаксис команды mkdir следующий:

Команда принимает в качестве аргументов одно или несколько имен каталогов.

Как создать новый каталог

Чтобы создать каталог в Linux, передайте имя каталога в качестве аргумента команды mkdir . Например, чтобы создать новый каталог newdir вы должны выполнить следующую команду:

Вы можете убедиться, что каталог был создан, перечислив его содержимое с помощью команды ls :

drwxrwxr-x 2 username username 4096 Jan 20 03:39 newdir 

При указании только имени каталога без полного пути он создается в текущем рабочем каталоге.

Текущий рабочий каталог — это каталог, из которого вы запускаете команды. Чтобы изменить текущий рабочий каталог, используйте команду cd .

Чтобы создать каталог в другом месте, вам необходимо указать абсолютный или относительный путь к файлу родительского каталога. Например, чтобы создать новый каталог в каталоге /tmp вы должны ввести:

Если вы попытаетесь создать каталог в родительском каталоге, в котором у пользователя недостаточно прав, вы получите сообщение об ошибке Permission denied :

mkdir: cannot create directory '/root/newdir': Permission denied 

Параметр -v ( —verbose ) указывает mkdir печатать сообщение для каждого созданного каталога.

Как создать родительские каталоги

Родительский каталог — это каталог, который находится над другим каталогом в дереве каталогов. Чтобы создать родительские каталоги, используйте параметр -p .

Допустим, вы хотите создать каталог /home/linuxize/Music/Rock/Gothic :

mkdir /home/linuxize/Music/Rock/Gothic

Если какой-либо из родительских каталогов не существует, вы получите сообщение об ошибке, как показано ниже:

mkdir: cannot create directory '/home/linuxize/Music/Rock/Gothic': No such file or directory 

Вместо того, чтобы создавать недостающие родительские каталоги один за другим, вызовите команду mkdir с параметром -p :

mkdir -p /home/linuxize/Music/Rock/Gothic

Когда используется опция -p , команда создает каталог, только если он не существует.

Читайте также:  Smart проверка дисков linux

Если вы попытаетесь создать каталог, который уже существует, а параметр -p не mkdir , mkdir выведет сообщение об ошибке File exists :

mkdir: cannot create directory 'newdir': File exists 

Как установить разрешения при создании каталога

Чтобы создать каталог с определенными разрешениями, используйте параметр -m ( -mode ). Синтаксис для назначения разрешений такой же, как и для команды chmod .

В следующем примере мы создаем новый каталог с разрешениями 700 , что означает, что только пользователь, создавший каталог, сможет получить к нему доступ:

Когда опция -m не используется, вновь созданные каталоги обычно имеют права доступа 775 или 755 , в зависимости от значения umask .

Как создать несколько каталогов

Чтобы создать несколько каталогов, укажите имена каталогов в качестве аргументов команды, разделенные пробелом:

Команда mkdir также позволяет создать сложное дерево каталогов с помощью одной команды:

mkdir -p Music/,Classical/Baroque/Early>

Приведенная выше команда создает следующее дерево каталогов :

Music/ |-- Classical | `-- Baroque | `-- Early |-- Disco |-- Folk |-- Jazz | `-- Blues `-- Rock |-- Gothic |-- Progressive `-- Punk 

Выводы

Команда mkdir в Linux используется для создания новых каталогов.

Для получения дополнительной информации о mkdir посетите страницу руководства mkdir .

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

Источник

Create a Directory in Linux Using Shell: Tips and Tricks with mkdir Command

Learn how to create a directory in Linux using the shell with the mkdir command. Navigate to the parent directory, create parent directories if necessary, set permissions, and create files in a single command. Tips and tricks included!

  • Basic syntax and usage of the mkdir command
  • Navigating to the parent directory before creating a new directory
  • Create a Folder in the Linux Shell Script Tutorial Directory
  • Creating parent directories if necessary using the -p flag
  • Setting permissions and displaying details of the mkdir command
  • Creating a directory and a file in a single command using mkdir and touch commands
  • Other helpful code examples for creating a directory in Linux using shell
  • Conclusion
  • How do I create a folder in a directory in Linux?
  • How do I create a folder in shell?
  • Can I create folder in root directory Linux?
  • How do I create a directory or file in Linux?

Linux is a powerful operating system with a command line interface that allows users to perform various tasks using shell commands. One of the essential tasks is creating a directory or folder using the mkdir command. In this article, we will explore how to create a directory in linux using the shell, and provide useful tips and tricks to make the process easier.

Basic syntax and usage of the mkdir command

The basic syntax for using the mkdir command is “mkdir ”. This command can be used to create a directory within the current location or to create a directory structure with missing parent directories . Different Linux operating systems may have slightly different versions of the mkdir command, but the basic usage remains the same.

Читайте также:  How to update linux mint

Here is an example of creating a directory named “mydirectory” in the current location:

To create a directory structure with missing parent directories, you can use the “-p” flag. For example, to create a directory named “mydirectory” inside a directory named “parentdirectory” which does not exist yet, you can use the following command:

mkdir -p parentdirectory/mydirectory 

This will automatically create the “parentdirectory” if it does not exist, and then create the “mydirectory” inside it.

Users can navigate to the desired parent directory using the cd command before using the mkdir command to create a new directory. This reduces the risk of creating a directory in the wrong location or accidentally overwriting an existing directory.

Here is an example of navigating to a parent directory named “myproject” and then creating a directory named “mydirectory” inside it:

cd myproject mkdir mydirectory 

This ensures that the “mydirectory” is created in the correct location, which is inside the “myproject” directory.

Create a Folder in the Linux Shell Script Tutorial Directory

http://filmsbykris.comhttp://www.patreon.com/metalx1000Playlisthttps://www.youtube.com/playlist Duration: 4:14

Creating parent directories if necessary using the -p flag

The -p flag can be used with the mkdir command to create parent directories if necessary. This saves time and effort by automatically creating missing parent directories instead of creating them one by one.

Here is an example of creating a directory named “mydirectory” inside a directory named “parentdirectory”, and automatically creating the “parentdirectory” if it does not exist:

mkdir -p parentdirectory/mydirectory 

This will create both the “parentdirectory” and the “mydirectory” inside it if they do not exist yet.

Setting permissions and displaying details of the mkdir command

The mkdir command also allows for setting permissions using the -m flag. This is useful when you want to set specific permissions for the directory you are creating.

Here is an example of creating a directory named “mydirectory” inside a directory named “parentdirectory”, and setting the permissions to 755:

mkdir -m 755 parentdirectory/mydirectory 

The -v flag can be used to display details of the mkdir command, such as the directories created and any errors encountered. This is useful when you want to see the output of the mkdir command and make sure that everything was created successfully.

Here is an example of creating a directory named “mydirectory” inside a directory named “parentdirectory”, and displaying the details of the command:

mkdir -v parentdirectory/mydirectory 

This will display the output of the mkdir command, which should show that the “parentdirectory” and “mydirectory” were created successfully.

Читайте также:  Linux указать прокси сервер

Creating a directory and a file in a single command using mkdir and touch commands

A combination of mkdir and touch commands can be used to create both a directory and a file in a single command. This is useful for creating directories with accompanying files without having to run separate commands.

Here is an example of creating a directory named “mydirectory” and a file named “myfile.txt” inside it, using a single command:

mkdir mydirectory && touch mydirectory/myfile.txt 

This will create the “mydirectory” and “myfile.txt” inside it in a single command.

Other helpful code examples for creating a directory in Linux using shell

In shell, create folder with shell/bash code example

In shell, Creating a directory or folder in linux code example

You create folders using the mkdir command:$ mkdir fruitsYou can create multiple folders with one command:$ mkdir dogs carsYou can also create multiple nested folders by adding the -p option:$ mkdir -p fruits/applesOptions in UNIX commands commonly take this form. You add them right after the command name, and they change how the command behaves. You can often combine multiple options, too. You can find which options a command supports by typing man . Try now with 'man mkdir' for example$ man mkdir(press the 'q' key to esc the 'man page'). Man pages are the amazing built-in help for UNIX.
To create a new folder/directory mkdir foldernameTo view the contents of your folder cd foldername -- to get inside the folder then ls or dir -- to view contents of the folderTo create a new file touch example.txt -- filename and extension eg .js .html .txt 

In shell, shell Creating folders and files code example

mkdir /tmp/tutorial cd /tmp/tutorialmkdir dir1 dir2 dir3mkdir cd /etc ~/Desktop ls

In shell, make directory in linux code example

In shell, Create directory Linux code example

In shell, How to create directory on Linux code example

mkdir /tmp/tutorial cd /tmp/tutorial

Conclusion

Creating a directory in Linux using the shell is a simple yet essential task. By using the mkdir command with different options and flags, users can create directories, set permissions, and create parent directories if necessary. The mkdir command can also be used in combination with other commands to create directories and files in a single command. With this knowledge, users can efficiently manage their directories and files in Linux.

Источник

Оцените статью
Adblock
detector