Creating Files and Directories with touch and mkdir

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 16 of 205

Almost every task in a terminal starts with a place to put things. The touch command creates empty files, and the mkdir command creates directories. This lesson explains how each command works, what happens when the target already exists, and how to create a whole project layout with a single line.

Understanding the Concept

A file system stores two kinds of items that you create by hand: files, which hold data, and directories, which hold other items. Creating either one means adding an entry to a parent directory. If the parent does not exist, there is nowhere to add the entry, and the command fails. That one rule explains most of the error messages in this lesson.

CommandCreatesFails when
touch nameAn empty file (or updates the time of an existing one)The parent directory does not exist, or you lack write permission there
mkdir nameA directoryThe name already exists, or the parent directory does not exist

Both commands are external programs from the GNU coreutils package, so the options below are the GNU versions found on Linux. macOS ships BSD versions that accept the common options but differ in some details.

Creating Empty Files with touch

The simplest use of touch is to give it a file name:

touch notes.txt
ls -l --time-style=long-iso notes.txt

Output:

-rw-r--r-- 1 student student 0 2026-11-20 10:52 notes.txt

The file exists and its size is 0 bytes. touch never writes any content. Its real job is to set the timestamps of a file, and creating the file when it is missing is a side effect of that job.

What Happens When the File Already Exists

If the file exists, touch leaves its content alone and changes only the modification time to the current time. This makes touch safe to run on a file that already contains data. Nothing is erased.

You can set a specific time with -d:

touch -d "2026-01-15 09:30" notes.txt
ls -l --time-style=long-iso notes.txt

Output:

-rw-r--r-- 1 student student 0 2026-01-15 09:30 notes.txt

Build tools such as make compare modification times to decide which files are out of date, which is one practical reason to adjust a time deliberately. To copy the time from another file, use -r (reference):

touch -d "2025-12-01 08:00" ref.txt
touch -r ref.txt copy_time.txt
ls -l --time-style=long-iso ref.txt copy_time.txt

Output:

-rw-r--r-- 1 student student 0 2025-12-01 08:00 copy_time.txt
-rw-r--r-- 1 student student 0 2025-12-01 08:00 ref.txt

Here copy_time.txt did not exist, so touch created it and then gave it the time of ref.txt.

Creating Several Files at Once

touch accepts any number of names:

touch a.txt b.txt c.txt
ls

Output:

a.txt  b.txt  c.txt

Bash can generate the names for you with brace expansion, which is performed by the shell before touch even starts. The shell turns report_{1..3}.txt into three separate words:

touch report_{1..3}.txt
ls report_*

Output:

report_1.txt  report_2.txt  report_3.txt

The command that actually ran was touch report_1.txt report_2.txt report_3.txt. A later lesson covers brace expansion in detail.

Updating Only Existing Files

The -c option (no create) tells touch to do nothing when the file is missing:

touch -c ghost.txt
echo "status=$?"
ls ghost.txt

Output:

status=0
ls: cannot access 'ghost.txt': No such file or directory

The status is 0, which means success, because -c makes "skip missing files" a valid outcome. The file was not created, as the ls error confirms.

When touch Fails

touch cannot create a file inside a directory that does not exist:

touch nodir/x.txt

Output:

touch: cannot touch 'nodir/x.txt': No such file or directory

The message says cannot touch rather than cannot create, because from the command's point of view it was trying to update a timestamp. The fix is to create the directory first, which is the job of mkdir.

Creating Directories with mkdir

mkdir stands for "make directory":

mkdir projects
ls

Output:

projects

Like touch, it accepts several names, and each one is created independently:

mkdir one two three
ls

Output:

one  projects  three  two

When the Directory Already Exists

Unlike touch, plain mkdir treats an existing name as an error:

mkdir projects
echo "status=$?"

Output:

mkdir: cannot create directory 'projects': File exists
status=1

The message says File exists even for a directory, because on Linux a directory is a special kind of file. The non-zero status matters in scripts, where a failed mkdir should usually stop the script.

Creating Parent Directories with -p

Without -p, mkdir creates only the last component of the path, and every earlier component must already exist:

mkdir a/b/c
echo "status=$?"

Output:

mkdir: cannot create directory 'a/b/c': No such file or directory
status=1

The option -p (parents) creates every missing directory along the path:

mkdir -p a/b/c
echo "status=$?"
ls -R a

Output:

status=0
a:
b

a/b:
c

a/b/c:

The option -p has a second effect that makes it very popular in scripts: it does not complain when the directory already exists.

mkdir -p projects
echo "status=$?"

Output:

status=0

So mkdir -p means "make sure this directory exists", which can be run any number of times with the same result. A script that behaves this way is called idempotent.

Seeing What Was Created with -v

The -v option (verbose) prints a line for each directory that mkdir creates:

mkdir -v v1 v2
mkdir -pv deep/er/still

Output:

mkdir: created directory 'v1'
mkdir: created directory 'v2'
mkdir: created directory 'deep'
mkdir: created directory 'deep/er'
mkdir: created directory 'deep/er/still'

With -p, you can see every level that was added, which is helpful when you are not sure how much of a path already existed.

Permissions of New Items

Every new item receives permissions that depend on a setting called the umask. Print it with umask:

umask

Output:

0022

The umask lists permission bits to remove. New directories start from 777 and new files from 666. Removing 022 leaves 755 for directories (rwxr-xr-x) and 644 for files (rw-r--r--), which matches the -rw-r--r-- line you saw earlier.

mkdir -m sets the permissions of a new directory directly. This example creates a directory that only the owner can enter:

mkdir -m 700 private
ls -ld private projects

Output:

drwx------ 2 student student 4096 2026-11-20 10:52 private
drwxr-xr-x 2 student student 4096 2026-11-20 10:52 projects

The directory private shows drwx------, and projects shows the default drwxr-xr-x. A later lesson explains permission strings fully.

Names That Contain Spaces

The shell splits a command line into words at every space. A name with a space therefore needs quotes, or it becomes two arguments:

touch "my file.txt"
mkdir "my folder"
mkdir my other folder
ls

Output:

folder  my  my file.txt  my folder  other

The first two commands each created one item with a space in its name: the file my file.txt and the directory my folder. The third command had no quotes, so mkdir received three separate arguments and created three directories named my, other and folder. Quoting the name, or escaping each space with a backslash as in my\ folder, is the reliable way to avoid this surprise.

Practical Applications

Creating a Project Skeleton

Brace expansion and mkdir -p combine well. This creates a directory tree for a small project:

mkdir -p myapp/{src,tests,docs}
touch myapp/README.md myapp/src/main.py myapp/tests/test_main.py
find myapp | sort

Output:

myapp
myapp/README.md
myapp/docs
myapp/src
myapp/src/main.py
myapp/tests
myapp/tests/test_main.py

The first command expands into mkdir -p myapp/src myapp/tests myapp/docs. Because of -p, myapp is created automatically along the way. The second command then fills the structure with empty starter files.

Braces can be nested to create a grid of directories:

mkdir -p src/{main,test}/{java,resources}
find src | sort

Output:

src
src/main
src/main/java
src/main/resources
src/test
src/test/java
src/test/resources

Each of the two choices in the first brace pair is combined with each of the two choices in the second pair, giving four leaf directories.

Making a Script Safe to Run Twice

A setup script often needs a directory for its output. Using mkdir -p means the script works on the first run and on every run after that:

mkdir -p "$HOME/backups/2026"

If the script had used plain mkdir, the second run would print File exists and return a failing status.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Creating Files and Directories with touch and mkdir and get answers drawn from it.

Signed-in readers only.