title: Bash script processing limited number of commands in parallel
body: <p>I have a bash script that looks like this:</p>
  
  <pre><code>#!/bin/bash
  wget LINK1 &gt;/dev/null 2&gt;&amp;1
  wget LINK2 &gt;/dev/null 2&gt;&amp;1
  wget LINK3 &gt;/dev/null 2&gt;&amp;1
  wget LINK4 &gt;/dev/null 2&gt;&amp;1
  # ..
  # ..
  wget LINK4000 &gt;/dev/null 2&gt;&amp;1
  </code></pre>
  
  <p>But processing each line until the command is finished then moving to the next one is very time consuming, I want to process for instance 20 lines at once then when they're finished another 20 lines are processed.</p>
  
  <p>I thought of <code>wget LINK1 &gt;/dev/null 2&gt;&amp;1 &amp;</code> to send the command to the background and carry on, but there are 4000 lines here this means I will have performance issues, not to mention being limited in how many processes I should start at the same time so this is not a good idea.</p>
  
  <p>One solution that I'm thinking of right now is checking whether one of the commands is still running or not, for instance after 20 lines I can add this loop:</p>
  
  <pre><code>while [  $(ps -ef | grep KEYWORD | grep -v grep | wc -l) -gt 0 ]; do
  sleep 1
  done
  </code></pre>
  
  <p>Of course in this case I will need to append &amp; to the end of the line! But I'm feeling this is not the right way to do it.</p>
  
  <p>So how do I actually group each 20 lines together and wait for them to finish before going to the next 20 lines, this script is dynamically generated so I can do whatever math I want on it while it's being generated, but it DOES NOT have to use wget, it was just an example so any solution that is wget specific is not gonna do me any good.</p>