title: Bash: file descriptors
body: <p>I am a Bash beginner but I am trying to learn this tool to have a job in computers one of these days.</p>
  
  <p>I am trying to teach myself about file descriptors now. Let me share some of my experiments:</p>
  
  <hr>
  
  <pre><code>#!/bin/bash
  
  # Some dummy multi-line content
  read -d '' colours &lt;&lt;- 'EOF'
          red
          green
          blue
  EOF
  
  # File descriptor 3 produces colours
  exec 3&lt; &lt;(echo "$colours")
  
  # File descriptor 4 filters colours
  exec 4&gt; &gt;(grep --color=never green)
  
  # File descriptor 5 is an unlimited supply of violet
  exec 5&lt; &lt;(yes violet)
  
  echo Reading colours from file descriptor 3...
  cat &lt;&amp;3
  echo ... done.
  
  echo Reading colours from file descriptor 3 again...
  cat &lt;&amp;3
  echo ... done.
  
  echo Filtering colours through file descriptor 4...
  echo "$colours" &gt;&amp;4
  echo ... done. # Race condition?
  
  echo Dipping into some violet...
  head &lt;&amp;5
  echo ... done.
  
  echo Dipping into some more violet...
  head &lt;&amp;5
  echo ... done.
  </code></pre>
  
  <hr>
  
  <p>Some questions spring to mind as I see the output coming from the above:</p>
  
  <ol>
  <li>fd3 seems to get "depleted" after "consumption", is it also automatically closed after first use?</li>
  <li>how is fd3 different from a named pipe? (something I have looked at already)</li>
  <li>when <em>exactly</em> does the command <code>yes</code> start executing? upon fd declaration? later?</li>
  <li>does <code>yes</code> stop (<code>CTRL-Z</code> or other) and restart when more violet is needed?</li>
  <li>how can I get the PID of <code>yes</code>?</li>
  <li>can I get a list of "active" fds?</li>
  <li>very interesting race condition on filtering through fd4, can it be avoided?</li>
  <li>will <code>yes</code> only stop when I <code>exec 5&gt;&amp;-</code>?</li>
  <li>does it matter whether I close with <code>&gt;&amp;-</code> or <code>&lt;&amp;-</code>?</li>
  </ol>
  
  <p>I'll stop here, for now.</p>
  
  <p>Thanks!</p>
  
  <p>PS: partial (numbered) answers are fine.. I'll put together the different bits and pieces myself.. (although a comprehensive answer from a single person would be impressive!)</p>