Overview
This lecture explains the differences and similarities between bash command substitution methods using backticks () and dollar parentheses $(), covering their usage, syntax, and best practices.
Command Substitution Forms in Bash
- Bash supports two command substitution forms: backticks (`) and dollar parentheses $().
- $() syntax is not supported by the original Bourne shell but is supported by all POSIX-conformant shells.
- Both forms allow output from a command to be used as input in another command or assigned to a variable.`
Using Backticks ()
- Backticks use the ` character to enclose a command whose output is captured.
- Output can be assigned to variables, e.g., `list=``ls```.
- Nesting backticks requires escaping, making scripts harder to read and maintain.
- Common commands using backticks: count=
ls -1 | wc -l, dateToday=date.
Using Dollar Parentheses $()
- Dollar parentheses $() enclose a command, which runs in a subshell and returns output.
- Syntax example: list=$(ls), count=$(ls -1 | wc -l), dateToday=$(date).
- Allows direct use of command output in other commands or variable assignments.
- Easier to nest multiple commands using $() compared to backticks.
Backticks vs Dollar Parentheses: Comparison
- Both forms perform command substitution and are equivalent in newer shells.
- Backticks can be confused with single quotes and require escaping when nested.
- $() is more readable and manageable, especially for complex or nested commands.
Key Terms & Definitions
- Command Substitution — Process of replacing a command with its output in a shell script.
- **Backticks (
)** — Older command substitution syntax using command`.
- Dollar Parentheses $() — Preferred command substitution syntax using $(command).
- Nesting — Placing one command substitution inside another.`
Action Items / Next Steps
- Practice writing bash scripts using both backticks and dollar parentheses for command substitution.
- Compare readability and maintenance of scripts using nested command substitutions with both methods.