Pattern-Action Pairs

You can directly associate a command with a pattern. Such commands are referred to as actions. The association is made by listing the action immediately after the pattern in the expect command itself. For example:

expect "hi" {send "You said $expect_out(buffer)"}

The command "send "You said $expect_out(buffer)"" will be executed if and only if hi is matched from the input.

Additional pattern-action pairs can be listed after the first one:

expect "hi"                { send "You said hi\n" } \
    "hello"            { send "Hello yourself\n" } \
    "bye"            { send "That was unexpected\n" }

This command looks for "hi“, "hello“, and "bye" simultaneously. If any of the three patterns are found, the action listed immediately after the first matching pattern is executed. It is possible that none of them match within the time period defined by the timeout. In this case, expect stops waiting and execution continues with the next command in the script. Actions can be associated with timeouts, and I will describe that in Chapter 4 (p. 94).

In the expect command, it does not matter how the patterns and actions visually line up. They can all appear on a single line if you can fit them, but lining up the patterns and actions usually makes it easier for a human to read them.

Notice how all the actions are embedded in braces. That is because expect would otherwise misinterpret the command. What is the problem with the following command?

expect "hi" send "You said hi\n"     ;# wrong!

In this case, hi is taken as a pattern, ...

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.