Command substitution

2 snippets in Bash & Linux

SHBash & Linux

Variables & Quoting

SH · Bash Scripting
Syntax
name=value
$name or ${name}
"double quotes" vs 'single quotes'
Example
APP_ENV="production"
PORT=8080
echo "Server running on port ${PORT} in ${APP_ENV}"
FILES=$(ls *.conf)
READONLY_VAR="locked"
readonly READONLY_VAR
Output
Server running on port 8080 in production

Note No spaces around the = sign. Double quotes expand variables; single quotes are literal. Always double-quote variable expansions ("$var") to prevent word splitting and glob expansion. Use $() for command substitution instead of backticks.

Command Substitution

SH · Shortcuts & Productivity
Syntax
$(command)
`command` (legacy)
Example
echo "Today is $(date '+%A, %B %d')"
BRANCH=$(git rev-parse --abbrev-ref HEAD)
FILES_CHANGED=$(git diff --name-only | wc -l)
echo "${FILES_CHANGED} files changed on ${BRANCH}"
Output
Today is Saturday, April 04
3 files changed on feature/auth

Note Always use $() instead of backticks. $() nests cleanly: $(echo $(whoami)) works; backticks require escaping for nesting. The output has trailing newlines stripped automatically.

Frequently asked questions

How does Bash & Linux handle command substitution?
Bash & Linux covers this with 2 copy-ready snippets on this page. The "Variables & Quoting" snippet in Bash & Linux uses `name=value`.
Which command does the Bash & Linux example use?
The "Variables & Quoting" snippet uses `name=value`, from the Bash Scripting section of the Bash & Linux cheat sheet.
What other Bash & Linux snippets are shown for "command substitution"?
Besides "Variables & Quoting", this page also shows "Command Substitution".
Is there anything to watch out for?
Yes. For "Variables & Quoting": No spaces around the = sign. Double quotes expand variables; single quotes are literal. Always double-quote variable expansions ("$var") to prevent word splitting and glob expansion. Use $() for command substitution instead of backticks.