Understanding Command Substitution
Command substitution is a mechanism that allows you to store the output of a command in a variable. This technique is essential when you need to process command results programmatically, such as capturing file listings, system information, or calculating time differences.
In shell scripting, two primary syntaxes achieve command substitution:
variable=`commands`
variable=$(commands)
The commands section can contain a single command or multiple commands separated by semicolons.
Practical Time Measurement Examples
Let's explore different approaches to measuring execution time using command substitution:
| Script | Output | Key Concepts |
|---|---|---|
#!/bin/bash start_time=`date +%T` sleep 5 end_time=$(date +%T) echo "Started: $start_time" echo "Completed: $end_time" |
Started: 14:25:30 Completed: 14:25:35 | Uses %T format to capture time in HH:MM:SS format |
#!/bin/bash initial_epoch=`date +%s` sleep 5 final_epoch=$(date +%s) duration=$((final_epoch - initial_epoch)) echo "Epoch start: $initial_epoch" echo "Epoch end: $final_epoch" echo "Duration: ${duration} seconds" |
Epoch start: 1678904730 Epoch end: 1678904735 Duration: 5 seconds | 1. %s format provides Unix timestamp 2. Note the space after 'date' command 3. (( )) enables arithmetic operations in shell |
Handling Multi-line Output
When commands output multiple lines or contain consecutive whitespace, proper quoting becomes crucial:
#!/bin/bash
file_data=$(ls -la)
echo Without quotes:
$file_data
echo
echo With quotes:
"$file_data"
Output demonstrates the difference:
Without quotes:
total 8 -rw-r--r-- 1 user group 156 Jan 15 10:30 script.sh -rw-r--r-- 1 user group 42 Jan 15 10:31 notes.txt
With quotes:
total 8
-rw-r--r-- 1 user group 156 Jan 15 10:30 script.sh
-rw-r--r-- 1 user group 42 Jan 15 10:31 notes.txt
Always wrap variables containing command output in double quotes when displaying to preserve line breaks and whitespace integrity.
Syntax Comparison: Backticks vs $()
While both syntaxes are functionally equivalent for basic substitution, several difference influence their usage:
Readability: The $() syntax clearly distinguishes substitution from regular strings, avoiding confusion with single quotes.
Nesting capabliity: $() supports nesting while backticks do not. Example:
file_count=$(wc -l $(find /home -name "*.log" | head -1))
echo "Lines in first log file: $file_count"
Portability: Backticks work acros most shell implementations, while $() is specific to Bash and some modern shells.
For new scripts, prefer $() for its clarity and nesting support, unless compatibility with older shells is required.