title: Automatically (or more easily) reconnect to a screen session after network interruption
body: <p>ADDED: This question is now, I believe, subsumed by this one:
    <a href="https://stackoverflow.com/questions/1075947/can-i-use-gnu-screen">Using GNU Screen completely transparently and automatically</a></p>
  
  <p>See also this related question:<br>
  <a href="https://superuser.com/questions/147873/ssh-sessions-in-xterms-freeze-for-many-minutes-whenever-they-disconnect">https://superuser.com/questions/147873/ssh-sessions-in-xterms-freeze-for-many-minutes-whenever-they-disconnect</a></p>
  
  <p>Original question:</p>
  
  <p>It would be nice if there were a way to ssh to a machine and immediately reconnect to a specific screen session.  You can do this:</p>
  
  <pre><code>laptop&gt; ssh server.com screen -ls
  </code></pre>
  
  <p>and it will show a list of screens available on server.com like so [1]:</p>
  
  <pre><code>123.pts-1
  456.pts-2
  </code></pre>
  
  <p>And then you might try to do this:</p>
  
  <pre><code>laptop&gt; ssh server.com screen -dr pts-2
  </code></pre>
  
  <p>but that fails, saying "Must be connected to a terminal."
  You have to ssh in first and then do the "screen -dr pts-2" on server.com which is no good if you have a flaky connection and get disconnected a lot. You want to be able to resume with a simple "up-arrow enter" on the laptop.  (Or perhaps make it even more automatic.)</p>
  
  <p>I have a rihackulous solution to this problem which I'll post as an answer and hope it gets downvoted to oblivion in favor of the Right Way to deal with this.</p>
  
  <p><hr> 
  Footnotes:</p>
  
  <p>[1] Or, better, if you created the screen sessions with names like "<code>screen -S foo</code>" and "<code>screen -S bar</code>" then you'll get a friendlier list like:</p>
  
  <pre><code>123.foo
  456.bar
  </code></pre>
  
  <p>and can reconnect with, eg, "<code>screen -dr foo</code>".</p>
  
  <hr>
  
  <h2>Mini screen tutorial, incorporating the answer to this question:</h2>
  
  <p>Login in to server.com and do </p>
  
  <pre><code>screen -S foo 
  </code></pre>
  
  <p>and then never log out of that session again.
  To reconnect to it from elsewhere, do</p>
  
  <pre><code>ssh -t server.com screen -dr foo
  </code></pre>
  
  <p>To list available screens to reconect to:</p>
  
  <pre><code>screen -ls
  </code></pre>
  
  <p>or, of course, </p>
  
  <pre><code>ssh server.com screen -ls
  </code></pre>
  
  <p>to check on server.com's available screens remotely.</p>
  
  <p>I now use the following alias (tcsh), based on Jason's answer below, to connect to a named screen if it exists or create and connect otherwise:</p>
  
  <pre><code>alias ssc 'ssh -t \!:1 "screen -S \!:2 -dr || screen -S \!:2"'
  </code></pre>