Working with Filenames That Contain Spaces

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 111 of 205

On Linux and macOS a filename may contain almost any character: spaces, tabs, quotes, asterisks, even newlines. Only the slash / (which separates directories) and the null byte are forbidden. Files created by people, downloaded from the web or copied from Windows often have names such as my report.txt or Budget 2026 Final.xlsx. Bash handles these names correctly only when a script is written with that possibility in mind.

This lesson shows why spaces break commands, which habits keep filenames intact, and how to recognize the places where a name can still be split by accident. It brings together ideas from earlier lessons on word splitting (53), quoting (55) and file loops (82) and applies them to everyday file work.

Why a Space Breaks a Command

Bash reads a command line and splits it into words. The first word is the command, and every other word becomes one argument. Spaces and tabs separate the words. A filename with a space therefore looks like two arguments unless something tells Bash that the space is part of the name.

The same thing happens a second time after variable expansion. When a variable is used without double quotes, Bash splits its value at the characters in IFS (space, tab and newline by default) and then treats each piece as a separate word. This step is called word splitting (lesson 53).

The examples use a folder with three files:

touch "my report.txt" "notes.txt" "budget 2026 final.txt"
ls
budget 2026 final.txt
my report.txt
notes.txt

The quotes in the touch command make each name one argument, so three files are created, not six.

An Unquoted Variable

f="my report.txt"
cat $f
cat: my: No such file or directory
cat: report.txt: No such file or directory

The assignment stores the full name correctly; quotes are needed there only because of the space on the right side. The problem appears when the value is used. $f without quotes expands to my report.txt, word splitting cuts it into my and report.txt, and cat receives two arguments that name files that do not exist. cat returns status 1.

With double quotes, the value stays one word:

echo hello > "$f"
cat "$f"
hello

Double quotes still allow the variable to be expanded, but they turn off word splitting and filename expansion for the result. This is the single most important rule for filenames: put double quotes around every variable and command substitution that holds a filename.

Unquoted Variables in Tests

The single-bracket test command receives its arguments after splitting, so an unquoted name with a space changes the number of arguments:

