Bash – Expect timeout, in Bash scripting

bashexpect

How do I add timeout for "expect" in the following script? I want to set it as 120 seconds.

#!/bin/bash
HOST="localhost"
USER="myuname"
PASS="mypassword"

VAR=$(expect -c "
spawn ssh $USER@$HOST
expect \"password:\"
send \"$PASS\r\"
expect \"\\\\$\"
send \"ls\r\"
expect -re \"$USER.*\"
send \"logout\"
")

echo "==============="
echo "$VAR"

Best Answer

The default timeout for expect is 10 seconds according to its manpage. To change it to 120 seconds, before spawn ssh $USER@$HOST, add the line

set timeout 120

to make this

VAR=$(expect -c "
set timeout 120
spawn ssh $USER@$HOST
expect \"password:\"
send \"$PASS\r\"
expect \"\\\\$\"
send \"ls\r\"
expect -re \"$USER.*\"
send \"logout\"
")