Chapter 3. Getting Started With Expect

Three commands are central to the power of Expect: send, expect, and spawn. The send command sends strings to a process, the expect command waits for strings from a process, and the spawn command starts a process.

In this chapter, I will describe these commands and another one that is very useful: interact. To best understand this chapter, it will help to have some basic familiarity with Tcl. If you are wondering about a command that is not explained, look it up in the index for a reference in the previous chapter and read about it there.

The send Command

The send command takes a string as an argument and sends it to a process. For example:

send "hello world"

This sends the string "hello world" (without the quotes). If Expect is already interacting with a program, the string will be sent to that program. But initially, send will send to the standard output. Here is what happens when I type this to the Expect interpreter interactively:

expect1.1> send "hello world"
hello worldexpect1.2>

The send command does not format the string in any way, so after it is printed the next Expect prompt gets appended to it without any space. To make the prompt appear on a different line, put a newline character at the end of the string. A newline is represented by "\n“.

expect1.1> send "hello world\n"
hello world

If these commands are stored in a file, speak, the script can be executed from the UNIX command line:

% expect speak
hello world

With a little ...

Get Exploring Expect now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.