The mkdir
command in Linux stands for “make directory” and is used to create new directories (folders) in the filesystem. It allows users to organize files hierarchically by generating single or multiple directories at once.
Key features include creating nested directory structures automatically, setting permissions during creation, and handling complex directory names with spaces or special characters. The command is indispensable for scripting, file management, and maintaining an organized directory tree.
Create a Single Directory
mkdir documents
Creates a directory named documents
in the current location.
Create Multiple Directories
mkdir dir1 dir2 dir3
Creates three directories (dir1
, dir2
, dir3
) in the current directory.
Create Nested Directories Recursively
mkdir -p projects/2023/src
- The
-p
flag creates parent directories if they don’t exist. - Builds the full path
projects/2023/src
even ifprojects
or2023
are missing.
Set Directory Permissions
mkdir -m 750 private_dir
-m
sets permissions (e.g.,750
= owner:rwx
, group:r-x
, others:---
).
Create Directories with Spaces
mkdir "My Photos"
Use quotes to create directories with spaces in their names.
Handle Special Characters in Names
mkdir 'dir$name' # Quotes for special characters like $
mkdir dir\#temp # Backslash to escape #
Creates directories with names containing $
, #
, or other special characters.
Verbose Mode (Show Confirmation)
mkdir -v logs
-v
prints a message:mkdir: created directory 'logs'
.
Create Timestamped Directories
mkdir "backup_$(date +%F)"
Creates a directory like backup_2023-10-23
using the current date.
Use Brace Expansion for Multiple Subdirectories
mkdir -p app/{src,dist,test}
Creates app/src
, app/dist
, and app/test
in one command.
Create Directories from a List in a File
xargs mkdir -p < list_of_dirs.txt
Reads directory names from list_of_dirs.txt
and creates them.
Create Hidden Directories
mkdir .config
Hidden directories start with a .
(e.g., .config
for configuration files).
Temporary Directories for Scripts
mkdir -p /tmp/myscript_temp
Creates a temporary directory for short-lived files in scripts.
Combine with && for Workflows
mkdir -p /opt/app && cd "$_"
Creates /opt/app
and immediately navigates into it using cd "$_"
.
Create Directories with Default Permissions via umask
umask 022 && mkdir new_project
umask 022
ensures new directories have755
permissions by default.
Avoid Errors with Existing Directories
mkdir -p existing_dir
-p
suppresses errors ifexisting_dir
already exists.
Key Notes:
- Use
-p
(parents) to automate nested directory creation. - Always quote directory names with spaces or special characters.
- Verify permissions with
ls -l
after creating directories.
The mkdir
command simplifies directory management, making it essential for both casual users and system administrators. 🐧