Great question! Command substitution is a powerful feature that allows you to take the output of a command and use it as an argument (a piece of data) for another command.
Think of it as "piping" the answer of one question directly into another command.
1. The Syntax
There are two ways to write it in Linux:
- Modern way (Recommended):
$(command) - Old way:
`command`(using backticks)
2. How it works visually
When you run a command like this:
echo "Today is $(date)"
The Shell follows these steps:
- It sees the
$()and pauses theechocommand. - It runs
datein the background. - The output (e.g.,
Tue Dec 23...) replaces the entire$(date)string. - Finally, it runs the full
echocommand with the new text.
3. Practical Examples
Here are a few ways you might use it in the real world:
-
Creating a Timestamped File:
Instead of typing the name manually, you can let the system do it:touch report-$(date +%F).txtThis creates a file named something like
report-2025-12-23.txt. -
Storing Output in a Variable:
CURRENT_USER=$(whoami) echo "The logged in user is $CURRENT_USER" -
Counting lines in a file:
If you wanted to say how many words are in a file (using thewordsfile in your project folder):echo "This file has $(wc -l < words) lines."
Why is it useful?
It allows you to make your commands dynamic. Instead of hard-coding values (like a specific date or username), your commands can adapt based on the current state of the system.
Try it yourself in the terminal:
echo "I am $(whoami) and the time is $(date +%R)"
Does that make sense, or would you like to see how to use it with different commands?