Backtick (`) symbol in Linux Shell Scripting

One of the most useful features of shell scripts is the lowly back quote character, usually called the backtick (`) in the Linux world. Be careful—this is not the normal single quotation mark character you are used to using for strings. Because it is not used very often outside of shell scripts, you may not even know where to find it on your keyboard. You should become familiar with it, because it's a crucial component of many shell scripts.

Hint: On a U.S. keyboard, it is usually on the same key as the tilde symbol ( ∼ ).

The backtick allows you to assign the output of a shell command to a variable. While this doesn't seem like much, it is a major building block in script programming. You must surround the entire command line command with backtick characters:

# testing=`date`

The shell runs the command within the backticks and assigns the output to the variable testing. Here's an example of creating a variable using the output from a normal shell command:

$ cat myscript.sh
#!/bin/bash
# using the backtick character
testing=`date`
echo "The date and time are: $testing"
$

The variable testing receives the output from the date command, and it is used in the echo statement to display it. Running the shell script produces the following output:

The today variable is assigned the output of a formatted date command. This is a common technique used to extract date information for log filenames. The +%y%m%d format instructs the date command to display the date as a two-digit year, month, and day:

$ date +%y%m%d
140721
$

The script assigns the value to a variable, which is then used as part of a filename. The file itself contains the redirected output of a directory listing. After running the script, you should see a new file in /tmp directory:

The log file appears in the directory using the value of the $today variable as part of the filename. The contents of the log file are the directory listing from the /usr/bin directory. If the script is run the next day, the log filename will belog.140722 , thus creating a new file for the new day.