title: Bash script that check connection with host:port using telnet and netcar
body: <p>I have task to create quite complicated bash script, which at first part is checking the connection to host:port with telnet and- if telnet would fail or would not be installed, try the connection using netcat.</p>
  <p>I have problem with loop, where it will skip netcat if telnet would connect to the host and also, if both- telnet and netcat would fail- script would finish with error message.
  The script:</p>
  <pre><code>#!/bin/bash
  echo Type host IP address
  read REMOTEHOST
  echo Type port number
  read REMOTEPORT
  TIMEOUT=5
  
  echo quit | timeout --signal=9 5 telnet $REMOTEHOST $REMOTEPORT
  
  
  if nc -w $TIMEOUT -z $REMOTEHOST $REMOTEPORT; then
      echo &quot;I was able to connect to ${REMOTEHOST}:${REMOTEPORT}&quot;
  else
      echo &quot;Connection to ${REMOTEHOST}:${REMOTEPORT} failed. Exit code from Netcat was ($?).&quot;
  fi
  </code></pre>