How to Use Command Substitution in Bash: Simple Guide
In Bash, use
$(command) to run a command and replace it with its output. This lets you store or use the output directly in variables or other commands.Syntax
The basic syntax for command substitution in Bash is $(command). Here, command is any valid shell command. Bash runs this command first, then replaces the whole $(command) expression with the output of that command.
This allows you to use the output as part of another command or assign it to a variable.
bash
result=$(date)
echo "Current date and time: $result"Output
Current date and time: Sat Jun 8 12:34:56 UTC 2024
Example
This example shows how to use command substitution to get the current directory name and use it in a greeting message.
bash
current_dir=$(pwd)
echo "You are in the directory: $current_dir"Output
You are in the directory: /home/user
Common Pitfalls
One common mistake is using backticks `command` which is the older style and harder to read, especially when nested. Another issue is forgetting to quote the substitution which can cause word splitting or globbing problems.
Always prefer $(command) and quote the result if it might contain spaces.
bash
wrong_way=`ls -l` echo "$wrong_way" right_way="$(ls -l)" echo "$right_way"
Output
total 0
-rw-r--r-- 1 user user 0 Jun 8 12:00 file1
-rw-r--r-- 1 user user 0 Jun 8 12:00 file2
total 0
-rw-r--r-- 1 user user 0 Jun 8 12:00 file1
-rw-r--r-- 1 user user 0 Jun 8 12:00 file2
Quick Reference
- Use:
$(command)to run and capture output. - Assign:
var=$(command)to save output in a variable. - Quote: Use quotes around substitution if output has spaces:
"$(command)". - Avoid: Backticks
`command`for better readability and nesting.
Key Takeaways
Use $(command) to run a command and use its output in Bash.
Always quote command substitution if output may contain spaces.
Avoid backticks `command` as they are harder to read and nest.
Command substitution helps store or reuse command output easily.
It is a fundamental tool for writing flexible Bash scripts.