Bash: Command Substitution
Command substitution allows you to use the output of a command as a variable or as an argument for another command. This is a powerful feature for building dynamic scripts.
Syntax for Command Substitution
Using `$(...)`
current_date=$(date)
echo "Today's date is $current_date"The modern and preferred syntax is to enclose the command in `$()`. The shell will first execute the command inside the parentheses and then replace the entire expression with the command's standard output.
Using backticks `...`
current_date=`date`
echo "Today's date is $current_date"This is the older syntax for command substitution. It works similarly to `$(...)` but can be more difficult to read and less reliable in nested commands. The `$(...)` syntax is recommended.
Practical Examples
Creating a directory with the current date
mkdir "backup_$(date +%Y-%m-%d)"This command will create a new directory with a name that includes the current year, month, and day. The `date +%Y-%m-%d` command provides a formatted string as its output.
Counting files in a directory
file_count=$(ls | wc -l)
echo "There are $file_count files in this directory."This example demonstrates piping within a command substitution. The output of `ls` is piped to `wc -l` (word count with lines), and the final result (the line count) is stored in the `file_count` variable.