Handling Timeout
Much of the time, expect commands have only one argument—a pattern with no action—similar to the very first one in this chapter:
expect "hi"
All this does is wait for hi before continuing. You could also write this as:
expect "hi" {}
to show the empty action, but expect does not require it. Only the last action in an expect command can be omitted:
expect {
"hi" {send "You said hi\n"}
"hello" {send "Hello yourself\n"}
"bye"
}
As a natural consequence of this, it is typical to write expect commands with the exception strings at the top and the likely string at the bottom. For example, you could add some error checking to the beginning of the anonymous ftp script from the previous chapter:
spawn ftp $argv
set timeout 10
expect {
"connection refused" exit
"unknown host" exit
"Name"
}
send "anonymous\r"
If the script sees Name it will go on and send anonymous\r. But if it sees "unknown host" or "connection refused“, the script will exit. Scripts written this way flow gracefully from top to bottom.
If, after 10 seconds, none of these patterns have been seen, expect will timeout and the next command in the script will be executed. I used this behavior in constructing the timed_read script in the previous chapter. Here, however, I only want to go to the next command if Name is successfully matched.
You can distinguish the successful case from the timeout by associating an action with the timeout. This is done by using the special pattern timeout. It looks like this:
expect ...