Difference between $() and () in Bash

run4gnu picture run4gnu · Aug 23, 2016 · Viewed 10.2k times · Source

When I type ls -l $(echo file) output from bracket (which is just simple echo'ing) is taken and passed to external ls -l command. It equals to simple ls -l file.

When I type ls -l (echo file) we have error because one cannot nest () inside external command.

Can someone help me understand the difference between $() and () ?

Answer

Barry Scott picture Barry Scott · Aug 23, 2016

$(cmd) substitutes the result of cmd as a string, whereas (cmd; cmd) run a list of commands in a subprocess.

If you want to put the output of one or more commands into a variable use the $( cmd ) form.

However if you want to run a number of commands and treat them as a single unit use the () form.

The latter is useful when you want to run a set of commands in the background:

(git pull; make clean; make all) &