Linux – question on linux command


What do the two ampersands in the following command do:

(make foo&)&

Best Solution

The ( and ) run the command in a subshell. This means that a separate shell is spawned off and the command is run. This is probably because they wanted to use shell specific operation (backgrounding - other examples are redirection etc.). The first & in the command backgrounds the command run in the subshell (ie. make foo). The second ampersand backgrounds the subshell itself so that you get back your command prompt immediately.

You can see the effects here

Foreground on the current shell

(bb-python2.6)noufal@NibrahimT61% ls # shell waits for process to complete
a  b  c  d  e

Background on the current shell

(bb-python2.6)noufal@NibrahimT61% ls& #Shell returns immediately.
[1] 3801
a  b  c  d  e
[1]  + done       /bin/ls -h -p --color=auto -X

Using a subshell (Foreground)

(bb-python2.6)noufal@NibrahimT61% (ls&) # Current shell waits for subshell to finish.
a  b  c  d  e                           

In this case, the current shell waits for the subshell to finish even though the job in the subshell itself is backgrounded.

Using a subshell (BAckground)

(bb-python2.6)-130- noufal@NibrahimT61% (ls &)&
[1] 3829
a  b  c  d  e
[1]  + exit 130   (; /bin/ls -h -p --color=auto -X &; )

The foreground shell returns immediately (Doesn't wait for the subshell which itself doesn't wait for the ls to finish). Observe the difference the command executed.

A sidenote on the need to run some commands in a subshell. Suppose you wanted to run a "shell command" (ie. One that uses shell specific stuff like redirects, job ids etc.), you'd have to either run that command in a subshell (using (, )) or using the -c option to shells like bash. You can't just directly exec such things because the shell is necessary to process the job id or whatever. Ampersanding that will have the subshell return immediately. The second ampersand in your code looks (like the other answer suggests) redundant. A case of "make sure that it's backgrounded".