Overview
This lecture explains the two forms of command substitution in Bash: backticks (`) and dollar-parentheses ($()), comparing their usage, differences, and practical implications.`
Command Substitution in Bash
- Bash supports two command substitution methods: backticks (
`command`) and dollar-parentheses ($(command)).
- The output of a command can be assigned to a variable using either method.
Backticks (`` )
- Backticks are supported in both the original Bourne shell and modern shells.
- They allow a command's output to be captured and used in variables or other commands.
- Backticks can get confusing and difficult to read when nested, due to needing multiple levels of escaping.
- Backticks are sometimes mistaken for single quotes, leading to visual confusion.
- Example:
count=`ls -1 | wc -l` assigns the number of directory entries to count.
Dollar Parentheses ($())
$() is supported in all POSIX-compliant shells and is preferred in modern scripting.
- The command inside
$() runs in a subshell and its output is substituted into the main command.
- Dollar-parentheses are more readable, especially for nested commands or complex logic.
- Example:
count=$(ls -1 | wc -l) performs the same task with improved readability.
Comparison: Backticks vs Dollar Parentheses
- Both methods produce the same result and are called command substitution.
- Dollar-parentheses are much easier to read and nest than backticks.
- Nesting backticks requires escaping, making it error-prone and harder to maintain.
- Dollar-parentheses is the modern, recommended approach for new scripts.
Key Terms & Definitions
- Command Substitution — A shell feature that allows the output of a command to replace the command itself in a line.
- Backticks (
`) — The original syntax for command substitution, using the back quote character.
- Dollar Parentheses (
$() ) — The newer and preferred syntax for command substitution in POSIX shells.
- Nesting — Placing one command substitution inside another.`
Action Items / Next Steps
- Practice rewriting scripts using
$() instead of backticks.
- Try nesting command substitutions with both methods to observe the difference in readability.
- Review Bash scripting documentation for more examples of command substitution.