typestar

Command substitution in Bash

A command's output, used as a value.

# $( ) captures a command's output into a value
today=$(date +%Y-%m-%d)
echo "today is $today"

count=$(printf 'a\nb\nc\n' | wc -l)
echo "$count lines"

# substitutions nest without escaping
parent=$(basename "$(dirname /usr/local/bin)")
echo "parent dir: $parent"

How it works

  1. $(date ...) runs and its stdout becomes the string.
  2. Pipelines work inside; so does nesting, without escapes.
  3. Quote the result like any other expansion.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
264
Tokens
43
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 30 seconds.

Type this snippet

Step 2 of 3 in Functions, step 14 of 26 in Language basics.

← Previous Next →