Understanding Word Splitting

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 53 of 205

Word splitting is the step in which Bash cuts the result of an expansion into separate words. If a variable holds one two three and you use it without quotes, the command receives three arguments instead of one. Many surprising Bash bugs, such as files with spaces in their names being treated as several files, come from this single rule.

Understanding the Concept

A command line is a list of words. Normally you decide where one word ends and the next begins by typing spaces. Expansions complicate this: a variable or a command can produce text that contains spaces, tabs or newlines, and Bash must decide whether that text is one word or several.

The decision follows a fixed rule. After Bash performs parameter expansion, command substitution and arithmetic expansion, it scans the unquoted results and splits them at the characters listed in the IFS variable. The name stands for Internal Field Separator. Text you typed directly into the command line is not affected, and text inside quotes is not affected.

The examples below use two small helper functions. count reports how many arguments it received, and show prints each argument in square brackets, so the word boundaries are visible:

count() { echo "$# arguments"; }
show() { printf '[%s]\n' "$@"; }

Basic Example

v="one  two   three"
count $v
count "$v"
show $v
show "$v"

Output:

3 arguments
1 arguments
[one]
[two]
[three]
[one  two   three]
  • $v without quotes was split at the runs of spaces into three words. The extra spaces vanished, since the separators are discarded.
  • "$v" with quotes stayed one word, with every space preserved.

The IFS Variable

By default, IFS contains three characters: a space, a tab and a newline. You can see them with od, which shows non-printing characters:

printf '%s' "$IFS" | od -c

Output:

0000000      \t  \n
0000003

Any unquoted sequence of these characters acts as a separator. The same goes for text that contains tabs and newlines:

t=$'one\ttwo\nthree four'
show $t
show "$t"

Output:

[one]
[two]
[three]
[four]
[one	two
three four]

The unquoted version produced four words; the quoted version is a single word that contains a tab and a newline.

What Is Split and What Is Not

Splitting applies only to the results of these expansions, when they are not quoted:

  • Parameter expansion: $name, ${name}, ${name#prefix} and similar.
  • Command substitution: $(command).
  • Arithmetic expansion: $((...)).

It never applies to text you typed literally:

count a   b    c
count "a   b"
count $((1+2))

Output:

3 arguments
1 arguments
1 arguments

The first command has three words because you separated them yourself. The second quotes the spaces. The third produced the text 3, which contains no separator, so it is one word.

Several places never split at all:

  • Variable assignments: x=$v stores the whole value.
  • The word after case and the words inside [[ ... ]].
  • Here strings: the word after <<< is expanded but not split.
v="one  two   three"
x=$v
echo "$x"
cat <<< $v
case $v in "one  two   three") echo "case matched without quotes";; esac
[[ $v == "one  two   three" ]] && echo "[[ matched without quotes"

Output:

