Skip to main content

How to Create Directory in Bash

• 2 min read
bash file operations directory creation mkdir

Quick Answer: Create a Directory in Bash

To create a directory in Bash, use the mkdir command: mkdir mydir. For nested directories, use the -p flag: mkdir -p /path/to/nested/directory. This creates all parent directories as needed without errors.

Quick Comparison: Directory Creation Methods

MethodPurposeFlagsBest For
mkdirSingle directoryNoneSimple creation
mkdir -pNested structure-pComplex paths
mkdir -m 755With permissions-mSetting perms
mkdir -vVerbose output-vSeeing progress
mkdir -p + chmodNested + perms-p + chmodComplex setup

Bottom line: Use mkdir -p for safe nested directory creation.


Create directories in Bash using the mkdir command.

Create Single Directory

mkdir mydir

Create Nested Directories

# Create nested structure
mkdir -p /home/user/documents/projects/myblog

The -p flag creates parent directories as needed.

Create Multiple Directories

mkdir dir1 dir2 dir3

Create with Specific Permissions

# Create with 755 permissions (rwxr-xr-x)
mkdir -m 755 mydir

# Create with 700 permissions (rwx-----)
mkdir -m 700 private_dir

Practical Examples

Create Directory if It Doesn’t Exist

dir="/home/user/documents"

if [ ! -d "$dir" ]; then
  mkdir -p "$dir"
  echo "Created directory: $dir"
fi

Create Backup Directory

backup_dir="$HOME/backups/$(date +%Y-%m-%d)"
mkdir -p "$backup_dir"

echo "Backup saved to: $backup_dir"

Create Project Structure

#!/bin/bash

project_name="myproject"

mkdir -p "$project_name"/{src,tests,docs,bin}

echo "Project structure created:"
ls -la "$project_name"/

Output:

bin/
docs/
src/
tests/

Create Temporary Directory

# Create unique temporary directory
tmpdir=$(mktemp -d)
echo "Temporary directory: $tmpdir"

# Do work...

# Clean up
rm -rf "$tmpdir"

Error Handling

#!/bin/bash

dir="$1"

if mkdir -p "$dir" 2>/dev/null; then
  echo "Directory created successfully"
else
  echo "ERROR: Failed to create directory"
  exit 1
fi

Permissions Reference

ValuePermissionsMeaning
700rwx------Owner only
755rwxr-xr-xOwner full, others read+execute
777rwxrwxrwxEveryone full access
# Always use -p to create parent directories
mkdir -p "$directory_path"