More On The timed–read Script

In Chapter 3 (p. 77), I defined an Expect script called timed-read. Called from the shell with the maximum number of seconds to wait, the script waits for a string to be entered, unless the given time is exceeded. Here it is again:

set timeout $argv
expect "\n" {
    send [string trimright "$expect_out(buffer)" "\n"]
}

In that earlier example I used "string trimright" to trim off the newline. It is possible for the expect command to do this in the pattern matching process, but not with glob patterns. I will use a regular expression to rewrite the script above without using the string command.

# timed read using a regular expression
set timeout $argv
expect -re "(.*)\n" {
    send $expect_out(1,string)
}

In the expect command, the -re flag declares the following pattern to be a regular expression instead of a glob pattern. As before, the pattern is quoted with double quotes. The pattern itself is:

(.*)\n

This matches any string of characters followed by a "\n“. All the characters except for the \n get stored in expect_out(1,string). Since the pattern is successfully matched, the action is executed. The action is to send all the characters in $expect_out(1,string) to the standard output. Of course, these characters are exactly what was just typed without the terminating "\n“.

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.