[ -f $f ] && echo yes
bash: [: my: binary operator expected

[ received -f, my, report.txt and ]. It tried to read my report.txt as a comparison, failed, and returned status 2. Writing [ -f "$f" ] fixes the test.

The double-bracket form is different. [[ ]] is part of Bash's syntax, and Bash does not word-split variables inside it (lesson 69):

[[ -f $f ]] && echo yes
yes

Quoting inside [[ ]] is still harmless, and keeping the habit everywhere avoids having to remember which places are exceptions.

Three Ways to Write a Name with a Space

When typing a name directly on the command line, there are three equivalent ways to keep the space inside the word:

ls my\ report.txt
ls 'my report.txt'
ls "my report.txt"

Each prints:

my report.txt
  • A backslash escapes the single character that follows it. Tab completion in an interactive shell inserts these backslashes automatically.
  • Single quotes keep every character literally. Nothing inside them is expanded.
  • Double quotes keep spaces but still expand $variables and $(commands).

Quotes can also wrap only part of a word. "$dir"/file.txt and backup/"$name" are both single words, because Bash joins adjacent quoted and unquoted parts that have no space between them.

Looping Over Files: Globs, Not ls

A glob such as *.txt is expanded by Bash itself (lesson 52). Each matching filename becomes one word, whatever characters it contains, and the result is not split again:

for x in *.txt; do
    echo "[$x]"
done
[budget 2026 final.txt]
[my report.txt]
[notes.txt]

The brackets in the output make the boundaries of each value visible. All three names arrive intact.

Looping over the output of ls gives a different result:

for x in $(ls); do
    echo "[$x]"
done
[budget]
[2026]
[final.txt]
[my]
[report.txt]
[notes.txt]

$(ls) produces one block of text. Because the command substitution is unquoted, Bash splits that text at every space and newline, and the loop sees six words. Quoting it as "$(ls)" would produce the opposite problem: a single word containing all three names. ls is designed for people to read, not for scripts to parse, and a glob is the correct way to list files in a loop.

Inside the loop, the variable must still be quoted wherever it is used: cp "$x" backup/, wc -l "$x", mv "$x" "$x.bak".

When Nothing Matches

If no file matches a glob, Bash leaves the pattern as it is, and the loop runs once with the literal text:

for f in *.pdf; do echo "[$f]"; done
[*.pdf]

Either check that the file exists with [ -e "$f" ] || continue at the top of the loop, or turn on nullglob so that an unmatched pattern expands to nothing (lessons 82 and 149):

shopt -s nullglob
for f in *.pdf; do echo "[$f]"; done
echo "end"
end

Storing Several Filenames: Arrays

A plain variable can safely hold one filename. To keep several names, use an array (lesson 97). Each element keeps its spaces, and "${files[@]}" expands to one word per element:

files=( *.txt )
echo "${#files[@]}"
printf '<%s>\n' "${files[@]}"
3
<budget 2026 final.txt>
<my report.txt>
<notes.txt>

Without the quotes, the elements are split again:

printf '<%s>\n' ${files[@]}
<budget>
<2026>
<final.txt>
<my>
<report.txt>
<notes.txt>

A common attempt is to collect names in a single string separated by spaces, such as list="$list $f". That string cannot be split back into the original names, because the spaces between names look exactly like the spaces inside them. An array avoids the problem entirely.

The same rule applies to a function's or script's arguments. "$@" passes each argument as one word, while unquoted $@ splits them (lesson 43):

show() { printf '<%s>\n' "$@"; }
args() { show "$@"; echo ..; show $@; }
args "a b.txt" c.txt
<a b.txt>
<c.txt>
..
<a>
<b.txt>
<c.txt>

Commands Stored in Variables

Storing a whole command in a string and running it unquoted has the same flaw:

cmd="ls my report.txt"
$cmd
ls: cannot access 'my': No such file or directory
ls: cannot access 'report.txt': No such file or directory

Adding quotes inside the string does not help, because quotes that come out of a variable are ordinary characters, not shell syntax. An array keeps each argument separate:

cmd=(ls -l "my report.txt")
"${cmd[@]}"

The ls -l line for my report.txt is printed as expected.

Filenames That Begin with a Dash

A name that starts with - is not a space problem, but it fails in the same situations. Most commands read any argument that begins with a dash as options. With a file named -n file.txt in the folder:

touch -- "-n file.txt" "a b.txt" "c.txt"
ls *.txt
ls: invalid option -- ' '
Try 'ls --help' for more information.

The glob expanded correctly, but ls read -n file.txt as the options -n, (a space), f, and so on, and stopped at the invalid space option. Without --, the touch command that creates the file fails the same way (touch: invalid option -- 'n').

Two fixes work with nearly every command:

ls -- *.txt
ls ./*.txt
-n file.txt
a b.txt
c.txt
./-n file.txt
./a b.txt
./c.txt
  • -- marks the end of options. Every later argument is treated as a filename, even if it starts with a dash.
  • ./*.txt puts ./ in front of every match, so no argument can begin with a dash. This form also works with commands that do not support --.

Lesson 161 returns to this topic when it covers validating user-supplied filenames.

Reading Filenames from a File or Command

Sometimes the names come from a list rather than from a glob. while IFS= read -r reads each line into one variable without splitting it:

printf '%s\n' "my report.txt" "notes.txt" > list.txt

while IFS= read -r name; do
    printf '%s bytes: %s\n' "$(wc -c < "$name")" "$name"
done < list.txt
6 bytes: my report.txt
0 bytes: notes.txt
  • IFS= keeps leading and trailing spaces in the name. Without it, read removes them.
  • -r keeps backslashes as ordinary characters.
  • "$name" is quoted everywhere it is used.

The effect of IFS= is easy to see with a name that begins with spaces:

printf '  lead.txt\n' | { read -r n; echo "[$n]"; }
printf '  lead.txt\n' | { IFS= read -r n; echo "[$n]"; }
[lead.txt]
[  lead.txt]

Lesson 114 covers reading files line by line in more depth. A list with one name per line still breaks for the rare filename that contains a newline. The fully safe way to pass names between commands uses the null byte as a separator, which is the subject of lesson 112.

Names with Tabs and Newlines

Tabs and newlines in filenames are rare but legal. They break line-based tools such as ls | wc -l, which counts a name with a newline as two lines. A folder with the five files new⏎line.txt (a newline in the name), p_q.log, s p.txt, tab⇥name.txt (a tab) and x_y_z.txt gives:

ls | wc -l
6

ls -1 --quoting-style=shell-escape (GNU) and printf '%q\n' show such names in a form that can be typed back into the shell:

printf '%q\n' *line.txt
$'new\nline.txt'

The same folder shows why picking a file from ls output is fragile:

latest=$(ls -t | head -n 1)
echo "[$latest]"
[new]

The newest file was new⏎line.txt, but head -n 1 stopped at the newline inside its name.

Renaming Files to Remove Spaces

When a script controls the names, replacing spaces with underscores avoids the issue for later tools. Parameter expansion with ${f// /_} replaces every space (lesson 54):

touch "x y z.txt" "p q.log"
for f in *\ *; do
    [ -e "$f" ] || continue
    mv -- "$f" "${f// /_}"
done
ls -1
p_q.log
x_y_z.txt
  • *\ * matches only names that contain a space; the backslash makes the space part of the pattern.
  • [ -e "$f" ] || continue skips the literal pattern when nothing matches.
  • -- protects names that begin with a dash, and both arguments of mv are quoted.

If two names would become the same (for example a b.txt and a_b.txt), mv overwrites the second. mv -n (or mv --update=none in recent GNU coreutils) refuses to overwrite an existing file, as described in lesson 17.

Paths That Contain Spaces

Directory names can contain spaces too, so full paths need the same care. Parameter expansion and basename/dirname keep the spaces when their arguments are quoted:

p="/home/ana/My Docs/my report.txt"
basename "$p"
dirname "$p"
echo "${p##*/}"
echo "${p%/*}"
my report.txt
/home/ana/My Docs
my report.txt
/home/ana/My Docs

