title: bash script to run a constant number of jobs in the background
body: <p>I need a bash script to run some jobs in the background, three jobs at a time.</p>
  
  <p>I know can do this in the following way, and for illustration, I will assume the number of jobs is 6:</p>
  
  <pre><code>./j1 &amp;
  ./j2 &amp;
  ./j3 &amp;
  wait
  ./j4 &amp;
  ./j5 &amp;
  ./j6 &amp;
  wait
  </code></pre>
  
  <p>However, this way, if, for example, j2 takes a lot longer to run that j1 and j3, then, I will be stuck with only one background job running for a long time. </p>
  
  <p>The alternative (which is what I want) is that whenever one job is completed, bash should start the next job in the queue so that a rate of 3 jobs at any given time is maintained. Is it possible to write a bash script to implement this alternative, possibly using a loop? Please note that I need to run far more jobs, and I expect this alternative method to save me a lot of time.</p>
  
  <p>Here is my draft of the script, which I hope you can help me to verify its correctness and improve it, as I'm new to scripting in bash. The ideas in this script are taken and modified from <a href="https://stackoverflow.com/questions/12472933/loop-background-job">here</a>, <a href="https://stackoverflow.com/questions/1131484/wait-for-bash-background-jobs-in-script-to-be-finished">here</a>, and <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html" rel="nofollow noreferrer">here</a>):</p>
  
  <pre><code>for i in $(seq 6)
  do
     # wait here if the number of jobs is 3 (or more)
     while (( (( $(jobs -p | wc -l) )) &gt;= 3 )) 
     do 
        sleep 5      # check again after 5 seconds
     done
  
     jobs -x ./j$i &amp;
  done
  wait
  </code></pre>
  
  <p>IMHO, I think this script does the required behavior. However, I need to know -from bash experts- if I'm doing something wrong or if there is a better way of implementing this idea.</p>
  
  <p>Thank you very much. </p>