How to Create a New Folder in Ubuntu: Complete Directory Management Guide
Creating a new folder in Ubuntu is done primarily with the mkdir command in the terminal. The basic syntax is mkdir folder_name, which instantly creates a directory in your current working location. For nested structures, mkdir -p parent/child/grandchild creates the entire path in a single operation, even if intermediate directories do not yet exist.
This guide goes well beyond the basics. It covers every practical method for creating directories on Ubuntu — from simple single-folder creation to recursive structures, permission-aware provisioning, and automation-ready scripting patterns used in real production server environments.
Why Proper Directory Structure Matters on a Linux Server
On any Ubuntu server, the file system is the backbone of every operation. Poorly organized directories create cascading problems: broken application paths, misconfigured permission hierarchies, failed backup jobs, and security vulnerabilities caused by world-writable directories placed in sensitive locations.
A disciplined approach to directory management directly affects:
- Permission inheritance — child directories inherit parent permissions unless explicitly overridden, making initial structure decisions critical
- Backup scope — backup tools like
rsyncandtaroperate on directory trees, so logical grouping reduces backup complexity - Service configuration — web servers (Apache, Nginx), databases, and application runtimes all depend on predictable, well-defined directory paths
- Audit and compliance — structured paths make log correlation and forensic analysis significantly faster
If you are managing a VPS Hosting environment or a Dedicated Server, establishing a consistent directory convention from day one prevents technical debt that compounds rapidly as the system grows.
Prerequisites
Before executing any of the commands below, confirm the following:
- You have access to a terminal (local or via SSH)
- Your user account has write permission to the target location
- For system-level directories (e.g., under
/etc/or/var/), you havesudoprivileges - Ubuntu version: these commands apply universally to Ubuntu 18.04, 20.04, 22.04, and 24.04 LTS
To verify your current working directory at any time, run:
pwdMethod 1: Basic Directory Creation with mkdir
The mkdir (make directory) command is the standard POSIX utility for creating directories. It is available on every Linux distribution without installation.
Syntax:
mkdir directory_nameExample:
mkdir project_filesThis creates a directory named project_files in your current location. The command produces no output on success — this is standard Unix behavior. To confirm creation:
ls -laNaming conventions to follow in production:
- Use lowercase letters and underscores or hyphens:
web_assets,backup-2024 - Avoid spaces in directory names — they require escaping (
mkdir "my folder"ormkdir my folder) and break many shell scripts - Avoid special characters:
&,*,?,!,|have shell-specific meanings and cause unpredictable behavior
Method 2: Creating a Directory at a Specific Absolute Path
Rather than navigating to a target location first, you can pass the full absolute path directly to mkdir. This is the preferred approach in scripts and automated provisioning.
Syntax:
mkdir /full/path/to/new_directoryExample:
mkdir /var/www/html/myappImportant constraint: This command will fail if any intermediate directory in the path does not already exist. For example, if /var/www/html/ does not exist, the above command returns:
mkdir: cannot create directory '/var/www/html/myapp': No such file or directoryThe solution is the -p flag, covered in Method 3.
Using relative paths is equally valid and often more readable in interactive sessions:
mkdir ../sibling_directory
mkdir ./subdirectoryMethod 3: Creating Nested Directories Recursively with -p
The -p (parents) flag is one of the most operationally important options in mkdir. It instructs the command to create all missing intermediate directories in the specified path, and it suppresses the error that would normally occur if the target directory already exists.
Syntax:
mkdir -p parent_directory/child_directory/grandchild_directoryExample:
mkdir -p /var/www/html/myapp/logs/archiveIf /var/www/html/myapp/ does not exist, this single command creates the entire chain: myapp, then logs inside it, then archive inside that.
Critical production use case — web server document roots:
mkdir -p /var/www/vhosts/example.com/{public_html,logs,ssl,tmp}This brace expansion syntax (covered in detail in Method 6) combined with -p is a standard pattern for provisioning new virtual host environments in a single command.
The -p flag also prevents errors in idempotent scripts. If you run the same mkdir -p command twice, the second execution does nothing and exits cleanly with code 0. Without -p, the second run would return an error, breaking any script that uses set -e (exit on error).
Method 4: Creating Multiple Directories Simultaneously
mkdir accepts multiple arguments, creating all specified directories in a single invocation.
Syntax:
mkdir dir1 dir2 dir3Example:
mkdir assets uploads cache sessionsThis creates four separate directories in the current location. All directories are created at the same level — this is not a nested structure.
Combining with absolute paths:
mkdir /srv/app/modules /srv/app/config /srv/app/dataCombining with -p for multiple nested paths:
mkdir -p /srv/project/frontend/src /srv/project/backend/src /srv/project/docsThis is particularly useful when scaffolding a new application directory structure before deployment.
Method 5: Creating Directories with Specific Permissions Using -m
By default, mkdir applies permissions based on the system's umask value. On most Ubuntu systems, the default umask is 0022, which means new directories receive permissions of 755 (owner: read/write/execute; group: read/execute; others: read/execute).
In many server scenarios, the default permissions are either too permissive or too restrictive. The -m flag lets you set exact permissions at creation time using octal notation.
Syntax:
mkdir -m octal_mode directory_nameCommon permission patterns:
| Octal Mode | Symbolic | Typical Use Case |
|---|---|---|
700 | rwx------ | Private user data, SSH key directories |
750 | rwxr-x--- | Application directories shared with a group |
755 | rwxr-xr-x | Public web document roots |
770 | rwxrwx--- | Shared team directories |
777 | rwxrwxrwx | Temporary scratch space (avoid in production) |
Example — creating a secure directory for SSH keys:
mkdir -m 700 ~/.sshExample — creating a web root with correct permissions:
mkdir -m 755 /var/www/html/newsiteCombining -m and -p:
mkdir -p -m 750 /srv/app/config/secretsNote that when using -p, the mode is applied only to the final directory in the path, not to any intermediate directories that are created. Intermediate directories receive the default umask-based permissions. If you need precise control over all levels, create each level individually with explicit -m flags, or use chmod after the fact.
Method 6: Brace Expansion for Complex Directory Trees
Brace expansion is a Bash shell feature — not a mkdir option — that generates multiple arguments from a single pattern. Combined with mkdir -p, it is the most efficient way to create complex directory hierarchies.
Basic brace expansion:
mkdir -p project/{src,tests,docs,build}This expands to:
mkdir -p project/src project/tests project/docs project/buildMulti-level brace expansion:
mkdir -p app/{frontend/{components,pages,styles},backend/{controllers,models,routes},shared/utils}This creates the following structure:
app/
├── frontend/
│ ├── components/
│ ├── pages/
│ └── styles/
├── backend/
│ ├── controllers/
│ ├── models/
│ └── routes/
└── shared/
└── utils/This pattern is standard practice when initializing new application repositories or provisioning application directories on a fresh VPS with cPanel or bare-metal server.
Method 7: Creating Directories via the Ubuntu GUI (Files Application)
For desktop Ubuntu installations or remote desktop sessions, the GNOME Files application (Nautilus) provides a graphical method.
Steps:
- Open the Files application from the Activities menu or the dock
- Navigate to the parent directory where you want the new folder
- Right-click on an empty area within the directory
- Select New Folder from the context menu
- Type the desired folder name and press Enter
Keyboard shortcut: In Nautilus, Ctrl+Shift+N creates a new folder instantly without using the right-click menu.
Limitations of the GUI approach:
- Cannot set custom permissions during creation — requires a follow-up action in the terminal or file properties
- Cannot create recursive nested structures in a single operation
- Not available in headless server environments (the vast majority of production Ubuntu servers run without a desktop environment)
For any serious server administration work, the command-line methods are always preferred.
Method 8: Scripting Directory Creation for Automation
In real-world server administration, directories are rarely created manually one at a time. Provisioning scripts, deployment pipelines, and configuration management tools all rely on automated directory creation.
Basic shell script example:
#!/bin/bash
set -e
BASE_DIR="/var/www/vhosts"
DOMAIN="example.com"
directories=(
"$BASE_DIR/$DOMAIN/public_html"
"$BASE_DIR/$DOMAIN/logs"
"$BASE_DIR/$DOMAIN/ssl"
"$BASE_DIR/$DOMAIN/tmp"
"$BASE_DIR/$DOMAIN/backup"
)
for dir in "${directories[@]}"; do
mkdir -p "$dir"
echo "Created: $dir"
done
# Set ownership to web server user
chown -R www-data:www-data "$BASE_DIR/$DOMAIN"
chmod -R 755 "$BASE_DIR/$DOMAIN"
echo "Directory structure for $DOMAIN provisioned successfully."Key scripting practices:
- Always use
set -eto abort on any error - Quote all variables (
"$dir") to handle paths with spaces safely - Combine
mkdir -pwithchownandchmodin the same script to ensure permissions are correct immediately after creation - Use arrays for directory lists to keep scripts readable and maintainable
This approach is essential when managing multiple virtual hosts, deploying applications across environments, or automating server setup with tools like Ansible or Bash-based provisioning scripts.
Comparison: mkdir Options and Their Use Cases
| Command | Creates Intermediate Dirs | Sets Permissions | Multiple Dirs | Idempotent |
|---|---|---|---|---|
mkdir dir | No | No (uses umask) | No | No |
mkdir -p path/to/dir | Yes | No (uses umask) | No | Yes |
mkdir -m 755 dir | No | Yes | No | No |
mkdir -p -m 750 path/dir | Yes | Yes (final dir only) | No | Yes |
mkdir dir1 dir2 dir3 | No | No (uses umask) | Yes | No |
mkdir -p {a,b,c}/sub | Yes | No (uses umask) | Yes | Yes |
Common Errors and How to Fix Them
Error: Permission denied
mkdir: cannot create directory '/etc/myapp': Permission deniedCause: You are attempting to write to a system-owned directory without elevated privileges.
Fix: Prepend sudo:
sudo mkdir /etc/myappError: No such file or directory
mkdir: cannot create directory '/srv/app/config': No such file or directoryCause: One or more intermediate directories in the path do not exist.
Fix: Use the -p flag:
mkdir -p /srv/app/configError: File exists
mkdir: cannot create directory 'mydir': File existsCause: A directory or file with that name already exists.
Fix: Use -p to suppress this error when the existing path is a directory, or choose a different name.
Silent failure in scripts: If mkdir fails and your script does not use set -e or check exit codes, subsequent operations may proceed on a non-existent path, causing unpredictable failures. Always validate critical directory creation:
mkdir -p /srv/app/data || { echo "Failed to create data directory"; exit 1; }Security Considerations for Directory Creation
Directory permissions are a first-line defense in server security. Several high-impact vulnerabilities stem directly from incorrect directory permissions:
- World-writable directories (
777) allow any user on the system to write, modify, or delete files — a critical risk on shared hosting or multi-user servers - Incorrect ownership on web-facing directories can allow web application exploits to write malicious files outside the intended document root
- Sticky bit (
chmod +t) on shared directories (like/tmp) prevents users from deleting files owned by others — always set this on shared writable directories - SetGID bit on directories ensures new files inherit the group of the directory rather than the creating user's primary group — useful for collaborative project directories
Example — secure shared project directory:
mkdir -p /srv/shared/project
chown root:developers /srv/shared/project
chmod 2775 /srv/shared/project # SetGID + rwxrwxr-xWhen hosting web applications, SSL-secured domains, or email services, proper directory permissions are inseparable from the security posture of your SSL Certificates configuration and your Email Hosting setup.
Verifying Directory Creation
After creating directories, always verify the result before proceeding with dependent operations.
List with detailed permissions:
ls -la /path/to/parent/Verify a specific directory exists (useful in scripts):
[ -d /srv/app/config ] && echo "Directory exists" || echo "Directory missing"View the full tree structure (requires tree package):
sudo apt install tree -y
tree /srv/app/Check inode usage — on servers with many small files, inode exhaustion can prevent directory creation even when disk space is available:
df -i /srv/If inode usage is near 100%, you cannot create new directories or files regardless of available disk space. This is a common production issue on servers hosting large numbers of small files, such as mail servers or PHP session directories.
Practical Decision Matrix: Which Method to Use
| Scenario | Recommended Command |
|---|---|
| Single directory, interactive session | mkdir dirname |
| Directory at a known absolute path | mkdir /full/path/dirname |
| Nested path, some parents may not exist | mkdir -p /full/nested/path |
| Multiple sibling directories at once | mkdir dir1 dir2 dir3 |
| Complex multi-level tree in one command | mkdir -p root/{a,b,c}/{sub1,sub2} |
| Directory with non-default permissions | mkdir -m 750 dirname |
| Automated provisioning script | mkdir -p with chown/chmod in sequence |
| Idempotent deployment pipeline step | mkdir -p (safe to re-run) |
Key Technical Takeaways
mkdir -pis the safest default for any scripted or automated directory creation — it is idempotent and handles missing intermediate paths- Never use
777permissions on production directories; prefer755for public paths and750or700for sensitive data - The
-mflag inmkdirsets permissions only on the final directory when used with-p— usechmod -Ror per-levelmkdircalls for full control - Brace expansion is a Bash feature, not a
mkdirfeature — it will not work in/bin/shscripts unless the shell is Bash - Always check inode availability (
df -i) on high-density file systems before bulk directory creation - Combine directory creation with immediate
chownassignment in provisioning scripts to avoid a window where directories exist with incorrect ownership - On VPS Control Panels environments, web server users (typically
www-dataornginx) must have execute permission on every directory in the document root path — not just the final directory
FAQ
What is the difference between mkdir folder and mkdir -p folder?
mkdir folder creates a single directory and fails if any part of the path does not exist or if the directory already exists. mkdir -p folder creates all missing intermediate directories and exits silently without error if the target already exists, making it safe for scripts and repeated execution.
Can mkdir create a directory with spaces in the name?
Yes. Wrap the name in quotes: mkdir "my project folder" or escape the spaces: mkdir my project folder. However, spaces in directory names are strongly discouraged on servers because they require escaping in every subsequent command and break many shell scripts and application configurations.
Why does mkdir fail with "Permission denied" even with sudo?
This typically occurs when the target filesystem is mounted read-only, when SELinux or AppArmor policies restrict writes to that path, or when the path is on a network filesystem with server-side restrictions. Check mount options with mount | grep /target/path and review AppArmor logs with sudo aa-status.
How do I create a directory and immediately set its owner and group?
mkdir itself does not set ownership — use chown immediately after: mkdir -p /srv/app && chown www-data:www-data /srv/app. In a single pipeline: install -d -m 755 -o www-data -g www-data /srv/app — the install command creates directories with owner, group, and mode in one step.
What happens to permissions when using mkdir -p with multiple new levels?
Only the final (deepest) directory receives the mode specified by -m. All intermediate directories that are newly created receive permissions derived from the current umask. If consistent permissions across all levels are required, either create each level individually with explicit -m flags or apply chmod -R after the full path is created.
