Search code examples
bashbackgroundwait

Is there a difference between "background(&) and wait" and simply execute the normal command in bash?


In bash scripts, I have seen codes like this

command &
wait

I am wondering what is there any motivation behind this operation rather than simply run

command

instead.

The motivation of this question comes from this post: bash wait for rsync to finish for proceeding, where the poster chose to use the "wait" method while an unaccepted answer suggests the normal command method.

Although based on my understanding the answer to that post should be correct, I have also seen various other places (including companies and personal projects) where the "background and wait" method is used in practice, so I am getting a bit confused.

Is there any situation where the two codes actually have a difference?


Solution

  • Consider the script

    trap 'echo bye' SIGINT
    sleep 20
    

    If SIGINT is sent to your script while sleep is running, the trap will not execute (and the script will not exit) until sleep exits.

    Now consider

    trap 'echo bye' SIGINT
    sleep 20 &
    wait
    

    Now, it's not sleep that's blocking the script, but it's own built-in wait command. If SIGINT is sent to your script, the trap will execute and your script will exit immediately.