How to run multiple background commands in bash on the same line?

I usually run a few commands with something like this:

sleep 2 && sleep 3 

or

 sleep 2 ; sleep 3 

but what if I want to run them in the background from one command line command?

 sleep 2 & && sleep 3 & 

does not work. And does not replace && with ;

Is there any way to do this?

+80
linux bash shell
Jan 30 '13 at 19:45
source share
6 answers

How do you want them to run? If you want them to start in the background and run sequentially, you would do something like this:

 (sleep 2; sleep 3) & 

If, on the other hand, you would like them to run in parallel in the background, you can do this:

 sleep 2 & sleep 3 & 

And these two methods can be combined, for example:

 (sleep 2; echo first finished) & (sleep 3; echo second finished) & 

Bash bash, often there are many different methods for performing the same task, although sometimes with slight differences between them.

+134
Jan 30 '13 at 20:00
source share

You need to add several partners to your latest version -

 (sleep 2 &) && (sleep 3 &) 

or it also works -

 (sleep 2 &) ; (sleep 3 &) 
+33
Jan 30 '13 at 19:49
source share

to run multiple background commands you need to add & end of each command. for example: (command1 &) && (command2 &) && (command3 &)

+6
Jan 31 '13 at 12:05
source share

The answers above use parentheses. Bash can also use curly braces for a similar purpose:

 { sleep 2 && sleep 3; } & 

Note that curly braces are more legible in syntax - a space after { , a space before } and an end semicolon. In some situations, parentheses are more effective because they do not fork a new subshell. In this case, I do not know if this matters.

+4
Oct 30 '14 at 16:29
source share

It works:

 $(sleep 2 &) && sleep 3 & 

You can also do:

 $(sleep 2 && sleep 3) & 
+3
Jan 30 '13 at 19:48
source share

I also have the same mission. I tried (sleep2 ; fg )& sleep3 ; fg (sleep2 ; fg )& sleep3 ; fg , it works. And when you chase ctrl + c twice, two processes can be stopped.

0
03 Oct '16 at 9:40
source share



All Articles