Hone

Lessons · Terminal · $(...) (a command's output)

Using a command's output inside another

$(command) is replaced by what the command printed. $((2 + 3)) does whole-number maths.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Today's date in a file name, the number of files in a message, the result of one tool as an argument to the next.

How to think about it

Run the inner command on its own first and look at its output. Then wrap it in $(...) where that text should appear.

Worked example

echo "there are $(ls | wc -l) files here"
The inner command runs first: there are 0 files here.
count=$(printf 'a\nb\n' | wc -l)
Capture a pipeline's output in a variable.
echo $count
2.
echo $((count + 3))
5: arithmetic on it.

Your turn

Put today's date into the file name.

cp app.log app-(date +%F).log

The trap

Backticks do the same job and are still seen in old scripts, but they cannot nest and are easy to misread. Use $(...).

Practise $(...) (a command's output) on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.