2

I've come across a script being run as (myDir/myScript.sh arg1 arg2 &)

From my understanding, it's running the script in a subshell and also in the background of that sub-shell.

Will there be any side-effects if I ran the script myDir/myScript.sh arg1 arg2 & without the parenthesis that create the new subshell?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • This is the shell equivalent of a double-fork. See https://stackoverflow.com/questions/881388/what-is-the-reason-for-performing-a-double-fork-when-creating-a-daemon – that other guy Oct 18 '17 at 00:06

1 Answers1

5

The usual reason for running it in a subshell is so that shell doesn't print a message when the background process starts and finishes.

Also, if the script ever uses the wait command, it won't wait for background processes started in subshells (a process can only wait for its own children, not grandchildren).

This also means that the script can't get the exit status of the background process if it's started in a subshell -- you need to use wait to get that. And the $! variable won't be set to the PID of the background process (it's set inside the subshell, not the original shell process).

Basically, you use (command&) if the original shell has no need to deal with the background process, it just wants to start it and forget about it.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I thought the ampersand forks a new process in the background, but how is that different from a subshell? – avaldez1412 Oct 17 '17 at 21:42
  • Every non-built-in command forks a new process. Ampersand makes that process run in the background, which means the original shell continues without waiting for it to finish. – Barmar Oct 17 '17 at 21:44
  • `()` forks a new shell process, then that subshell forks a new process, either foreground or background depending on whether there's `&`. – Barmar Oct 17 '17 at 21:45
  • Thanks. So I have a follow up question. How do I get the exit status of the script? Since it's running the background of a subshell, then the script should return the exit status to the foreground of the subshell and after that pipe it to the parent shell. Is that correct? – avaldez1412 Oct 17 '17 at 21:55
  • You can't get the exit status easily. The subshell exits immediately with zero status, and that's the exit status the original shell gets. – Barmar Oct 18 '17 at 15:51