35

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 ';'
31

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 6 '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 6 '13 at 10:57
  • 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 7 '13 at 0: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 ) &
  • 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 6 '13 at 5:55
2

another way:

$(command1 &) && command2 & 
  • No, it will run first command then after finish first then it will run another command – Rahul Patil Mar 6 '13 at 5:20
  • you used && in your question, it means at first run a command then if run successfuly, run next command.if you don't consider it, you can run command1 & ; command2 & ; – PersianGulf Mar 6 '13 at 5:24
  • first command successfully goes in bg, or run using ; no issue with that – Rahul Patil Mar 6 '13 at 5:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.