Copying into a folder with a space works the same way:

mkdir "Back Up"
cp "$f" "Back Up/"
ls "Back Up"
my report.txt

Other Tools That Split Names

Bash is not the only program that splits text at spaces. Several common tools do it on their own:

  • awk splits each line into fields at spaces. ls -l | awk '{print $NF}' prints report.txt for my report.txt, because the last field is only the last word of the name.
  • xargs without options splits its input at spaces and newlines:
ls "s p.txt" | xargs wc -c
wc: s: No such file or directory
wc: p.txt: No such file or directory
0 total
  • cut and read with the default IFS split at spaces unless told otherwise.

find ... -exec command {} + passes each found name as a separate argument without any splitting, and find -print0 | xargs -0 (lesson 112) does the same through a pipe.

A Quick Way to Spot Splitting

When a script behaves strangely with certain files, print the values with markers around them. printf '[%s]\n' "$var" or printf '<%s>\n' "${arr[@]}" makes every word boundary visible, as the examples in this lesson do. Running the script with bash -x (lesson 126) shows each command after expansion, which reveals where a name became two arguments. ShellCheck (lesson 162) also warns about unquoted variables before the script is ever run.

The examples were run with Bash 5.2.21, GNU coreutils 9.4 and GNU findutils 4.9.0. Error messages are shown in their interactive form (beginning with bash:).

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 Working with Filenames That Contain Spaces and get answers drawn from it.

Signed-in readers only.