one  two   three
one  two   three
case matched without quotes
[[ matched without quotes

Empty and Whitespace-Only Values

An unquoted expansion that consists only of separators, or is empty, produces no word at all. A quoted one produces exactly one word, which is empty:

e=""
s="   "
unset u
count $e
count "$e"
count $s
count "$s"
count $u
count "$u"

Output:

0 arguments
1 arguments
0 arguments
1 arguments
0 arguments
1 arguments

This is the reason an empty variable can silently remove an argument from a command, which a later lesson on quoting examines in detail.

Splitting Command Substitution

The result of $(...) is split in the same way. Line breaks are separators, so each line, and each space-separated piece of a line, becomes a word:

out=$(printf 'x y\nz\n')
show $out
show "$out"

Output:

[x]
[y]
[z]
[x y
z]

The unquoted form turned two lines into three words. The quoted form kept both lines together as one word.

Changing IFS

IFS is an ordinary variable, so you can change it to split on something other than whitespace. Here, a comma is the separator:

csv="red,green,blue"
IFS=,
show $csv
IFS=$' \t\n'

Output:

[red]
[green]
[blue]

The last line restores the default value, using $'...' quoting to write the tab and newline.

Whitespace and Non-Whitespace Separators

Bash treats whitespace separators (space, tab, newline) differently from other separators.

  • Runs of whitespace separators count as one separator.
  • Every non-whitespace separator counts on its own, so two commas in a row produce an empty field.
sp="a  b"
IFS=,
csv2="a,,c"
show $csv2
IFS=$' \t\n'
show $sp

Output:

[a]
[]
[c]
[a]
[b]

The empty field between the two commas is kept. With the default IFS, the two spaces in a b were treated as one separator.

Leading and trailing separators behave differently from each other:

tr1="a,b,"
tr2=",a"
IFS=,
show $tr1
show $tr2
IFS=$' \t\n'

Output:

[a]
[b]
[]
[a]

A trailing separator does not create an empty field at the end, so a,b, gave only [a] and [b]. A leading separator does create an empty first field, so ,a gave [] and [a].

When IFS mixes both kinds, a non-whitespace separator together with surrounding whitespace counts as one separator:

IFS=', '
x="a, b,c  d"
show $x
IFS=$' \t\n'

Output:

[a]
[b]
[c]
[d]

Empty and Unset IFS

Setting IFS to an empty string turns splitting off:

v="one  two   three"
IFS=
show $v
IFS=$' \t\n'

Output:

[one  two   three]

If IFS is unset, Bash behaves as if it held the default characters:

unset IFS
show $v

Output:

[one]
[two]
[three]

Changing IFS Safely

Leaving IFS changed makes every later command behave differently, so limit the change to the place where it is needed. Three ways to do it:

For one command. A variable assignment placed directly before a command applies only to that command. read is the typical example:

IFS=: read -r a b c <<< "x:y:z"
echo "$a|$b|$c"
printf '%s' "$IFS" | od -c

Output:

x|y|z
0000000      \t  \n

The second command shows that IFS itself was not changed.

Inside a function, with local.

splitcsv() { local IFS=,; local -a parts=($1); echo "${#parts[@]} fields"; }
splitcsv "a,b,c,d"

Output:

4 fields

local IFS=, is undone when the function returns.

In a subshell, using parentheses, so the change disappears when the subshell ends.

Splitting Happens Before Globbing

After splitting, Bash performs filename expansion on each resulting word. The two steps combine, so an unquoted variable that contains a * can turn into file names. With files a.txt and b.txt in the current folder:

pat="*.txt other"
show $pat
set -f
show $pat
set +f

Output:

[a.txt]
[b.txt]
[other]
[*.txt]
[other]

First the value was split into *.txt and other. Then the pattern was matched against the folder. Running set -f switched filename expansion off, and the words stayed as they were. Once a name has been produced by globbing, it is not split again, so a file called my file.txt stays one word.

$@ and $*

The special parameters $@ and $* also depend on splitting rules. With f "a b" c, the function below receives two arguments, the first containing a space:

f() { count $@; count "$@"; count $*; count "$*"; }
f "a b" c

Output:

3 arguments
2 arguments
3 arguments
1 arguments
  • Unquoted $@ and $* are split, so a b became two words.
  • "$@" keeps each argument as its own word.
  • "$*" joins all arguments into one word, using the first character of IFS as the glue:
g() { local IFS=,; echo "$*"; }
g x y z

Output:

x,y,z

Splitting Into Arrays

An unquoted expansion inside parentheses fills an array using the split words. Quoted, it fills one element:

v="one  two   three"
words=($v)
echo "${#words[@]}"
words=("$v")
echo "${#words[@]}"

Output:

3
1

For splitting on a specific character, read -a with a temporary IFS avoids the globbing problem:

IFS=: read -ra parts <<< "usr:local:bin"
echo "${#parts[@]} parts: ${parts[1]}"

Output:

3 parts: local

Practical Applications

Splitting a Colon-Separated List

A PATH-style value splits cleanly, even when one directory name contains a space:

PATHX="/usr/bin:/bin:/opt/my tools"
IFS=: read -ra dirs <<< "$PATHX"
show "${dirs[@]}"

Output:

[/usr/bin]
[/bin]
[/opt/my tools]

An empty field is also preserved, which matters because an empty entry in PATH means the current directory:

IFS=:
p="/usr/bin:/bin::/opt"
show $p
IFS=$' \t\n'

Output:

[/usr/bin]
[/bin]
[]
[/opt]

Looping Over a Word List

When splitting is exactly what you want, an unquoted variable in a for loop is convenient:

list="red green blue"
for c in $list; do echo "color: $c"; done

Output:

color: red
color: green
color: blue

The same technique goes wrong when an item may contain a space:

fn="my file.txt"
for c in $fn; do echo "part: $c"; done
for c in "$fn"; do echo "whole: $c"; done

Output:

part: my
part: file.txt
whole: my file.txt

A Test That Breaks

The [ command receives its arguments after splitting, so an unquoted variable can change its meaning:

w="a b"
[ $w = "a b" ]
echo "status: $?"

Output:

bash: [: too many arguments
status: 2

After splitting, [ saw a, b, = and a b: four arguments, which it cannot interpret. Quoting "$w" fixes it, and the double-bracket form [[ $w = "a b" ]] avoids the problem because [[ does not split.

Availability in Other Shells

Word splitting and IFS are part of the POSIX shell standard. Dash splits unquoted results in the same way:

sh -c 'v="a  b c"; for w in $v; do echo "[$w]"; done'

Output:

[a]
[b]
[c]

Arrays and read -a are Bash features and are not available in Dash.

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 Understanding Word Splitting and get answers drawn from it.

Signed-in readers only.