Recognizing Prompts (Yet Again)

In Chapter 5 (p. 120), I described how to match a variety of different prompts and potentially any prompt that a user might choose. A problem I did not address is that programs can require interaction even before the first prompt. One such program is tset, which is used to set the terminal type.

tset is fairly clever, but if it cannot figure out the terminal type, it prompts the user. The tset prompt is well defined. The prompt starts with a fixed string and then has a default terminal type in parentheses, such as:

TERM = (xterm)

At this point, the user can either enter the terminal type or simply press return, in which case the type is set to the default. In most scripts, the default is fine.

The following fragment handles this interaction:

expect {
    "TERM = *) " {
        send "\r"
        exp_continue
    } -re $prompt
}

Both the prompt from tset and the shell are expected. If the shell prompt shows up first, the expect is satisfied and the script continues. If the tset prompt appears, the script acknowledges it and uses exp_continue to repeat and look for the shell prompt.

The fragment does a little more work than it needs. If it finds the tset prompt once, it looks for it again even though it will not appear. To avoid this, the loop would have to be unrolled—but it would have no substantive benefit. It is easier to write and more readable as it is.

Fortunately, tset is the only interactive program that is commonly encountered while logging in. If you have need to handle ...

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.