title: Using Expect how do I exit foreach function after EOF
body: <p>After the following script reads the inventory file and completes the commands from the testcommands file, the foreach function is looking for more information from the inventory file to process and errors rather than ending.</p>
  
  <pre><code>#!/usr/bin/expect
  
  set timeout 5
  
  # Open and read hosts from file
  set fp [open "inventory_2ps"]
  set hosts [split [read $fp]"\n"]
  close $fp
  
  # Get commands to run in server
  set fh [open "testcommands"]
  set commands [split [read $fh] "\n"]
  close $fh
  
  # Set login variable
  set user "xxxxxxx";
  set PW "xxxxxxx";
  
  # Spawn server login
  foreach host $hosts {
  
      spawn ssh $user@$host
      expect "$ "
  
      send "su - xxxxxx\n"
      expect "Password: "
  
      send "$PW\n"
      expect "$ "
  
      send "xxxxxx -nobash\r"
      expect "&gt; "
  
      foreach cmd $commands {
              send "$cmd\n"
              expect "&gt; "
  
              }
      expect eof
  </code></pre>
  
  <p>Receives error after last host login/exit:</p>
  
  <pre><code>&gt;$ spawn ssh xxxxxx@"
  ssh: Could not resolve hostname ": Name or service not known
  send: spawn id exp10 not open
      while executing
  "send "su - xxxxxx\n""
      ("foreach" body line 6)
      invoked from within
  "foreach host $hosts {
  
      spawn ssh $user@$host
      expect "$ "
  </code></pre>