title: How can I save and restore TTY settings from a subshell? (Or: understanding pty/tty within subshells)
body: <p>I am trying to understand <code>stty</code>'s operation within a subshell.  Here is a small Ruby script I am working with to wrap my head around the behavior.  I'm just trying to save and restore the <code>tty</code> state after we exit an infinite loop via <code>^C</code>.</p>
  
  <pre class="lang-rb prettyprint-override"><code>original_tty = `stty -f /dev/tty -g`
  begin
    loop do end
  rescue Interrupt
    # Suppress exception
  ensure
    $stderr.puts `stty -f /dev/tty #{original_tty}`
    $stderr.puts "stty exits with: #{$?}, i.e. success == #{$?.success?}"
  end
  </code></pre>
  
  <p>Now, if you put this into a file <code>wut.rb</code>, when I run it at my command line with <code>bash -c 'echo | ruby wut.rb</code> it works; <em>i.e.</em> <code>stty</code> returns <code>0</code>.  But if I run it in a subshell <em>via</em> command substitution, <code>bash -c 'echo $(echo | ruby wut.rb)'</code>, it does not; <em>i.e.</em> <code>stty</code> returns <code>1</code>.</p>
  
  <p>Running these directly from the command line works as I might expect:</p>
  
  <pre><code>$ foo=$(stty -f /dev/tty -g)
  $ echo $foo
  gfmt1:cflag=4b00:iflag=6b02:lflag=200005cf:oflag=3:discard=f:dsusp=19:eof=4:eol=ff:eol2=ff:erase=7f:intr=3:kill=15:lnext=16:min=1:quit=1c:reprint=12:start=11:status=14:stop=13:susp=1a:time=0:werase=17:ispeed=38400:ospeed=38400
  $ echo | stty -f /dev/tty $foo
  $ echo $?
  0
  $ echo $(echo | stty -f /dev/tty $foo)
  
  $ echo $?
  0
  </code></pre>
  
  <p>I'm on Mac OS X 10.10.2 using <code>bash 3.2</code> and <code>ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]</code> if it matters…</p>
  
  <hr>
  
  <p>Why is this?  I think it has to do with the subshell created by command substitution not being/having a <code>tty</code>, but I'm not sure. I would very much appreciate:</p>
  
  <ul>
  <li>any explanation of what's going on (including good readings on PTY/TTY—so far <a href="https://blog.nelhage.com/2009/12/a-brief-introduction-to-termios/" rel="nofollow">"A Brief Introduction to Termios"</a> and <a href="http://www.linusakesson.net/programming/tty/" rel="nofollow">"The TTY demystified"</a> have been the most helpful)</li>
  <li>and suggestions as to how I might successfully restore the original <code>tty</code> settings within a command substitution.</li>
  </ul>
  
  <p>Thanks!</p>