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

Expansion Order Logic

Master the order of variable, brace, and tilde expansions.

In this lesson, you will learn how Bash processes complex commands by following a strict, predictable sequence of expansions.

When you type a command into your terminal, Bash doesn’t just execute it as raw text. It performs a series of "expansions" to turn your shorthand into the final command it will actually run. Understanding this order is vital because some expansions happen before others, meaning later stages can "see" the results of earlier ones.

The Rule of Sequence

Bash follows this specific hierarchy when processing a line:

  1. Brace Expansion: Bash creates strings based on patterns (e.g., file_{a,b}.txt becomes file_a.txt file_b.txt).
  2. Tilde Expansion: Bash converts the ~ character into your home directory path (e.g., ~/docs becomes /home/user/docs).
  3. Variable Expansion: Bash replaces $VAR with its actual value.

Why the Order Matters

Because Brace Expansion happens first, it occurs before variable expansion. This is a common trap for beginners. Consider this script:

FILES="1,2"
echo file_{$FILES}.txt

You might expect this to print file_1.txt file_2.txt. However, because brace expansion happens first, Bash sees the braces before it ever looks at the $FILES variable. It treats the braces as literal characters and ends up trying to find a file named literally file_{1,2}.txt.

If you want the variable to be processed before the braces, you would need to use eval or a different approach like a loop, because the shell has already finished its "brace phase" by the time it reaches your variable.

Visualizing the Pipeline

Think of it like a factory assembly line. If the "Brace Station" is at the start of the belt, the "Variable Station" cannot feed information back into the Brace Station. Once the command has passed the brace phase, the shell moves on, never to revisit it. This logic ensures that the shell remains efficient and predictable, even if it occasionally catches us off guard when we try to pass variables into brace-expanded patterns.

Key Takeaway: Bash processes Brace, Tilde, and then Variable expansions in a rigid, one-way sequence, meaning the results of later expansions cannot influence the earlier ones.