title: Auto exit Telnet command back to prompt without human intervention ^] quit close exit code 1
body: <p>I'm running <code>telnet</code> command on a host for a given port (which is open), it returns 0 (success). </p>
  
  <p>For trying telnet manually, I type the following command, then I press control+bracket i.e. <code>^]</code>, then press <code>Enter</code> key, then I get to <code>telnet&gt;</code> prompt, where if I type <code>close</code> or <code>quit</code>, it comes back to the <code>$</code> prompt and seeing exit status of last command shows <code>0</code> for (success) as port 2878 is open (as per the telnet command's output).</p>
  
  <pre><code>[vagrant@myvagrant /tmp] $ telnet `hostname` 2878
  Trying 127.0.0.1...
  Connected to myvagrant.
  Escape character is '^]'.
  ^]
  
  telnet&gt; close
  Connection closed.
  [vagrant@myvagrant /tmp] $ echo $?
  0
  </code></pre>
  
  <p>Now, I wanted to run the same operation without any human intervention i.e.  I don't want to manually give <code>^]</code> and press <code>Enter</code> key to come to the <code>telnet&gt;</code> prompt, then enter <code>close</code> (or <code>quit</code>) telnet command to finally come back to the <code>$</code> prompt. </p>
  
  <p>For this, I tried using <code>echo -e</code> command's option and giving <code>^]</code>, <code>\n</code> (for new line character i.e. <code>Enter</code> key) and <code>close</code> command (for <code>telnet&gt;</code> prompt so that I come back to <code>$</code> prompt). Doing this, kind of worked as expected but for the exit status of last command <code>echo $?</code>, I'm getting <code>1</code> (instead of <strong>0</strong>). <strong>Why?</strong> </p>
  
  <pre><code>[vagrant@myvagrant /tmp] $ echo -e "^]\nclose" | telnet `hostname` 2878
  Trying 127.0.0.1...
  Connected to myvagrant.
  Escape character is '^]'.
  Connection closed by foreign host.
  [vagrant@myvagrant /tmp] $ 
  [vagrant@myvagrant /tmp] $ echo $?
  1
  [vagrant@myvagrant /tmp] $ 
  </code></pre>
  
  <p><strong>or</strong> tried the here-doc method as well, but not sure why it's returning <code>1</code> (as exit code) for a valid port which is open.</p>
  
  <pre><code>[vagrant@myvagrant /tmp] $ telnet `hostname` 2878 &lt;&lt;GIGA
  &gt; echo ^]
  &gt; echo close
  &gt; GIGA
  Trying 127.0.0.1...
  Connected to myvagrant.
  Escape character is '^]'.
  Connection closed by foreign host.
  [vagrant@myvagrant ~/aks/always-latest-ws-sunny] $ echo $?
  1
  [vagrant@myvagrant ~/aks/always-latest-ws-sunny] $
  </code></pre>
  
  <p>How can I automatically exit from telnet if the port is open and get <code>0</code> as exit code? If there's a way to capture the output of the previous command, may be I can grep the '<em>Connection closed by foreign host.</em>' string to mark it successful (0).</p>