How to use expect inside bash script

Hasan Rumman picture Hasan Rumman · Jul 17, 2017 · Viewed 11.1k times · Source

Could anybody please tell me why this is not working?

#!/bin/bash
cd /home
touch somefile
/usr/bin/expect<<FILETRANSFER
spawn scp -r -P remoteServerPort somefile remoteServerIP:/home
expect "assword:"
send "MyPassWord\r"
interact
FILETRANSFER
echo "It's done"

It doesn't give any error but file is not transferred to remote server.I have tried many ways still couldn't find any solution.

Answer

Cristian Ramon-Cortes picture Cristian Ramon-Cortes · Jul 17, 2017

The bash script you have defined is passing the expect commands on the standard input of expect. However, the expect command requires its arguments on a file or as an argument using the -c option.

You have several options but to add the less modifications on your script you just need to use the process substitution to create a here-document (temporary) for the expect command.

#!/bin/bash 

  echo "[DEBUG] INIT BASH"

  cd /home
  touch somefile

  /usr/bin/expect <(cat << EOF
spawn scp -r -P remoteServerPort somefile remoteServerIP:/home
expect "Password:"
send "MyPassWord\r"
interact
EOF
)

  echo "[DEBUG] END BASH"