Working with Filenames That Contain Spaces
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
$variablesand$(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../*.txtputs./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,readremoves them.-rkeeps 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" ] || continueskips the literal pattern when nothing matches.--protects names that begin with a dash, and both arguments ofmvare 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}'printsreport.txtformy 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
IFSsplit 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:).