Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $() and () in Bash

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 () ?

like image 402
run4gnu Avatar asked Aug 23 '16 20:08

run4gnu


People also ask

What does $() mean in bash?

Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

What is the difference between $() and ${}?

$() means: "first evaluate this, and then evaluate the rest of the line". On the other hand ${} expands a variable.

What is the difference between [] and in bash?

The difference is that word splitting and glob expansion are not performed for variables inside [[...]] so quoting the variables is not so crucial. Additionally, [[ can do pattern matching with the == operator and regular expression matching with the =~ operator.

What is the difference between == and =~ in bash?

The binary operator, '=~', has the same precedence as '==' and '!= '. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex3)). The return value is 0 if the string matches the pattern, and 1 otherwise.


1 Answers

$(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) &
like image 96
Barry Scott Avatar answered Sep 21 '22 15:09

Barry Scott