mkdir ‐ #folders #files - five4nets/Linux-Knowledgebase GitHub Wiki
mkdir
Command
Tutorial: Using the Linux The mkdir
(make directory) command in Linux is used to create directories (folders) in the file system. This tutorial covers the command's syntax, options, and practical examples, with references for further reading.
Syntax
mkdir [OPTIONS] DIRECTORY...
- OPTIONS: Flags to modify the command's behavior.
- DIRECTORY: Name(s) of the directory(ies) to create.
Common Options
-p
,--parents
: Create parent directories as needed; no error if directories already exist.-m
,--mode=MODE
: Set permissions for the new directory (e.g.,755
oru=rwx,g=rx,o=rx
).-v
,--verbose
: Display a message for each created directory.--help
: Show help information.--version
: Display the command version.
Examples
1. Create a Single Directory
Create a directory named my_folder
in the current working directory.
mkdir my_folder
- If
my_folder
already exists, an error is displayed:mkdir: cannot create directory ‘my_folder’: File exists
.
2. Create Multiple Directories
Create several directories (docs
, images
, videos
) at once.
mkdir docs images videos
- This creates all specified directories in the current directory.
-p
3. Create Nested Directories with Create a directory structure like project/src/include
where parent directories (project
, src
) don't exist.
mkdir -p project/src/include
- The
-p
option ensures parent directories are created as needed, and no error occurs if any part of the path already exists.
-m
4. Set Directory Permissions with Create a directory secure_folder
with specific permissions (e.g., 700
, meaning only the owner has read, write, and execute permissions).
mkdir -m 700 secure_folder
- Verify permissions with:
ls -ld secure_folder
- Output:
drwx------ 2 user user 4096 Jun 25 14:00 secure_folder
-v
5. Verbose Output with Create directories and display confirmation for each one.
mkdir -v backups logs
- Output:
mkdir: created directory 'backups'
mkdir: created directory 'logs'
6. Create Directories with Spaces in Names
To create a directory with a space in its name, use quotes or escape the space.
mkdir "my new folder"
OR
mkdir my\ new\ folder
- Both commands create a directory named
my new folder
.
7. Combine Options
Create a nested directory structure, set permissions, and show verbose output.
mkdir -p -m 750 -v app/config/data
- Output:
mkdir: created directory 'app'
mkdir: created directory 'app/config'
mkdir: created directory 'app/config/data'
- The
app/config/data
directory has permissionsrwxr-x---
.
Practical Tips
- Check if Directory Exists: Use
ls
ortest -d
to verify:
test -d my_folder && echo "Directory exists" || echo "Directory does not exist"
- Avoid Errors with
-p
: Always use-p
when scripting to prevent failures if directories already exist. - Permissions: Learn more about Linux permissions with
man chmod
or online resources (see below).