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

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.

Leave a Comment