Below is a sample snippet, normally it works fine unless we passes some command which shutdown the server or cause a disconnection .

To handle this, is it possible to expect either "#" or eof after sending the cmd .

  send "${_cmd_}\r"
     expect "#"
      send "exit\r"
  • 1
    take a look at sexpect with which you can write Expect scripts with shell code only.
    – UNIX.root
    Aug 15, 2018 at 2:26

1 Answer 1


Sure, if the connection closes, expect will react to the special pattern eof. What you want to do is this

  • if the connection is closed, expect eof
  • if you see the prompt, send the exit command, then continue to wait for eof
send "$_cmd_\r"
expect {
    "#" {
        send "exit\r"
# do something after the connection is closed

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .