When to Use $(…) vs ${…} in Bash: Command vs Parameter Substitution Explained
This article explains the technical differences between Bash's command substitution $(command) and parameter expansion ${parameter}, illustrating their syntax, usage examples, and precedence rules so readers can choose the appropriate form for scripting tasks.
Background
Linux and other GNU‑based operating systems rely on Bash (the Bourne Again Shell) as a powerful command‑language interpreter, offering both interactive use and scripting capabilities that extend beyond the original Bourne shell.
Command substitution $(...)
The $(command) construct performs command substitution: the enclosed command is executed in a subshell, its standard output is captured, and the result replaces the expression in the surrounding command.
echo "今天是 $(date). LinuxMi.com 又是美好的一天。"In this example, date runs first, its output is inserted into the echo statement, and the final string is printed.
Parameter expansion ${...}
The ${parameter} syntax handles parameter (variable) expansion. It allows the shell to replace a variable name with its value and supports additional features such as default values, substring extraction, and indirect expansion. animal=lion Attempting to echo $animals prints nothing because the variable animals is undefined. Using parameter expansion correctly yields the desired result: echo ${animal}s This prints lions, demonstrating how braces disambiguate the variable name from following characters.
Differences and precedence
While both forms replace text, they serve distinct purposes: $(...) runs a command and substitutes its output, whereas ${...} substitutes the value of an existing variable. Bash also supports indirect expansion with ${!var}, where the value of var is treated as the name of another variable.
animal=lion
lion=rafiki
echo ${!animal} # expands to the value of variable named by $animal, i.e., "rafiki"In such cases, the indirect expansion takes precedence over the direct variable value.
Conclusion
Understanding when to use $(command) for command substitution and ${parameter} for variable expansion helps write clearer, more reliable Bash scripts, avoiding common pitfalls related to quoting, naming, and expansion order.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
