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
| Method | Purpose | Flags | Best For |
|---|---|---|---|
| mkdir | Single directory | None | Simple creation |
| mkdir -p | Nested structure | -p | Complex paths |
| mkdir -m 755 | With permissions | -m | Setting perms |
| mkdir -v | Verbose output | -v | Seeing progress |
| mkdir -p + chmod | Nested + perms | -p + chmod | Complex 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
| Value | Permissions | Meaning |
|---|---|---|
| 700 | rwx------ | Owner only |
| 755 | rwxr-xr-x | Owner full, others read+execute |
| 777 | rwxrwxrwx | Everyone full access |
Recommended Pattern
# Always use -p to create parent directories
mkdir -p "$directory_path"