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

后端 未结 6 1356
心在旅途
心在旅途 2020-11-27 16:39

When running commands from a bash script, does bash always wait for the previous command to complete, or does it just start the command then go on to the next one?

i

相关标签:
6条回答
  • 2020-11-27 16:52

    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.

    0 讨论(0)
  • 2020-11-27 16:55

    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 &
    
    0 讨论(0)
  • 2020-11-27 17:00

    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.

    0 讨论(0)
  • 2020-11-27 17:11

    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 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-11-27 17:15

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

    0 讨论(0)
提交回复
热议问题