What Is Command Substitution? Using Output as a Value
Command substitution runs a command and replaces it with its output, letting you use the result of one command as a value inside another.
Often you need the output of one command as the input or argument to another, the current Git commit, today's date, the result of a query. Command substitution does exactly that: it runs a command and drops its output into the surrounding line. CI scripts rely on it constantly to compute tags, paths, and version strings.
What command substitution is
It captures the standard output of a command and substitutes it in place. The modern form is $(command); the older form uses backticks. The output replaces the expression before the line runs.
A simple example
Writing TAG=$(git rev-parse --short HEAD) runs the Git command and stores its output in TAG. You can then use "$TAG" to label a build or image with the commit it came from.
Why prefer $() over backticks
$()nests cleanly, while backticks are awkward to nest.- It is easier to read in long lines.
- Quoting rules inside
$()are more predictable.
Quoting the result
Always quote the substitution, as in "$(cmd)", to keep the output intact when it contains spaces or newlines. Unquoted, the shell splits the output on whitespace, which causes subtle bugs.
Command substitution in CI
Pipelines use it to derive values: a commit SHA for an image tag, a timestamp for an artifact name, a version from a file. Note that the command runs in a subshell, so a failure inside it can be missed unless you check the exit code.
Computing values on managed runners
On Latchkey runners, command substitution lets a step compute a value once and reuse it. Quote results and verify the inner command succeeded, especially under set -e, so a failed substitution does not feed empty data downstream.
Key takeaways
- Command substitution replaces a command with its output, via
$(...). - Prefer
$()over backticks and always quote the result. - CI uses it to compute tags, versions, and paths from command output.