Pcornel
Linux · Shell & Bash

Command Substitution

Cheat sheet · https://pcornel.dk/topic.php?topic=2687

Back to the Topic

Answer

Command substitution $(command) runs a command and inserts its stdout into the command line, for example today=$(date +%F). The older backtick form does the same.

Remember

Trailing newlines are removed. Unquoted, the result is word-split and globbed — quote it: "$(cmd)". A failing command inside $( ) does not stop the script unless you check $? or use set -e carefully.

First checks

  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — exit code of the last command

Verify in this order

subshell runs the command → stdout captured → trailing newlines removed → inserted (and split unless quoted)

Where it usually breaks

First mismatch in persistent intent → provider/parser/generator → kernel/userspace runtime → dependency/security context → logs/counters → consumer-visible read-back; preserve identity/native diagnostic/pre-state before mutation.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=2687

Confirmation

Confirm action

Continue?