title: Bash run a function in background
body: <p>Have a relatively simple question here. I need to run a function in the background in bash. Normally I would do it just like so:</p>
  
  <pre><code>FUNCTION &amp;
  </code></pre>
  
  <p>but things are a bit more complicated than that. I have the following line that runs the main function for each record in a text database. I cant really edit this code all that much without vastly changing the rest of the entire project, but im still open to new ideas.</p>
  
  <pre><code>cat databases/$WAN | grep -v \# | while read LINE; do MAIN; done
  </code></pre>
  
  <p>I want to spawn a new terminal in background for each record to do a sort of parallel type processing, making things go much faster. Main takes a minute to process for each record. This however does not work.</p>
  
  <pre><code>cat databases/$WAN | grep -v \# | while read LINE; do MAIN &amp;; done
  </code></pre>
  
  <p>Any suggestions?</p>
  
  <p><strong>* UPDATE *</strong></p>
  
  <p>Thanks for all the responses. Let me see if I can answer some of those questions. </p>
  
  <p>gniourf_gniourf - Yes I know using cat like this is wrong. This was early on, and critical code, so I have not updated it yet. I now read into the while loop for most things I do. I will fix it eventually. You may be right about syntax. When I break it up like so, things seem to work now:</p>
  
  <pre><code>  cat databases/$WAN | grep -v \# | while read LINE
    do
      MAIN &amp; &gt; /dev/null 2&gt;&amp;1
    done
  </code></pre>
  
  <p>So that fixes the background problem. I wonder what was messed up in my single line syntax. Thanks</p>
  
  <p>chepner - I don't believe LINE is a variable. I could be wrong though. Some things about Bash still confuse me. Maybe it is and is a variable that the entire record from the database gets stored to prior to processing.</p>
  
  <p>Bruce K - Waiting is exactly what I was trying to avoid. If I let it run in the same terminal one at a time, it will slowly process each record in order. If I push each record to a seperate terminal for processing, all records will be processed simultaneously (at least in our eyes). The additional overhead is intentional in order to speed up how quickly the loop through the database occurs.</p>
  
  <p>Radix - Yes you're right. I'll read up on that. Thanks for the link.</p>