In Command Line Interface and scripting languages, the backquote or backtick character (`) is often used to enclose a command that needs to be executed in the shell. The shell executes the backquote command and replaces it with the command output. This feature is known as command substitution.
This post illustrates the objective, usage, and functionality of backquote/backtick in command with the following outlines:
How Does the Backquote or Backtick Work?
In script programming, the backquote character (`) creates a link between two commands where the second command is dependent on the output of the first one. By enclosing the first command in backquotes, the output of the command is captured and used as input for the second command.
How to Use Backquote or Backtick in Commands?
The usage of backquote is very easy and straightforward in commands or scripts. Let’s see its practical implementation with the help of examples.
Example 1:
Here we have a “Sample.sh” bash script having the content shown below:
$ nano Sample.sh
#!/bin/bash
file_count=`ls | wc -l`
echo "There are $file_count files in this directory"
- The first line of this script is called a “bash shebang” and tells the computer to execute the script in a bash shell.
- The next line assigns a value to a variable named “file_count“. This value is the output of a group of commands enclosed in backticks (`). The first command, “ls“, lists all files present in the targeted directory, and the second command, “wc -l“, counts the number of lines in the output.
- The final line uses the “echo” command to display the output of the “file_count” variable. This prints the total number of files in the current directory to the terminal:
Simply execute the “Sample.sh” script in the terminal and see the results:
$ ./Sample.sh
Here, the “$file_count” variable value received and from the “ls | wc -l” command has been displayed in the terminal.
Example 2:
Here is another example to execute the “date” command displayed using the “echo” command. The same procedure of “backtick” is followed but with a few changes in the commands.
A bash script is created named “New.sh”:
$ nano New.sh
#!/bin/bash
d=`date+%y+:%m:%d`
echo "Today date is $d"
The description of the script is:
- The `date` command assigns the current date in “year:month:date” format to the “$d” variable.
- After that, the output will be displayed using the “echo” command.
The execution of the “New.sh” script provides output like this:
$ ./New.sh
The output shows the result of the “date” encoded in “backtick(`)” using the “echo” command.
Conclusion
In Linux, shell scripts use an essential component “backtick or backquote” for the command substitution. It basically assigns the desired shell command output to the variable that can be used globally in the script. This guide provides a brief detail on the purpose and usage of the backquote or backtick in commands.