In Bash, command substitution is a feature that allows you to capture the output of a command and use it as part of another command or assign it to a variable. It provides a way to dynamically incorporate the result of a command into your script.
Command substitution can be achieved using either the $()
syntax or backticks (“).
Here’s an example using the $()
syntax:
current_date=$(date +%Y-%m-%d)
echo "Today's date is: $current_date"
In this example, the date
command is executed within the $()
command substitution syntax. The output of the date
command, which represents the current date in the specified format (%Y-%m-%d), is captured and assigned to the current_date
variable. Subsequently, the value of current_date
is displayed using echo
.
The same example can be written using backticks:
current_date=`date +%Y-%m-%d`
echo "Today's date is: $current_date"
Both forms achieve the same result. However, the $()
syntax is recommended over backticks due to its better readability and ease of nesting multiple command substitutions.
Command substitution can be useful in various scenarios, such as:
- Assigning the output of a command to a variable for further processing.
- Embedding the output of a command within a string or command.
- Passing the output of a command as an argument to another command.
Here’s an example of using command substitution to embed command output within a string:
echo "The current working directory is: $(pwd)"
In this case, the $(pwd)
command substitution is used to capture the current working directory, and the result is embedded within the string passed to echo
.
Overall, command substitution is a powerful feature in Bash that allows you to incorporate the dynamic output of commands into your scripts, making them more flexible and adaptable.