- рекурсивный MKDIR
- Linux: How to Make a Directory Command
- mkdir command Syntax
- Examples
- How to create a new director
- How to create Directories in Linux
- How to create directories in Linux with verbose option
- Setting up permissions when creating a directory
- Setting up SELinux context with mkdir on RHEL or CentOS
- Sample mkdir demo command
- Summing up
- Getting help
- recursive mkdir
- 4 Answers 4
- How to Use the Recursive Linux Make Directory Command
- Method 1: Using the Parent mkdir Option
- Method 2: Using the Parent mkdir Option Plus Brace Expansion
- How can I create directories recursively? [duplicate]
- 5 Answers 5
рекурсивный MKDIR
Есть ли команда Linux, которую я пропускаю, которая позволяет сделать что-то вроде: (псевдо)
Или нет другого выхода, кроме как делать каталоги по одному?
Использование mkdir -p — это простой способ для большинства современных ОС:
Однако mkdir -p не рекомендуется во многих руководствах. Прочтите документацию по GNU make и autoconf о проблемах с использованием mkdir -p :
Кроссплатформенные системы установки и настройки имеют свои собственные безопасные альтернативы mkdir -p .
CMake для использования в командной строке оболочки:
Autoconf для использования в скрипте с предварительной обработкой:
Но эти решения требуют cmake или autoconf ( M4 ) инструментов для установки (и возможной предварительной обработки)
Вы также можете использовать install-sh скрипт с -d опцией:
Этот скрипт используется autoconf и automake проекта. Я думаю, что это должно быть самым безопасным решением.
В то время я искал кроссплатформенное решение для стандарта /bin/sh без зависимостей, но не нашел его. Поэтому я написал следующий скрипт, который может быть не идеальным, но я думаю, что он соответствует большинству кроссплатформенных требований :
Этот скрипт можно использовать для старых систем, где опция -p for mkdir отсутствует.
sed кросс-платформенная версия dirname была добавлена в код. Он работает аналогично dirname (корректно с путем / , путями только с базовым именем, путями с завершающими / , путями с и без конечных \n s). Эта функция не может работать корректно, если путь содержит новые строки или некоторые недопустимые символы для текущей локали. Он также заменяет любую комбинацию / ( // , /// ) /
Изменена строка mkdir «$1» || return 1 на test -d «$1» || < mkdir "$1" || return 1; >потому что mkdir завершается с ошибкой, если путь существует, и эта проверка необходима для путей, содержащих конструкции, такие как aaa\. (Если aaa не существует, предыдущая версия создает, aaa а затем пытается создать ее снова).
Эта версия mkd не генерирует ошибку, если путь уже существует (но у нее все еще есть возможность генерировать такую ошибку при параллельном выполнении) и не может получить несколько каталогов в командной строке.
Источник
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
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
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
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
Источник
recursive mkdir
Is there a linux command that I’m overlooking that makes it possible to do something along the lines of: (pseudo)
Or is there no alternative but to make the directories one at a time?
4 Answers 4
Parameter p stands for ‘parents’.
Using mkdir -p is a simple way for most modern OSes:
However, mkdir -p is not recommended in many manuals. Read documentation for of GNU make and autoconf about problems with using mkdir -p :
The cross platform installation and configuration systems have their own safe alternatives for mkdir -p .
CMake to use in shell command line:
Autoconf to use in script with preprocessing:
But these solutions require cmake or autoconf ( M4 ) tools to be installed (and possible preprocessing)
You can use also install-sh script with -d option:
This script is used by autoconf and automake project. I think it must be the safest solution.
At the time I was searching for a cross platform solution for standard /bin/sh without dependences, but haven’t found one. Therefore I wrote the next script that may be not ideal, but I think it is compliant to most cross platform requirements:
This script can be used for old systems, where option -p for mkdir is absent.
sed -based cross platform version of dirname was added to the code. It works with a way similar to dirname (correct with path / , paths with base name only, paths with trailing / , paths with and without trailing \n s). This function can’t work correct if the path has newlines or some invalid characters for current locale. It also replaces any combination of / ( // , /// ) with single /
Changed line mkdir «$1» || return 1 to test -d «$1» || < mkdir "$1" || return 1; >because mkdir terminates with error if path exists and this check is needed for paths containing constructions like aaa\. (If aaa doesn’t exist previous version creates aaa and then tries to create it again).
This version of mkd doesn’t generate an error if path already exist (but it still has the possibility to generate such an error in parallel execution) and can’t get several directories in command line.
Источник
How to Use the Recursive Linux Make Directory Command
Generally, when you use the mkdir Linux make directory command you create a single subdirectory that lives in whatever directory your prompt is currently sitting in. If you were in
/Documents and you typed mkdir Memoranda, then you’d create a single directory called Memoranda that lived in
/Documents. You don’t usually create more directories inside of it.
However, you can use the recursive form of the Linux make directory command to create entire directory trees. You can create a directory inside the directory that you’re sitting in and then make many other directories inside of that. Naturally, you’ll need to be working from a CLI prompt to continue. Hold down Ctrl, Alt and T to open a graphical terminal. You could also search for Terminal on the Ubuntu Unity Dash or select the Applications menu, click on System Tools and select Terminal. You won’t have to be working as a root user if you’re not making directories outside of your own home directory.
Method 1: Using the Parent mkdir Option
If you wanted to make a number of directories all at once, then you could type mkdir -p hey/this/is/a/whole/tree and then push enter. You’d get an entire set of directories with each of those names, all nested inside of each other. Obviously, you could use whichever name you’d like at any point in the tree. If some of those directories exist, say there already is hey and this but not the others, then mkdir will simply pass these over without error and make directories underneath them.
The -p option is called parents, and could theoretically be invoked in many distributions by typing –parents instead of -p in the previous command. You can create a practically unlimited number of directories in this fashion all at once. As soon as they’re created, they function completely like any other directories. This means that if you try to remove the top one, it will complain about not being empty too!
Method 2: Using the Parent mkdir Option Plus Brace Expansion
Brace expansion allows you to create a bunch of directories that follow a single pattern when using the bash command interpreter. For instance, if you typed mkdir , then you will have created four directories numbered as such in the current directory. If you wanted to, then you could combine this concept with the parent option. You could, for instance, type mkdir -p 1/ and push enter to create a directory called 1 with directories called 1, 2, 3 and 4 inside of it. It’s a very powerful command, and you can use it to create tons of directories all at once. This makes it perfect for sorting collections of photos, videos and music in Linux. Some people also use this technology when creating install scripts for software or packages they plan to distribute.
You can of course mix this option in and add brace expansion to any part of the command. If you wanted to create some directories via brace expansion, and then others via only parents recursion, then you might want to try a command like mkdir -p a/directory/inside , which will create a and directory inside of a as well as inside1, inside2, inside3 and inside4 underneath it. Feel free to experiment a bit and create extra directories inside of each other once you’ve already learned how to use the mkdir command, but keep in mind that you won’t be able to remove directories that have other directories inside them without a little recursion or the use of a file manager.
Источник
How can I create directories recursively? [duplicate]
Is there a Python method to create directories recursively? I have this path:
I would like to create
Can I do it recursively or I have to create one directory after the other?
The same thing for:
chmod and chown can I do it recursively without assign permissions for each file/dir?
5 Answers 5
a fresh answer to a very old question:
starting from python 3.2 you can do this:
thanks to the exist_ok flag this will not even complain if the directory exists (depending on your needs. ).
starting from python 3.4 (which includes the pathlib module) you can do this:
starting from python 3.5 mkdir also has an exist_ok flag — setting it to True will raise no exception if the directory exists:
os.makedirs is what you need. For chmod or chown you’ll have to use os.walk and use it on every file/dir yourself.
Here is my implementation for your reference:
I agree with Cat Plus Plus’s answer. However, if you know this will only be used on Unix-like OSes, you can use external calls to the shell commands mkdir , chmod , and chown . Make sure to pass extra flags to recursively affect directories:
EDIT I originally used commands , which was a bad choice since it is deprecated and vulnerable to injection attacks. (For example, if a user gave input to create a directory called first/;rm -rf —no-preserve-root /; , one could potentially delete all directories).
EDIT 2 If you are using Python less than 2.7, use check_call instead of check_output . See the subprocess documentation for details.
Источник