Example—Automating The write Command

Scripts are not limited to interactions with two processes. Large numbers of processes can be spawned from a single script. As an example, imagine a script that runs several write processes simultaneously. Why would this be useful? The UNIX write program allows a person to type messages on one other person’s terminal. The wall program allows messages to be typed on everyone’s terminal, but there is nothing in between—a program that types to a subset of terminals.

Using Expect, it is possible to write a script that writes messages to any set of users simultaneously. Here is the first half of such a script.

#!/usr/local/bin/expect --
set ulist {}
foreach user $argv {
    spawn write $user
    lappend ulist $spawn_id
}

The script reads the user names from the argument list. Each spawn id is appended to the list ulist. ulist is not a special variable. It could have been called anything. Notice that ulist is initialized to an empty list and then lappend is used to append to it. This is a common idiom for adding elements to lists.

Once all the spawn ids have been created, text can be sent to each process. In the second half of the script, text is read from the user via expect_user. Each time the user presses return, the line is sent to each spawned process.

set timeout −1
while 1 {
    expect_user {
        -re "\n" {}
        eof break
    }

    foreach spawn_id $ulist {
        send $expect_out(buffer)
    }
}

Each time through the foreach loop, spawn_id is assigned an element from ulist. This conveniently ...

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.