Course contentsShow
← Linux
Lesson 248 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Word Splitting Mechanisms

Master the rules behind how Bash parses arguments to commands.

In this lesson, you will learn how Bash decides where one command argument ends and the next begins using a process called Word Splitting.

After Bash finishes expanding variables, command substitutions, and arithmetic expressions, it looks at the resulting text to see if it needs to be chopped into separate pieces. This mechanism is what allows you to use spaces, tabs, and newlines to separate command arguments.

The IFS Variable

The secret engine behind word splitting is the IFS (Internal Field Separator) environment variable. By default, IFS is set to a space, a tab, and a newline. When Bash encounters any of these characters in an unquoted expansion, it treats them as delimiters.

Consider this example:

files="report.txt notes.txt"
ls $files

Here, Bash expands $files into report.txt notes.txt. Because there is a space between the filenames, and a space is part of the IFS, Bash splits this into two separate arguments for ls. ls then correctly processes both files.

The Danger of Splitting

Word splitting only happens if you omit double quotes. If you wrap the variable in quotes, like ls "$files", the expansion is treated as a single "word" (one argument), and word splitting is suppressed.

This is why experienced scripters use quotes almost everywhere. Without them, if one of your filenames accidentally contained a space (e.g., My Report.txt), the word splitter would incorrectly break it into two separate files (My and Report.txt), likely causing your command to fail.

When Splitting is Helpful

Word splitting is intentionally helpful when you want to generate multiple arguments from a single variable. For example:

flags="-l -h"
ls $flags /home/user

Bash splits $flags into two distinct arguments (-l and -h), making them appear as if you had typed ls -l -h /home/user directly into your terminal. By understanding how IFS defines your "split points," you gain full control over how your scripts parse data.

Key Takeaway: Word splitting uses the characters defined in the IFS variable to break unquoted expansions into multiple command arguments; use double quotes to prevent this behavior when you want to preserve spaces as part of a single argument.