Example—Timed Reads In The Shell

I have shown how to wait for input for a given amount of time and how to send data back. I will wrap this up in a script called timed-read.

#!/usr/local/bin/expect --
set timeout $argv
expect "\n" {
    send [string trimright "$expect_out(buffer)" "\n"]
}

The timeout is read from the variable argv which is predefined to contain the arguments from the command line. I will describe argv further in Chapter 9 (p. 209). The next command waits for a line to be entered. When it is, "string trimright ... "\n"" returns the string without the newline on the end of it, and that is returned as the result of the script.

You can now call this script from a shell as follows:

% timed-read 60

This command waits 60 seconds for the user to type a line and then it returns whatever the user typed. This ability is very useful. For example, suppose your system reboots automatically upon a crash. You could set up your system so that it gives someone the opportunity to log in to straighten out any problems before coming up all the way. Of course, if the machine crashes when no one is around, you do not want the computer to wait until someone comes in just to tell it to go ahead. To do so, just embed this in your shell script:

echo "Rebooting..."
echo "Want to poke around before coming up all the way?"
answer='timed-read 60'

Now you could test to see if the answer is yes or no. If no one is around, the script will just time out after 60 seconds and the answer will be empty. The ...

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.