title: How to pass an awk variable to a bash command
body: <p>How can I pass an <code>awk</code> variable to a <code>bash</code> command run within <code>awk</code>?</p>
  
  <p>I'm using awk to calculate a running sum of threads for each of a certain process, but then I want to use each pid to access the <code>/proc/$pid</code> filesystem.</p>
  
  <p>The line marked <strong>broken</strong> below is incorrect, because <code>$pid</code> is non-existent.</p>
  
  <p>How can I export the awk variable <code>pid</code> to the shell command I get <code>awk</code> to run?</p>
  
  <p><em>(Line breaks added for readability)</em></p>
  
  <pre><code>$ ps -ALf | grep $PROC | grep -v grep | \         # get each pid
      awk '{threads[$2]+=1} END \                   # count num threads per pid
           { \
             for (pid in threads) \
                "cat /proc/$pid/cwd"|getline cwd; \ # get 'cwd' (**broken**)
                 print cwd ": " threads[pid] \      # display 'cwd' and num threads
           }'
  </code></pre>