Understanding Word Splitting
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]
$vwithout 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=$vstores the whole value. - The word after
caseand 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, soa bbecame two words. "$@"keeps each argument as its own word."$*"joins all arguments into one word, using the first character ofIFSas 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.