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.