Indirect Spawn Ids

Earlier, I showed how to store a list of spawn ids in a variable and pass that to the expect command. In this case, the argument to the −i flag is called a direct spawn id.

set list "$spawn_id1 $spawn_id2 $spawn_id3"
expect −i $list pattern {
    command
    exp_continue
}

Instead of passing a list directly, it is occasionally useful to pass the name of a global variable that contains the list of direct spawn ids. This is known as an indirect spawn id. For example:

set list "$spawn_id1 $spawn_id2 $spawn_id3"
expect −i list pattern {                                        ;# DIFFERENT!  No
"$"!!
    command
    exp_continue
}

This example is identical to the previous example except that the list variable following the −i flag is passed without the $ preceding it. When the expect command begins, it reads the variable and uses the spawn ids in the list as if they had been specified directly. If the variable is changed while the expect command is in progress, the expect command accordingly modifies what processes are watched for patterns.

The following example shows how new spawn ids could be added to an expect in progress. Each time the add command is read, its argument is appended to the spawn id list stored in list.

expect −i list "add (.*)\n" {
    lappend list expect_out(1,string)
    exp_continue
}

Indirect spawn ids can also be used with expect_before and expect_after. For example, the following command removes closed spawn ids from the list, terminating the expect command when the list is empty and continuing it otherwise. ...

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.