🎓 A1Learner
🔍
0 of 50 lessons completed

Shell Command Substitution

Command substitution is the way to paste a command's output into a line. $(command) runs the command and puts its output in place of the $(...).

Paste a count into a sentence

The count from wc -l lands inside the sentence.

echo "There are $(wc -l < notes.txt) lines in notes.txt"

Store a date in a variable

Command substitution can fill a variable.

day=$(date -d '2026-01-15' '+%A')
echo "$day"

Build a file name from a count

The pasted count becomes part of the new name.

cp notes.txt "notes-$(wc -l < notes.txt).txt"
ls notes-*.txt

The old backtick form

Backticks do the same job, but $() is the form to use.

echo `wc -l < notes.txt`

Use output as an argument

The first line of notes.txt becomes part of the echo.

echo "First line: $(head -n 1 notes.txt)"

Example

count=$(sort shopping.txt | uniq | wc -l)
echo "Shopping list has $count different items."

Key points

  • Command substitution: $(command) runs a command and pastes its output into the line.
  • Use $(...) to put a result inside a longer word or sentence.
  • Backticks: `command` is the old form of command substitution.
  • Use $(...) instead of backticks, because nesting backticks is hard to read.

In this example, sort and uniq leave one copy of each shopping item. Then wc -l counts them. Then command substitution stores that count in count. Then echo prints the sentence with the count in place.

Note

The output's final newline is removed before it is pasted in.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does $(wc -l < notes.txt) put into a line?