Linux shell script asynchronous commands and notification on completion

I have a script that updates a web application. The web application is distributed on 2 servers. Here is a summary of the script

  • The shell script updates the git repository.
  • The shell script stops the application server.
  • The shell script stops the web server.
  • The shell script informs the application server of the latest git update.
  • The shell script tells the web server to check for the latest git update.
  • The shell script starts the application server.
  • The shell script starts the web server.

Each of the 7 steps is performed synchronously one after the other. Total run time is about 9 seconds. However, to reduce downtime, many of these steps can be performed asynchronously.

For example, steps 4 and 5 can be performed simultaneously. I want to start steps 4 and 5 asynchronously (for example, working in the background), but I cannot find how to wait until they both end before moving on.

+4
source share
3 answers

run step 4 and 5 in the background in the script (ending & ), and then just call wait bash builtin before step 6

+5
source

You might want to use a grouping of commands to support which steps should be synchronous:

 step1 ( step2 && step4 && step6 ) & ( step3 && step5 && step7 ) & wait && echo "all done" 
+10
source

You are looking for the wait command.

 wait: wait [id] Wait for job completion and return exit status. Waits for the process identified by ID, which may be a process ID or a job specification, and reports its termination status. If ID is not given, waits for all currently active child processes, and the return status is zero. If ID is aa job specification, waits for all processes in the job pipeline. Exit Status: Returns the status of ID; fails if ID is invalid or an invalid option is given. 
+3
source

All Articles