The expect_before And expect_after Commands

One of the most common uses for any_spawn_id is to check for an eof. Even if an eof is not expected, it is a good idea to test for it. That way the script can gracefully shut down even if something unexpected happens.

Unfortunately, adding eof patterns to all expect commands can make for a lot of extra typing. It is possible to create and call a new procedure that automatically tacks on the eof patterns, but Expect provides a more direct solution.

The commands expect_before and expect_after declare patterns that are used automatically by subsequent expect commands. As an example, consider the following commands. Each one explicitly checks for an eof as well as the pattern. If the pattern is found, the next command is executed. If an eof occurs, the fictitious command eofproc is called.

expect {
    "login:" {send "$user\r"}
    eof eofproc
}
expect {
    "password:" {send "$password\r"}
    eof eofproc
}
expect {
    "$prompt" {send "$command\r"}
    eof eofproc
}

Because the "eof eofproc" is the same in each, it is possible to declare it once using expect_after. The following code behaves identically to the earlier code.

expect_after eof eofproc
expect "login:"    {send "$user\r"}
expect "password:" {send "$password\r"}
expect "$prompt"   {send "$command\r"}

As you can see, the code is much shorter than before. You can drastically simplify a lot of code this way and at the same time make it much more robust.

The difference between expect_before and expect_after is the order ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.