How Bash Reads and Parses Input

Updated

October 31, 2026

How Bash Reads and Parses Input

Understanding the Bash execution model begins with lexical analysis and parsing. When Bash receives a command line, it does not execute it immediately. Instead, it processes the text through a series of discrete phases:

  1. Reading and Tokenization: Bash splits the input stream into tokens (words and operators) based on metacharacters (space, tab, newline, ;, &, (, ), |, <, >).
  2. Grammar Parsing: Identifies command structures, pipelines, control flow constructs (if, while, for, case), and reserved words.
  3. Compound Expansions: Executes parameter, command, arithmetic, and pathname expansions in a strict predefined sequence.
  4. Command Execution: Locates the executable (special built-in, function, alias, regular built-in, or external binary via $PATH) and forks/execs.

Builtin vs. Keyword vs. External Binary

Bash treats commands in a strict lookup priority:

# 1. Alias (only in interactive shells by default)
alias myls='ls -la'

# 2. Shell Keyword (part of the language grammar)
type if
# if is a shell keyword

# 3. Shell Function (user-defined routines)
type myfunc

# 4. Shell Builtin (executed directly inside the shell process, zero fork cost)
type cd
# cd is a shell builtin

# 5. External Binary (found via PATH lookup in the filesystem)
type grep
# grep is /usr/bin/grep