title: How to get the correct number of background jobs running, f.ex. $(jobs | wc -l | xargs) returns 1 instead of 0
body: <p>I have a jenkins build job that starts processes in the background. I need to write a function that checks wether there are still background processes running. To test it I came up with this:</p>
  
  <pre><code>#!/bin/bash -e
  
  function waitForUploadFinish() {
    runningJobs=$(jobs | wc -l | xargs)
    echo "Waiting for ${runningJobs} background upload jobs to finish"
  
    while [ "$(jobs | wc -l | xargs)" -ne 0 ];do
      echo "$(jobs | wc -l | xargs)"
      echo -n "."     # no trailing newline
      sleep 1
    done
    echo ""
  }
  
  
  for i in {1..3}
  do
    sleep $i &amp;
  done
  
  waitForUploadFinish
  </code></pre>
  
  <p>The problem is it never comes down to 0. Even when the last <code>sleep</code> is done, there is still one job running?</p>
  
  <pre><code>mles-MBP:ionic mles$ ./jobs.sh 
  Waiting for 3 background upload jobs to finish
  3
  .2
  .1
  .1
  .1
  .1
  .1
  .1
  </code></pre>
  
  <p><strong>Why I don't want to use <code>wait</code> here</strong></p>
  
  <p>In the Jenkins build job script where this snippet is for, i'm starting background upload processes for huge files. They don't run for 3 seconds like in the example here with <code>sleep</code>. They can take up to 30 minutes to proceed. If I use <code>wait</code> here, the user would see something like this in the log:</p>
  
  <pre><code>upload huge_file1.ipa &amp; 
  upload huge_file2.ipa &amp; 
  upload huge_file3.ipa &amp; 
  wait
  </code></pre>
  
  <p>They would wonder why is nothing going on? </p>
  
  <p>Instead I want to implement something like this:</p>
  
  <pre><code>upload huge_file1.ipa &amp; 
  upload huge_file2.ipa &amp; 
  upload huge_file3.ipa &amp; 
  Waiting for 3 background upload jobs to finish
  ............
  Waiting for 2 background upload jobs to finish
  .................
  Waiting for 1 background upload jobs to finish
  .........
  Upload done
  </code></pre>
  
  <p>That's why I need the loop with the current running background jobs.</p>