When should you use the backtick operator?

Tuesday, May 8th, 2007 at 7:17 pm

In Perl, PHP and shell (maybe others as well) the “`” character (informally known as the backtick and formally known as a Grave accent) is used to execute a shell command and return the output as a string.

Perl and PHP have other methods of achieving the same result that are not elements of syntactic sugar. These are less likely to surprise you, as I found today when I noticed that the computer collection section of this site was breaking in a strange way.

For those pages I use PHP to build up the page based on the directory structure and the existence of certain files. The first thing I checked was that the files were actually present. They were.

The next thing to check was the error log and here I found a number of messages telling me that shell executions were disabled. That made sense in relation to a recent change in the security configuration that the hosting people had made, but what was I executing on the shell?

As the error message was nice enough to tell me the specific file and line number I quickly found this call:


This is running pwd in a shell to get the current directory and then using trim() to remove excess whitespace. This is stupid. Especially since the following does exactly the same thing:


This has a crucial difference; it is built into the language, no shell execution (and potential security hole) is required.

To answer the original question: Use backticks to execute a shell command only if, for some bizarre reason, there is nothing built into the language or a module cannot be loaded to achieve the same result.

Tagged with: ,