Command Substitution | Linux

2024/01/21

Working with the Linux operating system often requires command-line operations, and Command Substitution is a powerful feature that allows you to insert the output of one command into another command, or assign it to a variable.

What is Command Substitution?

In Linux, Command Substitution allows you to embed the output of a command into other commands. There are two main syntaxes:

Both syntaxes have the same effect: they assign the output of the command to the result variable.

1. Using backticks (``):

result=`command`

2. Using $() syntax:

result=$(command)

More Command Examples:

  1. Get the current date The date command is used to get the current date and time, and Command Substitution assigns its output to the current_date variable. Finally, the echo command displays a message with the current date.
# Using backticks
current_date=`date`
echo "Current date is $current_date"

# Or using $() syntax
current_date=$(date)
echo "Current date is $current_date"
  1. Count the number of lines in a file The wc -l filename.txt command counts the number of lines in the filename.txt file. Command Substitution assigns this number to the file_lines variable, and then the relevant information is displayed.
# Use the wc command to count lines
file_lines=$(wc -l filename.txt)

echo "The file has $file_lines lines."