O'Reilly logo

Exploring Expect by Don Libes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required