Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for bash background jobs in script to be finished

To maximize CPU usage (I run things on a Debian Lenny in EC2) I have a simple script to launch jobs in parallel:

#!/bin/bash  for i in apache-200901*.log; do echo "Processing $i ..."; do_something_important; done & for i in apache-200902*.log; do echo "Processing $i ..."; do_something_important; done & for i in apache-200903*.log; do echo "Processing $i ..."; do_something_important; done & for i in apache-200904*.log; do echo "Processing $i ..."; do_something_important; done & ... 

I'm quite satisfied with this working solution, however I couldn't figure out how to write further code which only executed once all of the loops have been completed.

Is there a way to get control of this?

like image 369
mark Avatar asked Jul 15 '09 13:07

mark


People also ask

How do I make bash script wait?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

How do you wait for a process to finish in Linux?

wait command will suspend execution of the calling thread until one of its children terminate. It will return the exit status of that command. The sleep command is used to delay the execution of the next command for a given number of seconds, hours, minutes, days. kill is used to terminate a background running process.

Does bash script run in background?

If you want to push a command into the background, using & at the end is an easy way to do that. This way, you can issue a command in the background and continue to use your terminal as it runs. It comes with a catch, though. Using & doesn't disconnect the command away from you; it just pushes it into the background.


1 Answers

There's a bash builtin command for that.

wait [n ...]       Wait for each specified process and return its termination  sta‐       tus.   Each  n  may be a process ID or a job specification; if a       job spec is given, all processes  in  that  job’s  pipeline  are       waited  for.  If n is not given, all currently active child pro‐       cesses are waited for, and the return  status  is  zero.   If  n       specifies  a  non-existent  process or job, the return status is       127.  Otherwise, the return status is the  exit  status  of  the       last process or job waited for. 
like image 67
eduffy Avatar answered Sep 20 '22 07:09

eduffy