36

How can one run multiple programs in the background with single command?

I have tried the commands below, but they do not work.

nohup ./script1.sh & && nohup ./script2.sh &
-bash: syntax error near unexpected token '&&'

nohup ./script1.sh & ; nohup ./script2.sh &
-bash: syntax error near unexpected token ';'
Eli Heady
  • 1,234
Rahul Patil
  • 24,711

3 Answers3

32

From a shell syntax point of view, & separates commands like ;/|/&&... (though of course with different semantic). So it's just:

cmd1 & cmd2 & cmd3 &
  • 1
    this is not /quite/ right, ; starts the next command as soon as the first one ended. & actually puts the command to the background.

    just try this: echo foo & echo bar & echo test &

    – Oluf Lorenzen Mar 06 '13 at 10:08
  • 1
    @Finkregh, of course. Nobody doubts that. I just meant they both separate commands (from a syntax point of view) with no implications on how they are run. – Stéphane Chazelas Mar 06 '13 at 10:57
  • 1
    It's not quite what was asked, since the question specified issuing a "single command". Neither is my answer, as it too is a series of commands, but it has at least one semantic of a single command in that output is concatenated, can be redirected, etc. – Eli Heady Mar 07 '13 at 00:57
  • "Multiple commands with a single command" seems to be an oxymoron, though - what does that mean? If this is for something like sudo so you could enter the password only once, wrap then in bash -c or similar. – Richlv Jan 23 '18 at 13:10
12

The bash manpage section titled Compound Commands has two options that would work, list and group commands.

A group command is a series of commands enclosed in curly braces {}. A list is the same, enclosed in parentheses (). Both can be used to background multiple commands within, and finally to background the entire collection as a set. The list construct executes commands in a subshell, so variable assignments are not preserved.

To execute a group of commands:

{ command1 & command2 & } &

You can also execute your commands in a list (subshell):

( command1 & command2 ) &
Eli Heady
  • 1,234
  • 1
    You're welcome. I added the link to the manual. Note that the list () syntax executes the enclosed commands in a subshell, so variables are not preserved within. – Eli Heady Mar 06 '13 at 05:55
3

another way:

$(command1 &) && command2 & 
PersianGulf
  • 10,850