开发者

Is it possible for bash commands to continue before the result of the previous command?

开发者 https://www.devze.com 2022-12-22 00:38 出处:网络
When running commands from a bash script, does bash always wait for the previous command to complete, or does it just s开发者_StackOverflow社区tart the command then go on to the next one?

When running commands from a bash script, does bash always wait for the previous command to complete, or does it just s开发者_StackOverflow社区tart the command then go on to the next one?

ie: If you run the following two commands from a bash script is it possible for things to fail?

cp /tmp/a /tmp/b
cp /tmp/b /tmp/c


Yes, if you do nothing else then commands in a bash script are serialized. You can tell bash to run a bunch of commands in parallel, and then wait for them all to finish, but doing something like this:

command1 &
command2 &
command3 &
wait

The ampersands at the end of each of the first three lines tells bash to run the command in the background. The fourth command, wait, tells bash to wait until all the child processes have exited.

Note that if you do things this way, you'll be unable to get the exit status of the child commands (and set -e won't work), so you won't be able to tell whether they succeeded or failed in the usual way.

The bash manual has more information (search for wait, about two-thirds of the way down).


add '&' at the end of a command to run it parallel. However, it is strange because in your case the second command depends on the final result of the first one. Either use sequential commands or copy to b and c from a like this:

cp /tmp/a /tmp/b &
cp /tmp/a /tmp/c &


Unless you explicitly tell bash to start a process in the background, it will wait until the process exits. So if you write this:

foo args &

bash will continue without waiting for foo to exit. But if you don't explicitly put the process in the background, bash will wait for it to exit.

Technically, a process can effectively put itself in the background by forking a child and then exiting. But since that technique is used primarily by long-lived processes, this shouldn't affect you.


In general, unless explicitly sent to the background or forking themselves off as a daemon, commands in a shell script are serialized.


They wait until the previous one is finished. However, you can write 2 scripts and run them in separate processes, so they can be executed simultaneously. It's a wild guess, really, but I think you'll get an access error if a process tries to write in a file that's being read by another process.


I think what you want is the concept of a subshell. Here's one reference I just googled: http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/subshells.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号