How Bash Reads and Parses Input
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:
- Reading and Tokenization: Bash splits the input stream into tokens (words and operators) based on metacharacters (
space,tab,newline,;,&,(,),|,<,>). - Grammar Parsing: Identifies command structures, pipelines, control flow constructs (
if,while,for,case), and reserved words. - Compound Expansions: Executes parameter, command, arithmetic, and pathname expansions in a strict predefined sequence.
- 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