Backtick (`) symbol in Linux Shell Scripting – Tec Geeks
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:
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:
$ chmod u+x myscript.sh $ ./myscript.sh The date and time are: Mon Jul 21 09:13:42 IST 2014 $
That’s not all that exciting in this example (you could just as easily just put the command in the echo statement), but once you capture the command output in a variable, you can do anything with it.
Here’s a popular example of how the backtick is used to capture the current date and use it to create a unique filename in a script:
#!/bin/bash # copy the /usr/bin directory listing to a log file today=`date +%y%m%d` ls /usr/bin -al > /tmp/log.$today
The today variable is assigned the output of the 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:
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:
$ ls -l /tmp/log.140721 -rw-rw-r-- 1 geek geek 116755 Jul 21 09:21 /tmp/log.140721
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.