What is the benefit of using $() instead of backticks in shell scripts?

DVK picture DVK · Feb 26, 2012 · Viewed 73.7k times · Source

There are two ways to capture the output of command line in bash:

  1. Legacy Bourne shell backticks ``:

    var=`command`
    
  2. $() syntax (which as far as I know is Bash specific, or at least not supported by non-POSIX old shells like original Bourne)

    var=$(command)
    

Is there any benefit to using the second syntax compared to backticks? Or are the two fully 100% equivalent?

Answer

paxdiablo picture paxdiablo · Feb 26, 2012

The major one is the ability to nest them, commands within commands, without losing your sanity trying to figure out if some form of escaping will work on the backticks.

An example, though somewhat contrived:

deps=$(find /dir -name $(ls -1tr 201112[0-9][0-9]*.txt | tail -1l) -print)

which will give you a list of all files in the /dir directory tree which have the same name as the earliest dated text file from December 2011 (a).

Another example would be something like getting the name (not the full path) of the parent directory:

pax> cd /home/pax/xyzzy/plugh
pax> parent=$(basename $(dirname $PWD))
pax> echo $parent
xyzzy

(a) Now that specific command may not actually work, I haven't tested the functionality. So, if you vote me down for it, you've lost sight of the intent :-) It's meant just as an illustration as to how you can nest, not as a bug-free production-ready snippet.