15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
16.11.2023

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 rsync and tar operate 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 have sudo privileges
  • 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:

pwd

Method 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_name

Example:

mkdir project_files

This 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 -la

Naming 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" or mkdir 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_directory

Example:

mkdir /var/www/html/myapp

Important 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 directory

The 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 ./subdirectory

Method 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_directory

Example:

mkdir -p /var/www/html/myapp/logs/archive

If /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 dir3

Example:

mkdir assets uploads cache sessions

This 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/data

Combining with -p for multiple nested paths:

mkdir -p /srv/project/frontend/src /srv/project/backend/src /srv/project/docs

This 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_name

Common permission patterns:

Octal ModeSymbolicTypical Use Case
700rwx------Private user data, SSH key directories
750rwxr-x---Application directories shared with a group
755rwxr-xr-xPublic web document roots
770rwxrwx---Shared team directories
777rwxrwxrwxTemporary scratch space (avoid in production)

Example — creating a secure directory for SSH keys:

mkdir -m 700 ~/.ssh

Example — creating a web root with correct permissions:

mkdir -m 755 /var/www/html/newsite

Combining -m and -p:

mkdir -p -m 750 /srv/app/config/secrets

Note 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/build

Multi-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:

  1. Open the Files application from the Activities menu or the dock
  2. Navigate to the parent directory where you want the new folder
  3. Right-click on an empty area within the directory
  4. Select New Folder from the context menu
  5. 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 -e to abort on any error
  • Quote all variables ("$dir") to handle paths with spaces safely
  • Combine mkdir -p with chown and chmod in 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

CommandCreates Intermediate DirsSets PermissionsMultiple DirsIdempotent
mkdir dirNoNo (uses umask)NoNo
mkdir -p path/to/dirYesNo (uses umask)NoYes
mkdir -m 755 dirNoYesNoNo
mkdir -p -m 750 path/dirYesYes (final dir only)NoYes
mkdir dir1 dir2 dir3NoNo (uses umask)YesNo
mkdir -p {a,b,c}/subYesNo (uses umask)YesYes

Common Errors and How to Fix Them

Error: Permission denied

mkdir: cannot create directory '/etc/myapp': Permission denied

Cause: You are attempting to write to a system-owned directory without elevated privileges.

Fix: Prepend sudo:

sudo mkdir /etc/myapp

Error: No such file or directory

mkdir: cannot create directory '/srv/app/config': No such file or directory

Cause: One or more intermediate directories in the path do not exist.

Fix: Use the -p flag:

mkdir -p /srv/app/config

Error: File exists

mkdir: cannot create directory 'mydir': File exists

Cause: 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-x

When 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

ScenarioRecommended Command
Single directory, interactive sessionmkdir dirname
Directory at a known absolute pathmkdir /full/path/dirname
Nested path, some parents may not existmkdir -p /full/nested/path
Multiple sibling directories at oncemkdir dir1 dir2 dir3
Complex multi-level tree in one commandmkdir -p root/{a,b,c}/{sub1,sub2}
Directory with non-default permissionsmkdir -m 750 dirname
Automated provisioning scriptmkdir -p with chown/chmod in sequence
Idempotent deployment pipeline stepmkdir -p (safe to re-run)

Key Technical Takeaways

  • mkdir -p is the safest default for any scripted or automated directory creation — it is idempotent and handles missing intermediate paths
  • Never use 777 permissions on production directories; prefer 755 for public paths and 750 or 700 for sensitive data
  • The -m flag in mkdir sets permissions only on the final directory when used with -p — use chmod -R or per-level mkdir calls for full control
  • Brace expansion is a Bash feature, not a mkdir feature — it will not work in /bin/sh scripts 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 chown assignment in provisioning scripts to avoid a window where directories exist with incorrect ownership
  • On VPS Control Panels environments, web server users (typically www-data or nginx) 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.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started