How do I run multiple background commands in bash

2019-01-12 21:41发布

问题:

I normally run multiple commands with something like this:

sleep 2 && sleep 3

or

sleep 2 ; sleep 3

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

sleep 2 & && sleep 3 &

doesn't work. And neither does replacing && with ;

Is there a way to do it?

回答1:

Exactly how do you want them to run? If you want them to be started 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 instead do this:

sleep 2 & sleep 3 &

And the two techniques could be combined, such as:

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

Bash being bash, there's often a multitude of different techniques to accomplish the same task, although sometimes with subtle differences between them.



回答2:

You need to add some parens in your last version --

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

or this also works --

(sleep 2 &) ; (sleep 3 &)


回答3:

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



回答4:

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

{ sleep 2 && sleep 3; } &

Note that the braces are more picky about syntax--the space after {, the space before }, and the final semicolon are required. In some situations the braces are more efficient because they don't fork a new subshell. In this case I don't know if it makes a difference.



回答5:

This works:

$(sleep 2 &) && sleep 3 &

Also you can do:

$(sleep 2 && sleep 3) &


回答6:

I have the same mission too. I have try (sleep2 ; fg )& sleep3 ; fg,it's working. And when you preass ctrl+c doubled,the two process can be stoppped.



回答7:

If you want to run multiple commands sequentially, there is a really simple method that works everywhere: Creating a file! The benefit of this method is that it's clean and simple.

First, create your file with a name, e.g. commands.sh. Then, put your commands there. Here's is a sample:

commands.sh:

#!/system/bin/sh

sleep 3;
sleep 2;

OK, now we're in the last step. To run commands in the background (sequentially), just run:

$ sh commands.sh &


标签: linux bash shell