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"
The default timeout for
expect
is 10 seconds according to its manpage. To change it to 120 seconds, beforespawn ssh $USER@$HOST
, add the lineto make this
According to the following extract of the man page for expect:
" expect [[-opts] pat1 body1] ... [-opts] patn [bodyn]
waits until one of the patterns matches the output of a spawned process, a specified time period has passed, or an end-of-file is seen. If the final body is empty, it may be omitted.
Patterns from the most recent expect_before command are implicitly used before any other patterns. Patterns from the most recent expect_after command are implicitly used after any other patterns.
If the arguments to the entire expect statement require more than one line, all the arguments may be "braced" into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces.
If a pattern is the keyword eof, the corresponding body is executed upon end-of-file. If a pattern is the keyword timeout, the corresponding body is executed upon timeout. If no timeout keyword is used, an implicit null action is executed upon timeout. The default timeout period is 10 seconds but may be set, for example to 30, by the command "set timeout 30". An infinite timeout may be designated by the value -1. If a pattern is the keyword default, the corresponding body is executed upon either timeout or end-of-file.
If a pattern matches, then the corresponding body is executed. expect returns the result of the body (or the empty string if no pattern matched). In the event that multiple patterns match, the one appearing first is used to select a body. ... "
@DerfK has answered your question. I'd refactor your script for maintenance though: