title: Embedding an Expect script inside a Bash script
body: <p>I have the following script:</p>
  
  <pre><code>#!/bin/bash
  
  if [ `hostname` = 'EXAMPLE' ]
  then
  
  /usr/bin/expect &lt;&lt; EOD
  
  spawn scp -rp host:~/outfiles/ /home/USERNAME/outfiles/
  expect "id_rsa':"
  send "PASSWORD\r"
  interact
  
  spawn scp -rp host:~/errfiles/ /home/USERNAME/errfiles/
  expect "id_rsa':"
  send "PASSWORD\r"
  interact
  
  expect eof
  
  EOD
  
  echo 'Successful download'
  fi
  </code></pre>
  
  <p>Unfortunately it doesn't seem to work and I get an error message:</p>
  
  <pre><code>spawn scp -rp host:~/outfiles/ /home/USERNAME/outfiles/
  Enter passphrase for key '/home/USERNAME/.ssh/id_rsa': interact: spawn id exp0 not open
      while executing
  "interact"
  </code></pre>
  
  <p>I don't know what it means and why it doesn't work. However, when I wrote the above code using a not-embedded Expect script:</p>
  
  <pre><code>#!/usr/bin/expect
  
  spawn scp -rp host:~/outfiles/ /home/USERNAME/outfiles/
  expect "id_rsa':"
  send "PASSWORD\r"
  interact
  
  spawn scp -rp host:~/errfiles/ /home/USERNAME/errfiles/
  expect "id_rsa':"
  send "PASSWORD\r"
  interact
  </code></pre>
  
  <p>It worked without any problems. So what am I doing wrong?</p>
  
  <p>NOTE: Often when someone posts a question about using Expect to use <code>scp</code> or <code>ssh</code> the answer given is to use <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)" rel="nofollow noreferrer">RSA</a> keys. I tried, unfortunately on one of my computers there is some crappy bug with the GNOME keyring that means that I can't remove my password from the RSA key, which is exactly why I'm trying to write the above script with an <code>if</code> statement. So please don't tell me to use RSA keys.</p>