In Perl and shell scripts this character is used to quote whatever comes from the standard output of the command enclosed in the quotes. Perhaps this will be clearer with an example:
echo `wc -w foo.txt`
wc -w foo.txt counts the number of words in foo.txt and spits that number out on stdout. By quoting this command in backticks, whatever is on stdout ends up where the quoted expression is. So if the wc command spits out 50, presumably because there are 50 words in foo.txt, the command has the same effect as writing:
This works with any commands that can be run from the shell, or in Perl it can be used as the argument to a function or part of an expression. It works in concert with pipes, as pipes redirect stdout to stdin, whereas backticks convert stdout to command run-time arguments.
A good use I have found is when you want to do a recursive grep but just for certain file types, for instance if I was looking for all uses of some function in the source tree. Lets say I'm looking for all the uses of foo()
in Java files. You can try grep -r foo *.java
, but since none of the directories match *.java you won't actually recurse. If only you had a list of all the Java files. Fortunately, you do; you can get it by typing find . -name *.java
. With that in hand, you can do the job by using grep foo `find . -name *.java`
Is there an easier way to do this?
Another use for backticks is in (common) Lisp, as a useful variation on the ordinary ' quote character. The way quote works is that it prevents the expression following it from being evaluated. Examples:
'foo means the symbol foo, not a variable called foo.
'(a b c) means "the list of symbols a b and c", not "call the function called a with two arguments, the values of the variables b and c".
' applies to the whole expression, so '(1 2 (* 1 3)) means a list of two numbers and a list, the internal list containing the symbol * and two more numbers.
Quoting also stops once the expression ends, so in (append '(1 2 3) (* 2 2)), (* 2 2) is still evaluated to give the value 4.
Backtick works just like ' in the absence of commas, so '(1 2 3) = `(1 2 3) (or in lisp style, (equal '(1 2 3) `(1 2 3))).
However, if a comma is used inside a backticked expression, the subexpression that follows the comma returns to being evaluated. For example `(1 2 3 ,(* 2 2)) is the same as '(1 2 3 4). ,@ can also be used, and works such that when given a list argument, it inserts the contents of that list into its place rather than the list itself, for example `(1 2 ,@'(3 4)) is equivalent to '(1 2 3 4), whereas `(1 2 ,'(3 4)) is '(1 2 (3 4)).
While the purpose of this might not be apparent at first, it turns out to be useful in Lisp macros, as it allows one to control the order of evaluation.