1EXPECT(1) General Commands Manual EXPECT(1)
2
3
4
6 expect - programmed dialogue with interactive programs, Version 5
7
9 expect [ -dDhinNv ] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ]
10
12 Expect is a program that "talks" to other interactive programs accord‐
13 ing to a script. Following the script, Expect knows what can be
14 expected from a program and what the correct response should be. An
15 interpreted language provides branching and high-level control struc‐
16 tures to direct the dialogue. In addition, the user can take control
17 and interact directly when desired, afterward returning control to the
18 script.
19
20 Expectk is a mixture of Expect and Tk. It behaves just like Expect and
21 Tk's wish. Expect can also be used directly in C or C++ (that is,
22 without Tcl). See libexpect(3).
23
24 The name "Expect" comes from the idea of send/expect sequences popular‐
25 ized by uucp, kermit and other modem control programs. However unlike
26 uucp, Expect is generalized so that it can be run as a user-level com‐
27 mand with any program and task in mind. Expect can actually talk to
28 several programs at the same time.
29
30 For example, here are some things Expect can do:
31
32 · Cause your computer to dial you back, so that you can login
33 without paying for the call.
34
35 · Start a game (e.g., rogue) and if the optimal configuration
36 doesn't appear, restart it (again and again) until it does,
37 then hand over control to you.
38
39 · Run fsck, and in response to its questions, answer "yes",
40 "no" or give control back to you, based on predetermined
41 criteria.
42
43 · Connect to another network or BBS (e.g., MCI Mail, Com‐
44 puServe) and automatically retrieve your mail so that it
45 appears as if it was originally sent to your local system.
46
47 · Carry environment variables, current directory, or any kind
48 of information across rlogin, telnet, tip, su, chgrp, etc.
49
50 There are a variety of reasons why the shell cannot perform these
51 tasks. (Try, you'll see.) All are possible with Expect.
52
53 In general, Expect is useful for running any program which requires
54 interaction between the program and the user. All that is necessary is
55 that the interaction can be characterized programmatically. Expect can
56 also give the user back control (without halting the program being con‐
57 trolled) if desired. Similarly, the user can return control to the
58 script at any time.
59
61 Expect reads cmdfile for a list of commands to execute. Expect may
62 also be invoked implicitly on systems which support the #! notation by
63 marking the script executable, and making the first line in your
64 script:
65
66 #!/usr/local/bin/expect -f
67
68 Of course, the path must accurately describe where Expect lives.
69 /usr/local/bin is just an example.
70
71 The -c flag prefaces a command to be executed before any in the script.
72 The command should be quoted to prevent being broken up by the shell.
73 This option may be used multiple times. Multiple commands may be exe‐
74 cuted with a single -c by separating them with semicolons. Commands
75 are executed in the order they appear. (When using Expectk, this
76 option is specified as -command.)
77
78 The -d flag enables some diagnostic output, which primarily reports
79 internal activity of commands such as expect and interact. This flag
80 has the same effect as "exp_internal 1" at the beginning of an Expect
81 script, plus the version of Expect is printed. (The strace command is
82 useful for tracing statements, and the trace command is useful for
83 tracing variable assignments.) (When using Expectk, this option is
84 specified as -diag.)
85
86 The -D flag enables an interactive debugger. An integer value should
87 follow. The debugger will take control before the next Tcl procedure
88 if the value is non-zero or if a ^C is pressed (or a breakpoint is hit,
89 or other appropriate debugger command appears in the script). See the
90 README file or SEE ALSO (below) for more information on the debugger.
91 (When using Expectk, this option is specified as -Debug.)
92
93 The -f flag prefaces a file from which to read commands from. The flag
94 itself is optional as it is only useful when using the #! notation (see
95 above), so that other arguments may be supplied on the command line.
96 (When using Expectk, this option is specified as -file.)
97
98 By default, the command file is read into memory and executed in its
99 entirety. It is occasionally desirable to read files one line at a
100 time. For example, stdin is read this way. In order to force arbi‐
101 trary files to be handled this way, use the -b flag. (When using
102 Expectk, this option is specified as -buffer.) Note that stdio-buffer‐
103 ing may still take place however this shouldn't cause problems when
104 reading from a fifo or stdin.
105
106 If the string "-" is supplied as a filename, standard input is read
107 instead. (Use "./-" to read from a file actually named "-".)
108
109 -h causes Expect to print its usage message and exit.
110
111 The -i flag causes Expect to interactively prompt for commands instead
112 of reading them from a file. Prompting is terminated via the exit com‐
113 mand or upon EOF. See interpreter (below) for more information. -i is
114 assumed if neither a command file nor -c is used. (When using Expectk,
115 this option is specified as -interactive.)
116
117 -- may be used to delimit the end of the options. This is useful if
118 you want to pass an option-like argument to your script without it
119 being interpreted by Expect. This can usefully be placed in the #!
120 line to prevent any flag-like interpretation by Expect. For example,
121 the following will leave the original arguments (including the script
122 name) in the variable argv.
123
124 #!/usr/local/bin/expect --
125
126 Note that the usual getopt(3) and execve(2) conventions must be
127 observed when adding arguments to the #! line.
128
129 The file $exp_library/expect.rc is sourced automatically if present,
130 unless the -N flag is used. (When using Expectk, this option is speci‐
131 fied as -NORC.) Immediately after this, the file ~/.expect.rc is
132 sourced automatically, unless the -n flag is used. If the environment
133 variable DOTDIR is defined, it is treated as a directory and .expect.rc
134 is read from there. (When using Expectk, this option is specified as
135 -norc.) This sourcing occurs only after executing any -c flags.
136
137 -v causes Expect to print its version number and exit. (The corre‐
138 sponding flag in Expectk, which uses long flag names, is -version.)
139
140 Optional args are constructed into a list and stored in the variable
141 named argv. argc is initialized to the length of argv.
142
143 argv0 is defined to be the name of the script (or binary if no script
144 is used). For example, the following prints out the name of the script
145 and the first three arguments:
146
147 send_user "$argv0 [lrange $argv 0 2]\n"
148
149
151 Expect uses Tcl (Tool Command Language). Tcl provides control flow
152 (e.g., if, for, break), expression evaluation and several other fea‐
153 tures such as recursion, procedure definition, etc. Commands used here
154 but not defined (e.g., set, if, exec) are Tcl commands (see tcl(3)).
155 Expect supports additional commands, described below. Unless otherwise
156 specified, commands return the empty string.
157
158 Commands are listed alphabetically so that they can be quickly located.
159 However, new users may find it easier to start by reading the descrip‐
160 tions of spawn, send, expect, and interact, in that order.
161
162 Note that the best introduction to the language (both Expect and Tcl)
163 is provided in the book "Exploring Expect" (see SEE ALSO below). Exam‐
164 ples are included in this man page but they are very limited since this
165 man page is meant primarily as reference material.
166
167 Note that in the text of this man page, "Expect" with an uppercase "E"
168 refers to the Expect program while "expect" with a lower-case "e"
169 refers to the expect command within the Expect program.)
170
171 close [-slave] [-onexec 0|1] [-i spawn_id]
172 closes the connection to the current process. Most interactive
173 programs will detect EOF on their stdin and exit; thus close usu‐
174 ally suffices to kill the process as well. The -i flag declares
175 the process to close corresponding to the named spawn_id.
176
177 Both expect and interact will detect when the current process
178 exits and implicitly do a close. But if you kill the process by,
179 say, "exec kill $pid", you will need to explicitly call close.
180
181 The -onexec flag determines whether the spawn id will be closed
182 in any new spawned processes or if the process is overlayed. To
183 leave a spawn id open, use the value 0. A non-zero integer value
184 will force the spawn closed (the default) in any new processes.
185
186 The -slave flag closes the slave associated with the spawn id.
187 (See "spawn -pty".) When the connection is closed, the slave is
188 automatically closed as well if still open.
189
190 No matter whether the connection is closed implicitly or explic‐
191 itly, you should call wait to clear up the corresponding kernel
192 process slot. close does not call wait since there is no guaran‐
193 tee that closing a process connection will cause it to exit. See
194 wait below for more info.
195
196 debug [[-now] 0|1]
197 controls a Tcl debugger allowing you to step through statements,
198 set breakpoints, etc.
199
200 With no arguments, a 1 is returned if the debugger is not run‐
201 ning, otherwise a 0 is returned.
202
203 With a 1 argument, the debugger is started. With a 0 argument,
204 the debugger is stopped. If a 1 argument is preceded by the -now
205 flag, the debugger is started immediately (i.e., in the middle of
206 the debug command itself). Otherwise, the debugger is started
207 with the next Tcl statement.
208
209 The debug command does not change any traps. Compare this to
210 starting Expect with the -D flag (see above).
211
212 See the README file or SEE ALSO (below) for more information on
213 the debugger.
214
215 disconnect
216 disconnects a forked process from the terminal. It continues
217 running in the background. The process is given its own process
218 group (if possible). Standard I/O is redirected to /dev/null.
219
220 The following fragment uses disconnect to continue running the
221 script in the background.
222
223 if {[fork]!=0} exit
224 disconnect
225 . . .
226
227 The following script reads a password, and then runs a program
228 every hour that demands a password each time it is run. The
229 script supplies the password so that you only have to type it
230 once. (See the stty command which demonstrates how to turn off
231 password echoing.)
232
233 send_user "password?\ "
234 expect_user -re "(.*)\n"
235 for {} 1 {} {
236 if {[fork]!=0} {sleep 3600;continue}
237 disconnect
238 spawn priv_prog
239 expect Password:
240 send "$expect_out(1,string)\r"
241 . . .
242 exit
243 }
244
245 An advantage to using disconnect over the shell asynchronous
246 process feature (&) is that Expect can save the terminal parame‐
247 ters prior to disconnection, and then later apply them to new
248 ptys. With &, Expect does not have a chance to read the termi‐
249 nal's parameters since the terminal is already disconnected by
250 the time Expect receives control.
251
252 exit [-opts] [status]
253 causes Expect to exit or otherwise prepare to do so.
254
255 The -onexit flag causes the next argument to be used as an exit
256 handler. Without an argument, the current exit handler is
257 returned.
258
259 The -noexit flag causes Expect to prepare to exit but stop short
260 of actually returning control to the operating system. The user-
261 defined exit handler is run as well as Expect's own internal han‐
262 dlers. No further Expect commands should be executed. This is
263 useful if you are running Expect with other Tcl extensions. The
264 current interpreter (and main window if in the Tk environment)
265 remain so that other Tcl extensions can clean up. If Expect's
266 exit is called again (however this might occur), the handlers are
267 not rerun.
268
269 Upon exiting, all connections to spawned processes are closed.
270 Closure will be detected as an EOF by spawned processes. exit
271 takes no other actions beyond what the normal _exit(2) procedure
272 does. Thus, spawned processes that do not check for EOF may con‐
273 tinue to run. (A variety of conditions are important to deter‐
274 mining, for example, what signals a spawned process will be sent,
275 but these are system-dependent, typically documented under
276 exit(3).) Spawned processes that continue to run will be inher‐
277 ited by init.
278
279 status (or 0 if not specified) is returned as the exit status of
280 Expect. exit is implicitly executed if the end of the script is
281 reached.
282
283 exp_continue [-continue_timer]
284 The command exp_continue allows expect itself to continue execut‐
285 ing rather than returning as it normally would. By default
286 exp_continue resets the timeout timer. The -continue_timer flag
287 prevents timer from being restarted. (See expect for more infor‐
288 mation.)
289
290 exp_internal [-f file] value
291 causes further commands to send diagnostic information internal
292 to Expect to stderr if value is non-zero. This output is dis‐
293 abled if value is 0. The diagnostic information includes every
294 character received, and every attempt made to match the current
295 output against the patterns.
296
297 If the optional file is supplied, all normal and debugging output
298 is written to that file (regardless of the value of value). Any
299 previous diagnostic output file is closed.
300
301 The -info flag causes exp_internal to return a description of the
302 most recent non-info arguments given.
303
304 exp_open [args] [-i spawn_id]
305 returns a Tcl file identifier that corresponds to the original
306 spawn id. The file identifier can then be used as if it were
307 opened by Tcl's open command. (The spawn id should no longer be
308 used. A wait should not be executed.
309
310 The -leaveopen flag leaves the spawn id open for access through
311 Expect commands. A wait must be executed on the spawn id.
312
313 exp_pid [-i spawn_id]
314 returns the process id corresponding to the currently spawned
315 process. If the -i flag is used, the pid returned corresponds to
316 that of the given spawn id.
317
318 exp_send
319 is an alias for send.
320
321 exp_send_error
322 is an alias for send_error.
323
324 exp_send_log
325 is an alias for send_log.
326
327 exp_send_tty
328 is an alias for send_tty.
329
330 exp_send_user
331 is an alias for send_user.
332
333 exp_version [[-exit] version]
334 is useful for assuring that the script is compatible with the
335 current version of Expect.
336
337 With no arguments, the current version of Expect is returned.
338 This version may then be encoded in your script. If you actually
339 know that you are not using features of recent versions, you can
340 specify an earlier version.
341
342 Versions consist of three numbers separated by dots. First is
343 the major number. Scripts written for versions of Expect with a
344 different major number will almost certainly not work. exp_ver‐
345 sion returns an error if the major numbers do not match.
346
347 Second is the minor number. Scripts written for a version with a
348 greater minor number than the current version may depend upon
349 some new feature and might not run. exp_version returns an error
350 if the major numbers match, but the script minor number is
351 greater than that of the running Expect.
352
353 Third is a number that plays no part in the version comparison.
354 However, it is incremented when the Expect software distribution
355 is changed in any way, such as by additional documentation or
356 optimization. It is reset to 0 upon each new minor version.
357
358 With the -exit flag, Expect prints an error and exits if the ver‐
359 sion is out of date.
360
361 expect [[-opts] pat1 body1] ... [-opts] patn [bodyn]
362 waits until one of the patterns matches the output of a spawned
363 process, a specified time period has passed, or an end-of-file is
364 seen. If the final body is empty, it may be omitted.
365
366 Patterns from the most recent expect_before command are implic‐
367 itly used before any other patterns. Patterns from the most
368 recent expect_after command are implicitly used after any other
369 patterns.
370
371 If the arguments to the entire expect statement require more than
372 one line, all the arguments may be "braced" into one so as to
373 avoid terminating each line with a backslash. In this one case,
374 the usual Tcl substitutions will occur despite the braces.
375
376 If a pattern is the keyword eof, the corresponding body is exe‐
377 cuted upon end-of-file. If a pattern is the keyword timeout, the
378 corresponding body is executed upon timeout. If no timeout key‐
379 word is used, an implicit null action is executed upon timeout.
380 The default timeout period is 10 seconds but may be set, for
381 example to 30, by the command "set timeout 30". An infinite
382 timeout may be designated by the value -1. If a pattern is the
383 keyword default, the corresponding body is executed upon either
384 timeout or end-of-file.
385
386 If a pattern matches, then the corresponding body is executed.
387 expect returns the result of the body (or the empty string if no
388 pattern matched). In the event that multiple patterns match, the
389 one appearing first is used to select a body.
390
391 Each time new output arrives, it is compared to each pattern in
392 the order they are listed. Thus, you may test for absence of a
393 match by making the last pattern something guaranteed to appear,
394 such as a prompt. In situations where there is no prompt, you
395 must use timeout (just like you would if you were interacting
396 manually).
397
398 Patterns are specified in three ways. By default, patterns are
399 specified as with Tcl's string match command. (Such patterns are
400 also similar to C-shell regular expressions usually referred to
401 as "glob" patterns). The -gl flag may be used to protect pat‐
402 terns that might otherwise match expect flags from doing so. Any
403 pattern beginning with a "-" should be protected this way. (All
404 strings starting with "-" are reserved for future options.)
405
406
407 For example, the following fragment looks for a successful login.
408 (Note that abort is presumed to be a procedure defined elsewhere
409 in the script.)
410
411 expect {
412 busy {puts busy\n ; exp_continue}
413 failed abort
414 "invalid password" abort
415 timeout abort
416 connected
417 }
418
419 Quotes are necessary on the fourth pattern since it contains a
420 space, which would otherwise separate the pattern from the
421 action. Patterns with the same action (such as the 3rd and 4th)
422 require listing the actions again. This can be avoid by using
423 regexp-style patterns (see below). More information on forming
424 glob-style patterns can be found in the Tcl manual.
425
426 Regexp-style patterns follow the syntax defined by Tcl's regexp
427 (short for "regular expression") command. regexp patterns are
428 introduced with the flag -re. The previous example can be
429 rewritten using a regexp as:
430
431 expect {
432 busy {puts busy\n ; exp_continue}
433 -re "failed|invalid password" abort
434 timeout abort
435 connected
436 }
437
438 Both types of patterns are "unanchored". This means that pat‐
439 terns do not have to match the entire string, but can begin and
440 end the match anywhere in the string (as long as everything else
441 matches). Use ^ to match the beginning of a string, and $ to
442 match the end. Note that if you do not wait for the end of a
443 string, your responses can easily end up in the middle of the
444 string as they are echoed from the spawned process. While still
445 producing correct results, the output can look unnatural. Thus,
446 use of $ is encouraged if you can exactly describe the characters
447 at the end of a string.
448
449 Note that in many editors, the ^ and $ match the beginning and
450 end of lines respectively. However, because expect is not line
451 oriented, these characters match the beginning and end of the
452 data (as opposed to lines) currently in the expect matching buf‐
453 fer. (Also, see the note below on "system indigestion.")
454
455 The -ex flag causes the pattern to be matched as an "exact"
456 string. No interpretation of *, ^, etc is made (although the
457 usual Tcl conventions must still be observed). Exact patterns
458 are always unanchored.
459
460
461 The -nocase flag causes uppercase characters of the output to
462 compare as if they were lowercase characters. The pattern is not
463 affected.
464
465 While reading output, more than 2000 bytes can force earlier
466 bytes to be "forgotten". This may be changed with the function
467 match_max. (Note that excessively large values can slow down the
468 pattern matcher.) If patlist is full_buffer, the corresponding
469 body is executed if match_max bytes have been received and no
470 other patterns have matched. Whether or not the full_buffer key‐
471 word is used, the forgotten characters are written to
472 expect_out(buffer).
473
474 If patlist is the keyword null, and nulls are allowed (via the
475 remove_nulls command), the corresponding body is executed if a
476 single ASCII 0 is matched. It is not possible to match 0 bytes
477 via glob or regexp patterns.
478
479 Upon matching a pattern (or eof or full_buffer), any matching and
480 previously unmatched output is saved in the variable
481 expect_out(buffer). Up to 9 regexp substring matches are saved
482 in the variables expect_out(1,string) through
483 expect_out(9,string). If the -indices flag is used before a pat‐
484 tern, the starting and ending indices (in a form suitable for
485 lrange) of the 10 strings are stored in the variables
486 expect_out(X,start) and expect_out(X,end) where X is a digit,
487 corresponds to the substring position in the buffer. 0 refers to
488 strings which matched the entire pattern and is generated for
489 glob patterns as well as regexp patterns. For example, if a
490 process has produced output of "abcdefgh\n", the result of:
491
492 expect "cd"
493
494 is as if the following statements had executed:
495
496 set expect_out(0,string) cd
497 set expect_out(buffer) abcd
498
499 and "efgh\n" is left in the output buffer. If a process produced
500 the output "abbbcabkkkka\n", the result of:
501
502 expect -indices -re "b(b*).*(k+)"
503
504 is as if the following statements had executed:
505
506 set expect_out(0,start) 1
507 set expect_out(0,end) 10
508 set expect_out(0,string) bbbcabkkkk
509 set expect_out(1,start) 2
510 set expect_out(1,end) 3
511 set expect_out(1,string) bb
512 set expect_out(2,start) 10
513 set expect_out(2,end) 10
514 set expect_out(2,string) k
515 set expect_out(buffer) abbbcabkkkk
516
517 and "a\n" is left in the output buffer. The pattern "*" (and -re
518 ".*") will flush the output buffer without reading any more out‐
519 put from the process.
520
521 Normally, the matched output is discarded from Expect's internal
522 buffers. This may be prevented by prefixing a pattern with the
523 -notransfer flag. This flag is especially useful in experiment‐
524 ing (and can be abbreviated to "-not" for convenience while
525 experimenting).
526
527 The spawn id associated with the matching output (or eof or
528 full_buffer) is stored in expect_out(spawn_id).
529
530 The -timeout flag causes the current expect command to use the
531 following value as a timeout instead of using the value of the
532 timeout variable.
533
534 By default, patterns are matched against output from the current
535 process, however the -i flag declares the output from the named
536 spawn_id list be matched against any following patterns (up to
537 the next -i). The spawn_id list should either be a whitespace
538 separated list of spawn_ids or a variable referring to such a
539 list of spawn_ids.
540
541 For example, the following example waits for "connected" from the
542 current process, or "busy", "failed" or "invalid password" from
543 the spawn_id named by $proc2.
544
545 expect {
546 -i $proc2 busy {puts busy\n ; exp_continue}
547 -re "failed|invalid password" abort
548 timeout abort
549 connected
550 }
551
552 The value of the global variable any_spawn_id may be used to
553 match patterns to any spawn_ids that are named with all other -i
554 flags in the current expect command. The spawn_id from a -i flag
555 with no associated pattern (i.e., followed immediately by another
556 -i) is made available to any other patterns in the same expect
557 command associated with any_spawn_id.
558
559 The -i flag may also name a global variable in which case the
560 variable is read for a list of spawn ids. The variable is reread
561 whenever it changes. This provides a way of changing the I/O
562 source while the command is in execution. Spawn ids provided
563 this way are called "indirect" spawn ids.
564
565 Actions such as break and continue cause control structures
566 (i.e., for, proc) to behave in the usual way. The command
567 exp_continue allows expect itself to continue executing rather
568 than returning as it normally would.
569
570 This is useful for avoiding explicit loops or repeated expect
571 statements. The following example is part of a fragment to auto‐
572 mate rlogin. The exp_continue avoids having to write a second
573 expect statement (to look for the prompt again) if the rlogin
574 prompts for a password.
575
576 expect {
577 Password: {
578 stty -echo
579 send_user "password (for $user) on $host: "
580 expect_user -re "(.*)\n"
581 send_user "\n"
582 send "$expect_out(1,string)\r"
583 stty echo
584 exp_continue
585 } incorrect {
586 send_user "invalid password or account\n"
587 exit
588 } timeout {
589 send_user "connection to $host timed out\n"
590 exit
591 } eof {
592 send_user \
593 "connection to host failed: $expect_out(buffer)"
594 exit
595 } -re $prompt
596 }
597
598 For example, the following fragment might help a user guide an
599 interaction that is already totally automated. In this case, the
600 terminal is put into raw mode. If the user presses "+", a vari‐
601 able is incremented. If "p" is pressed, several returns are sent
602 to the process, perhaps to poke it in some way, and "i" lets the
603 user interact with the process, effectively stealing away control
604 from the script. In each case, the exp_continue allows the cur‐
605 rent expect to continue pattern matching after executing the cur‐
606 rent action.
607
608 stty raw -echo
609 expect_after {
610 -i $user_spawn_id
611 "p" {send "\r\r\r"; exp_continue}
612 "+" {incr foo; exp_continue}
613 "i" {interact; exp_continue}
614 "quit" exit
615 }
616
617
618 By default, exp_continue resets the timeout timer. The timer is
619 not restarted, if exp_continue is called with the -continue_timer
620 flag.
621
622 expect_after [expect_args]
623 works identically to the expect_before except that if patterns
624 from both expect and expect_after can match, the expect pattern
625 is used. See the expect_before command for more information.
626
627 expect_background [expect_args]
628 takes the same arguments as expect, however it returns immedi‐
629 ately. Patterns are tested whenever new input arrives. The pat‐
630 tern timeout and default are meaningless to expect_background and
631 are silently discarded. Otherwise, the expect_background command
632 uses expect_before and expect_after patterns just like expect
633 does.
634
635 When expect_background actions are being evaluated, background
636 processing for the same spawn id is blocked. Background process‐
637 ing is unblocked when the action completes. While background
638 processing is blocked, it is possible to do a (foreground) expect
639 on the same spawn id.
640
641 It is not possible to execute an expect while an expect_back‐
642 ground is unblocked. expect_background for a particular spawn id
643 is deleted by declaring a new expect_background with the same
644 spawn id. Declaring expect_background with no pattern removes
645 the given spawn id from the ability to match patterns in the
646 background.
647
648 expect_before [expect_args]
649 takes the same arguments as expect, however it returns immedi‐
650 ately. Pattern-action pairs from the most recent expect_before
651 with the same spawn id are implicitly added to any following
652 expect commands. If a pattern matches, it is treated as if it
653 had been specified in the expect command itself, and the associ‐
654 ated body is executed in the context of the expect command. If
655 patterns from both expect_before and expect can match, the
656 expect_before pattern is used.
657
658 If no pattern is specified, the spawn id is not checked for any
659 patterns.
660
661 Unless overridden by a -i flag, expect_before patterns match
662 against the spawn id defined at the time that the expect_before
663 command was executed (not when its pattern is matched).
664
665 The -info flag causes expect_before to return the current speci‐
666 fications of what patterns it will match. By default, it reports
667 on the current spawn id. An optional spawn id specification may
668 be given for information on that spawn id. For example
669
670 expect_before -info -i $proc
671
672 At most one spawn id specification may be given. The flag -indi‐
673 rect suppresses direct spawn ids that come only from indirect
674 specifications.
675
676 Instead of a spawn id specification, the flag "-all" will cause
677 "-info" to report on all spawn ids.
678
679 The output of the -info flag can be reused as the argument to
680 expect_before.
681
682 expect_tty [expect_args]
683 is like expect but it reads characters from /dev/tty (i.e. key‐
684 strokes from the user). By default, reading is performed in
685 cooked mode. Thus, lines must end with a return in order for
686 expect to see them. This may be changed via stty (see the stty
687 command below).
688
689 expect_user [expect_args]
690 is like expect but it reads characters from stdin (i.e. key‐
691 strokes from the user). By default, reading is performed in
692 cooked mode. Thus, lines must end with a return in order for
693 expect to see them. This may be changed via stty (see the stty
694 command below).
695
696 fork creates a new process. The new process is an exact copy of the
697 current Expect process. On success, fork returns 0 to the new
698 (child) process and returns the process ID of the child process
699 to the parent process. On failure (invariably due to lack of
700 resources, e.g., swap space, memory), fork returns -1 to the par‐
701 ent process, and no child process is created.
702
703 Forked processes exit via the exit command, just like the origi‐
704 nal process. Forked processes are allowed to write to the log
705 files. If you do not disable debugging or logging in most of the
706 processes, the result can be confusing.
707
708 Some pty implementations may be confused by multiple readers and
709 writers, even momentarily. Thus, it is safest to fork before
710 spawning processes.
711
712 interact [string1 body1] ... [stringn [bodyn]]
713 gives control of the current process to the user, so that key‐
714 strokes are sent to the current process, and the stdout and
715 stderr of the current process are returned.
716
717 String-body pairs may be specified as arguments, in which case
718 the body is executed when the corresponding string is entered.
719 (By default, the string is not sent to the current process.)
720 The interpreter command is assumed, if the final body is missing.
721
722 If the arguments to the entire interact statement require more
723 than one line, all the arguments may be "braced" into one so as
724 to avoid terminating each line with a backslash. In this one
725 case, the usual Tcl substitutions will occur despite the braces.
726
727 For example, the following command runs interact with the follow‐
728 ing string-body pairs defined: When ^Z is pressed, Expect is
729 suspended. (The -reset flag restores the terminal modes.) When
730 ^A is pressed, the user sees "you typed a control-A" and the
731 process is sent a ^A. When $ is pressed, the user sees the date.
732 When ^C is pressed, Expect exits. If "foo" is entered, the user
733 sees "bar". When ~~ is pressed, the Expect interpreter runs
734 interactively.
735
736 set CTRLZ \032
737 interact {
738 -reset $CTRLZ {exec kill -STOP [pid]}
739 \001 {send_user "you typed a control-A\n";
740 send "\001"
741 }
742 $ {send_user "The date is [clock format [clock seconds]]."}
743 \003 exit
744 foo {send_user "bar"}
745 ~~
746 }
747
748
749 In string-body pairs, strings are matched in the order they are
750 listed as arguments. Strings that partially match are not sent
751 to the current process in anticipation of the remainder coming.
752 If characters are then entered such that there can no longer pos‐
753 sibly be a match, only the part of the string will be sent to the
754 process that cannot possibly begin another match. Thus, strings
755 that are substrings of partial matches can match later, if the
756 original strings that was attempting to be match ultimately
757 fails.
758
759 By default, string matching is exact with no wild cards. (In
760 contrast, the expect command uses glob-style patterns by
761 default.) The -ex flag may be used to protect patterns that
762 might otherwise match interact flags from doing so. Any pattern
763 beginning with a "-" should be protected this way. (All
764 strings starting with "-" are reserved for future options.)
765
766 The -re flag forces the string to be interpreted as a regexp-
767 style pattern. In this case, matching substrings are stored in
768 the variable interact_out similarly to the way expect stores its
769 output in the variable expect_out. The -indices flag is simi‐
770 larly supported.
771
772 The pattern eof introduces an action that is executed upon end-
773 of-file. A separate eof pattern may also follow the -output flag
774 in which case it is matched if an eof is detected while writing
775 output. The default eof action is "return", so that interact
776 simply returns upon any EOF.
777
778 The pattern timeout introduces a timeout (in seconds) and action
779 that is executed after no characters have been read for a given
780 time. The timeout pattern applies to the most recently specified
781 process. There is no default timeout. The special variable
782 "timeout" (used by the expect command) has no affect on this
783 timeout.
784
785 For example, the following statement could be used to autologout
786 users who have not typed anything for an hour but who still get
787 frequent system messages:
788
789 interact -input $user_spawn_id timeout 3600 return -output \
790 $spawn_id
791
792
793 If the pattern is the keyword null, and nulls are allowed (via
794 the remove_nulls command), the corresponding body is executed if
795 a single ASCII 0 is matched. It is not possible to match 0 bytes
796 via glob or regexp patterns.
797
798 Prefacing a pattern with the flag -iwrite causes the variable
799 interact_out(spawn_id) to be set to the spawn_id which matched
800 the pattern (or eof).
801
802 Actions such as break and continue cause control structures
803 (i.e., for, proc) to behave in the usual way. However return
804 causes interact to return to its caller, while inter_return
805 causes interact to cause a return in its caller. For example, if
806 "proc foo" called interact which then executed the action
807 inter_return, proc foo would return. (This means that if inter‐
808 act calls interpreter interactively typing return will cause the
809 interact to continue, while inter_return will cause the interact
810 to return to its caller.)
811
812 During interact, raw mode is used so that all characters may be
813 passed to the current process. If the current process does not
814 catch job control signals, it will stop if sent a stop signal (by
815 default ^Z). To restart it, send a continue signal (such as by
816 "kill -CONT <pid>"). If you really want to send a SIGSTOP to
817 such a process (by ^Z), consider spawning csh first and then run‐
818 ning your program. On the other hand, if you want to send a
819 SIGSTOP to Expect itself, first call interpreter (perhaps by
820 using an escape character), and then press ^Z.
821
822 String-body pairs can be used as a shorthand for avoiding having
823 to enter the interpreter and execute commands interactively. The
824 previous terminal mode is used while the body of a string-body
825 pair is being executed.
826
827 For speed, actions execute in raw mode by default. The -reset
828 flag resets the terminal to the mode it had before interact was
829 executed (invariably, cooked mode). Note that characters entered
830 when the mode is being switched may be lost (an unfortunate fea‐
831 ture of the terminal driver on some systems). The only reason to
832 use -reset is if your action depends on running in cooked mode.
833
834 The -echo flag sends characters that match the following pattern
835 back to the process that generated them as each character is
836 read. This may be useful when the user needs to see feedback
837 from partially typed patterns.
838
839 If a pattern is being echoed but eventually fails to match, the
840 characters are sent to the spawned process. If the spawned
841 process then echoes them, the user will see the characters twice.
842 -echo is probably only appropriate in situations where the user
843 is unlikely to not complete the pattern. For example, the fol‐
844 lowing excerpt is from rftp, the recursive-ftp script, where the
845 user is prompted to enter ~g, ~p, or ~l, to get, put, or list the
846 current directory recursively. These are so far away from the
847 normal ftp commands, that the user is unlikely to type ~ followed
848 by anything else, except mistakenly, in which case, they'll prob‐
849 ably just ignore the result anyway.
850
851 interact {
852 -echo ~g {getcurdirectory 1}
853 -echo ~l {getcurdirectory 0}
854 -echo ~p {putcurdirectory}
855 }
856
857 The -nobuffer flag sends characters that match the following pat‐
858 tern on to the output process as characters are read.
859
860 This is useful when you wish to let a program echo back the pat‐
861 tern. For example, the following might be used to monitor where
862 a person is dialing (a Hayes-style modem). Each time "atd" is
863 seen the script logs the rest of the line.
864
865 proc lognumber {} {
866 interact -nobuffer -re "(.*)\r" return
867 puts $log "[clock format [clock seconds]]: dialed $interact_out(1,string)"
868 }
869
870 interact -nobuffer "atd" lognumber
871
872
873 During interact, previous use of log_user is ignored. In partic‐
874 ular, interact will force its output to be logged (sent to the
875 standard output) since it is presumed the user doesn't wish to
876 interact blindly.
877
878 The -o flag causes any following key-body pairs to be applied to
879 the output of the current process. This can be useful, for exam‐
880 ple, when dealing with hosts that send unwanted characters during
881 a telnet session.
882
883 By default, interact expects the user to be writing stdin and
884 reading stdout of the Expect process itself. The -u flag (for
885 "user") makes interact look for the user as the process named by
886 its argument (which must be a spawned id).
887
888 This allows two unrelated processes to be joined together without
889 using an explicit loop. To aid in debugging, Expect diagnostics
890 always go to stderr (or stdout for certain logging and debugging
891 information). For the same reason, the interpreter command will
892 read interactively from stdin.
893
894 For example, the following fragment creates a login process.
895 Then it dials the user (not shown), and finally connects the two
896 together. Of course, any process may be substituted for login.
897 A shell, for example, would allow the user to work without sup‐
898 plying an account and password.
899
900 spawn login
901 set login $spawn_id
902 spawn tip modem
903 # dial back out to user
904 # connect user to login
905 interact -u $login
906
907 To send output to multiple processes, list each spawn id list
908 prefaced by a -output flag. Input for a group of output spawn
909 ids may be determined by a spawn id list prefaced by a -input
910 flag. (Both -input and -output may take lists in the same form
911 as the -i flag in the expect command, except that any_spawn_id is
912 not meaningful in interact.) All following flags and strings (or
913 patterns) apply to this input until another -input flag appears.
914 If no -input appears, -output implies "-input $user_spawn_id
915 -output". (Similarly, with patterns that do not have -input.)
916 If one -input is specified, it overrides $user_spawn_id. If a
917 second -input is specified, it overrides $spawn_id. Additional
918 -input flags may be specified.
919
920 The two implied input processes default to having their outputs
921 specified as $spawn_id and $user_spawn_id (in reverse). If a
922 -input flag appears with no -output flag, characters from that
923 process are discarded.
924
925 The -i flag introduces a replacement for the current spawn_id
926 when no other -input or -output flags are used. A -i flag
927 implies a -o flag.
928
929 It is possible to change the processes that are being interacted
930 with by using indirect spawn ids. (Indirect spawn ids are
931 described in the section on the expect command.) Indirect spawn
932 ids may be specified with the -i, -u, -input, or -output flags.
933
934 interpreter [args]
935 causes the user to be interactively prompted for Expect and Tcl
936 commands. The result of each command is printed.
937
938 Actions such as break and continue cause control structures
939 (i.e., for, proc) to behave in the usual way. However return
940 causes interpreter to return to its caller, while inter_return
941 causes interpreter to cause a return in its caller. For example,
942 if "proc foo" called interpreter which then executed the action
943 inter_return, proc foo would return. Any other command causes
944 interpreter to continue prompting for new commands.
945
946 By default, the prompt contains two integers. The first integer
947 describes the depth of the evaluation stack (i.e., how many times
948 Tcl_Eval has been called). The second integer is the Tcl history
949 identifier. The prompt can be set by defining a procedure called
950 "prompt1" whose return value becomes the next prompt. If a
951 statement has open quotes, parens, braces, or brackets, a sec‐
952 ondary prompt (by default "+> ") is issued upon newline. The
953 secondary prompt may be set by defining a procedure called
954 "prompt2".
955
956 During interpreter, cooked mode is used, even if the its caller
957 was using raw mode.
958
959 If stdin is closed, interpreter will return unless the -eof flag
960 is used, in which case the subsequent argument is invoked.
961
962 log_file [args] [[-a] file]
963 If a filename is provided, log_file will record a transcript of
964 the session (beginning at that point) in the file. log_file will
965 stop recording if no argument is given. Any previous log file is
966 closed.
967
968 Instead of a filename, a Tcl file identifier may be provided by
969 using the -open or -leaveopen flags. This is similar to the
970 spawn command. (See spawn for more info.)
971
972 The -a flag forces output to be logged that was suppressed by the
973 log_user command.
974
975 By default, the log_file command appends to old files rather than
976 truncating them, for the convenience of being able to turn log‐
977 ging off and on multiple times in one session. To truncate
978 files, use the -noappend flag.
979
980 The -info flag causes log_file to return a description of the
981 most recent non-info arguments given.
982
983 log_user -info|0|1
984 By default, the send/expect dialogue is logged to stdout (and a
985 logfile if open). The logging to stdout is disabled by the com‐
986 mand "log_user 0" and reenabled by "log_user 1". Logging to the
987 logfile is unchanged.
988
989 The -info flag causes log_user to return a description of the
990 most recent non-info arguments given.
991
992 match_max [-d] [-i spawn_id] [size]
993 defines the size of the buffer (in bytes) used internally by
994 expect. With no size argument, the current size is returned.
995
996 With the -d flag, the default size is set. (The initial default
997 is 2000.) With the -i flag, the size is set for the named spawn
998 id, otherwise it is set for the current process.
999
1000 overlay [-# spawn_id] [-# spawn_id] [...] program [args]
1001 executes program args in place of the current Expect program,
1002 which terminates. A bare hyphen argument forces a hyphen in
1003 front of the command name as if it was a login shell. All
1004 spawn_ids are closed except for those named as arguments. These
1005 are mapped onto the named file identifiers.
1006
1007 Spawn_ids are mapped to file identifiers for the new program to
1008 inherit. For example, the following line runs chess and allows
1009 it to be controlled by the current process - say, a chess master.
1010
1011 overlay -0 $spawn_id -1 $spawn_id -2 $spawn_id chess
1012
1013 This is more efficient than "interact -u", however, it sacrifices
1014 the ability to do programmed interaction since the Expect process
1015 is no longer in control.
1016
1017 Note that no controlling terminal is provided. Thus, if you dis‐
1018 connect or remap standard input, programs that do job control
1019 (shells, login, etc) will not function properly.
1020
1021 parity [-d] [-i spawn_id] [value]
1022 defines whether parity should be retained or stripped from the
1023 output of spawned processes. If value is zero, parity is
1024 stripped, otherwise it is not stripped. With no value argument,
1025 the current value is returned.
1026
1027 With the -d flag, the default parity value is set. (The initial
1028 default is 1, i.e., parity is not stripped.) With the -i flag,
1029 the parity value is set for the named spawn id, otherwise it is
1030 set for the current process.
1031
1032 remove_nulls [-d] [-i spawn_id] [value]
1033 defines whether nulls are retained or removed from the output of
1034 spawned processes before pattern matching or storing in the vari‐
1035 able expect_out or interact_out. If value is 1, nulls are
1036 removed. If value is 0, nulls are not removed. With no value
1037 argument, the current value is returned.
1038
1039 With the -d flag, the default value is set. (The initial default
1040 is 1, i.e., nulls are removed.) With the -i flag, the value is
1041 set for the named spawn id, otherwise it is set for the current
1042 process.
1043
1044 Whether or not nulls are removed, Expect will record null bytes
1045 to the log and stdout.
1046
1047 send [-flags] string
1048 Sends string to the current process. For example, the command
1049
1050 send "hello world\r"
1051
1052 sends the characters, h e l l o <blank> w o r l d <return> to the
1053 current process. (Tcl includes a printf-like command (called
1054 format) which can build arbitrarily complex strings.)
1055
1056 Characters are sent immediately although programs with line-
1057 buffered input will not read the characters until a return char‐
1058 acter is sent. A return character is denoted "\r".
1059
1060 The -- flag forces the next argument to be interpreted as a
1061 string rather than a flag. Any string can be preceded by "--"
1062 whether or not it actually looks like a flag. This provides a
1063 reliable mechanism to specify variable strings without being
1064 tripped up by those that accidentally look like flags. (All
1065 strings starting with "-" are reserved for future options.)
1066
1067 The -i flag declares that the string be sent to the named
1068 spawn_id. If the spawn_id is user_spawn_id, and the terminal is
1069 in raw mode, newlines in the string are translated to return-new‐
1070 line sequences so that they appear as if the terminal was in
1071 cooked mode. The -raw flag disables this translation.
1072
1073 The -null flag sends null characters (0 bytes). By default, one
1074 null is sent. An integer may follow the -null to indicate how
1075 many nulls to send.
1076
1077 The -break flag generates a break condition. This only makes
1078 sense if the spawn id refers to a tty device opened via "spawn
1079 -open". If you have spawned a process such as tip, you should
1080 use tip's convention for generating a break.
1081
1082 The -s flag forces output to be sent "slowly", thus avoid the
1083 common situation where a computer outtypes an input buffer that
1084 was designed for a human who would never outtype the same buffer.
1085 This output is controlled by the value of the variable
1086 "send_slow" which takes a two element list. The first element is
1087 an integer that describes the number of bytes to send atomically.
1088 The second element is a real number that describes the number of
1089 seconds by which the atomic sends must be separated. For exam‐
1090 ple, "set send_slow {10 .001}" would force "send -s" to send
1091 strings with 1 millisecond in between each 10 characters sent.
1092
1093 The -h flag forces output to be sent (somewhat) like a human
1094 actually typing. Human-like delays appear between the charac‐
1095 ters. (The algorithm is based upon a Weibull distribution, with
1096 modifications to suit this particular application.) This output
1097 is controlled by the value of the variable "send_human" which
1098 takes a five element list. The first two elements are average
1099 interarrival time of characters in seconds. The first is used by
1100 default. The second is used at word endings, to simulate the
1101 subtle pauses that occasionally occur at such transitions. The
1102 third parameter is a measure of variability where .1 is quite
1103 variable, 1 is reasonably variable, and 10 is quite invariable.
1104 The extremes are 0 to infinity. The last two parameters are,
1105 respectively, a minimum and maximum interarrival time. The mini‐
1106 mum and maximum are used last and "clip" the final time. The
1107 ultimate average can be quite different from the given average if
1108 the minimum and maximum clip enough values.
1109
1110 As an example, the following command emulates a fast and consis‐
1111 tent typist:
1112
1113 set send_human {.1 .3 1 .05 2}
1114 send -h "I'm hungry. Let's do lunch."
1115
1116 while the following might be more suitable after a hangover:
1117
1118 set send_human {.4 .4 .2 .5 100}
1119 send -h "Goodd party lash night!"
1120
1121 Note that errors are not simulated, although you can set up error
1122 correction situations yourself by embedding mistakes and correc‐
1123 tions in a send argument.
1124
1125 The flags for sending null characters, for sending breaks, for
1126 forcing slow output and for human-style output are mutually
1127 exclusive. Only the one specified last will be used. Furthermore,
1128 no string argument can be specified with the flags for sending
1129 null characters or breaks.
1130
1131 It is a good idea to precede the first send to a process by an
1132 expect. expect will wait for the process to start, while send
1133 cannot. In particular, if the first send completes before the
1134 process starts running, you run the risk of having your data
1135 ignored. In situations where interactive programs offer no ini‐
1136 tial prompt, you can precede send by a delay as in:
1137
1138 # To avoid giving hackers hints on how to break in,
1139 # this system does not prompt for an external password.
1140 # Wait for 5 seconds for exec to complete
1141 spawn telnet very.secure.gov
1142 sleep 5
1143 send password\r
1144
1145 exp_send is an alias for send. If you are using Expectk or some
1146 other variant of Expect in the Tk environment, send is defined by
1147 Tk for an entirely different purpose. exp_send is provided for
1148 compatibility between environments. Similar aliases are provided
1149 for other Expect's other send commands.
1150
1151 send_error [-flags] string
1152 is like send, except that the output is sent to stderr rather
1153 than the current process.
1154
1155 send_log [--] string
1156 is like send, except that the string is only sent to the log file
1157 (see log_file.) The arguments are ignored if no log file is
1158 open.
1159
1160 send_tty [-flags] string
1161 is like send, except that the output is sent to /dev/tty rather
1162 than the current process.
1163
1164 send_user [-flags] string
1165 is like send, except that the output is sent to stdout rather
1166 than the current process.
1167
1168 sleep seconds
1169 causes the script to sleep for the given number of seconds. Sec‐
1170 onds may be a decimal number. Interrupts (and Tk events if you
1171 are using Expectk) are processed while Expect sleeps.
1172
1173 spawn [args] program [args]
1174 creates a new process running program args. Its stdin, stdout
1175 and stderr are connected to Expect, so that they may be read and
1176 written by other Expect commands. The connection is broken by
1177 close or if the process itself closes any of the file identi‐
1178 fiers.
1179
1180 When a process is started by spawn, the variable spawn_id is set
1181 to a descriptor referring to that process. The process described
1182 by spawn_id is considered the current process. spawn_id may be
1183 read or written, in effect providing job control.
1184
1185 user_spawn_id is a global variable containing a descriptor which
1186 refers to the user. For example, when spawn_id is set to this
1187 value, expect behaves like expect_user.
1188
1189 error_spawn_id is a global variable containing a descriptor which
1190 refers to the standard error. For example, when spawn_id is set
1191 to this value, send behaves like send_error.
1192
1193 tty_spawn_id is a global variable containing a descriptor which
1194 refers to /dev/tty. If /dev/tty does not exist (such as in a
1195 cron, at, or batch script), then tty_spawn_id is not defined.
1196 This may be tested as:
1197
1198 if {[info vars tty_spawn_id]} {
1199 # /dev/tty exists
1200 } else {
1201 # /dev/tty doesn't exist
1202 # probably in cron, batch, or at script
1203 }
1204
1205
1206 spawn returns the UNIX process id. If no process is spawned, 0
1207 is returned. The variable spawn_out(slave,name) is set to the
1208 name of the pty slave device.
1209
1210 By default, spawn echoes the command name and arguments. The
1211 -noecho flag stops spawn from doing this.
1212
1213 The -console flag causes console output to be redirected to the
1214 spawned process. This is not supported on all systems.
1215
1216 Internally, spawn uses a pty, initialized the same way as the
1217 user's tty. This is further initialized so that all settings are
1218 "sane" (according to stty(1)). If the variable stty_init is
1219 defined, it is interpreted in the style of stty arguments as fur‐
1220 ther configuration. For example, "set stty_init raw" will cause
1221 further spawned processes's terminals to start in raw mode.
1222 -nottycopy skips the initialization based on the user's tty.
1223 -nottyinit skips the "sane" initialization.
1224
1225 Normally, spawn takes little time to execute. If you notice
1226 spawn taking a significant amount of time, it is probably encoun‐
1227 tering ptys that are wedged. A number of tests are run on ptys
1228 to avoid entanglements with errant processes. (These take 10
1229 seconds per wedged pty.) Running Expect with the -d option will
1230 show if Expect is encountering many ptys in odd states. If you
1231 cannot kill the processes to which these ptys are attached, your
1232 only recourse may be to reboot.
1233
1234 If program cannot be spawned successfully because exec(2) fails
1235 (e.g. when program doesn't exist), an error message will be
1236 returned by the next interact or expect command as if program had
1237 run and produced the error message as output. This behavior is a
1238 natural consequence of the implementation of spawn. Internally,
1239 spawn forks, after which the spawned process has no way to commu‐
1240 nicate with the original Expect process except by communication
1241 via the spawn_id.
1242
1243 The -open flag causes the next argument to be interpreted as a
1244 Tcl file identifier (i.e., returned by open.) The spawn id can
1245 then be used as if it were a spawned process. (The file identi‐
1246 fier should no longer be used.) This lets you treat raw devices,
1247 files, and pipelines as spawned processes without using a pty. 0
1248 is returned to indicate there is no associated process. When the
1249 connection to the spawned process is closed, so is the Tcl file
1250 identifier. The -leaveopen flag is similar to -open except that
1251 -leaveopen causes the file identifier to be left open even after
1252 the spawn id is closed.
1253
1254 The -pty flag causes a pty to be opened but no process spawned.
1255 0 is returned to indicate there is no associated process.
1256 Spawn_id is set as usual.
1257
1258 The variable spawn_out(slave,fd) is set to a file identifier cor‐
1259 responding to the pty slave. It can be closed using "close
1260 -slave".
1261
1262 The -ignore flag names a signal to be ignored in the spawned
1263 process. Otherwise, signals get the default behavior. Signals
1264 are named as in the trap command, except that each signal
1265 requires a separate flag.
1266
1267 strace level
1268 causes following statements to be printed before being executed.
1269 (Tcl's trace command traces variables.) level indicates how far
1270 down in the call stack to trace. For example, the following com‐
1271 mand runs Expect while tracing the first 4 levels of calls, but
1272 none below that.
1273
1274 expect -c "strace 4" script.exp
1275
1276
1277 The -info flag causes strace to return a description of the most
1278 recent non-info arguments given.
1279
1280 stty args
1281 changes terminal modes similarly to the external stty command.
1282
1283 By default, the controlling terminal is accessed. Other termi‐
1284 nals can be accessed by appending "< /dev/tty..." to the command.
1285 (Note that the arguments should not be grouped into a single
1286 argument.)
1287
1288 Requests for status return it as the result of the command. If
1289 no status is requested and the controlling terminal is accessed,
1290 the previous status of the raw and echo attributes are returned
1291 in a form which can later be used by the command.
1292
1293 For example, the arguments raw or -cooked put the terminal into
1294 raw mode. The arguments -raw or cooked put the terminal into
1295 cooked mode. The arguments echo and -echo put the terminal into
1296 echo and noecho mode respectively.
1297
1298 The following example illustrates how to temporarily disable
1299 echoing. This could be used in otherwise-automatic scripts to
1300 avoid embedding passwords in them. (See more discussion on this
1301 under EXPECT HINTS below.)
1302
1303 stty -echo
1304 send_user "Password: "
1305 expect_user -re "(.*)\n"
1306 set password $expect_out(1,string)
1307 stty echo
1308
1309
1310 system args
1311 gives args to sh(1) as input, just as if it had been typed as a
1312 command from a terminal. Expect waits until the shell termi‐
1313 nates. The return status from sh is handled the same way that
1314 exec handles its return status.
1315
1316 In contrast to exec which redirects stdin and stdout to the
1317 script, system performs no redirection (other than that indicated
1318 by the string itself). Thus, it is possible to use programs
1319 which must talk directly to /dev/tty. For the same reason, the
1320 results of system are not recorded in the log.
1321
1322 timestamp [args]
1323 returns a timestamp. With no arguments, the number of seconds
1324 since the epoch is returned.
1325
1326 The -format flag introduces a string which is returned but with
1327 substitutions made according to the POSIX rules for strftime.
1328 For example %a is replaced by an abbreviated weekday name (i.e.,
1329 Sat). Others are:
1330 %a abbreviated weekday name
1331 %A full weekday name
1332 %b abbreviated month name
1333 %B full month name
1334 %c date-time as in: Wed Oct 6 11:45:56 1993
1335 %d day of the month (01-31)
1336 %H hour (00-23)
1337 %I hour (01-12)
1338 %j day (001-366)
1339 %m month (01-12)
1340 %M minute (00-59)
1341 %p am or pm
1342 %S second (00-61)
1343 %u day (1-7, Monday is first day of week)
1344 %U week (00-53, first Sunday is first day of week one)
1345 %V week (01-53, ISO 8601 style)
1346 %w day (0-6)
1347 %W week (00-53, first Monday is first day of week one)
1348 %x date-time as in: Wed Oct 6 1993
1349 %X time as in: 23:59:59
1350 %y year (00-99)
1351 %Y year as in: 1993
1352 %Z timezone (or nothing if not determinable)
1353 %% a bare percent sign
1354
1355 Other % specifications are undefined. Other characters will be
1356 passed through untouched. Only the C locale is supported.
1357
1358 The -seconds flag introduces a number of seconds since the epoch
1359 to be used as a source from which to format. Otherwise, the cur‐
1360 rent time is used.
1361
1362 The -gmt flag forces timestamp output to use the GMT timezone.
1363 With no flag, the local timezone is used.
1364
1365 trap [[command] signals]
1366 causes the given command to be executed upon future receipt of
1367 any of the given signals. The command is executed in the global
1368 scope. If command is absent, the signal action is returned. If
1369 command is the string SIG_IGN, the signals are ignored. If com‐
1370 mand is the string SIG_DFL, the signals are result to the system
1371 default. signals is either a single signal or a list of signals.
1372 Signals may be specified numerically or symbolically as per sig‐
1373 nal(3). The "SIG" prefix may be omitted.
1374
1375 With no arguments (or the argument -number), trap returns the
1376 signal number of the trap command currently being executed.
1377
1378 The -code flag uses the return code of the command in place of
1379 whatever code Tcl was about to return when the command originally
1380 started running.
1381
1382 The -interp flag causes the command to be evaluated using the
1383 interpreter active at the time the command started running rather
1384 than when the trap was declared.
1385
1386 The -name flag causes the trap command to return the signal name
1387 of the trap command currently being executed.
1388
1389 The -max flag causes the trap command to return the largest sig‐
1390 nal number that can be set.
1391
1392 For example, the command "trap {send_user "Ouch!"} SIGINT" will
1393 print "Ouch!" each time the user presses ^C.
1394
1395 By default, SIGINT (which can usually be generated by pressing
1396 ^C) and SIGTERM cause Expect to exit. This is due to the follow‐
1397 ing trap, created by default when Expect starts.
1398
1399 trap exit {SIGINT SIGTERM}
1400
1401 If you use the -D flag to start the debugger, SIGINT is redefined
1402 to start the interactive debugger. This is due to the following
1403 trap:
1404
1405 trap {exp_debug 1} SIGINT
1406
1407 The debugger trap can be changed by setting the environment vari‐
1408 able EXPECT_DEBUG_INIT to a new trap command.
1409
1410 You can, of course, override both of these just by adding trap
1411 commands to your script. In particular, if you have your own
1412 "trap exit SIGINT", this will override the debugger trap. This
1413 is useful if you want to prevent users from getting to the debug‐
1414 ger at all.
1415
1416 If you want to define your own trap on SIGINT but still trap to
1417 the debugger when it is running, use:
1418
1419 if {![exp_debug]} {trap mystuff SIGINT}
1420
1421 Alternatively, you can trap to the debugger using some other sig‐
1422 nal.
1423
1424 trap will not let you override the action for SIGALRM as this is
1425 used internally to Expect. The disconnect command sets SIGALRM
1426 to SIG_IGN (ignore). You can reenable this as long as you dis‐
1427 able it during subsequent spawn commands.
1428
1429 See signal(3) for more info.
1430
1431 wait [args]
1432 delays until a spawned process (or the current process if none is
1433 named) terminates.
1434
1435 wait normally returns a list of four integers. The first integer
1436 is the pid of the process that was waited upon. The second inte‐
1437 ger is the corresponding spawn id. The third integer is -1 if an
1438 operating system error occurred, or 0 otherwise. If the third
1439 integer was 0, the fourth integer is the status returned by the
1440 spawned process. If the third integer was -1, the fourth integer
1441 is the value of errno set by the operating system. The global
1442 variable errorCode is also set.
1443
1444 Additional elements may appear at the end of the return value
1445 from wait. An optional fifth element identifies a class of
1446 information. Currently, the only possible value for this element
1447 is CHILDKILLED in which case the next two values are the C-style
1448 signal name and a short textual description.
1449
1450 The -i flag declares the process to wait corresponding to the
1451 named spawn_id (NOT the process id). Inside a SIGCHLD handler,
1452 it is possible to wait for any spawned process by using the spawn
1453 id -1.
1454
1455 The -nowait flag causes the wait to return immediately with the
1456 indication of a successful wait. When the process exits (later),
1457 it will automatically disappear without the need for an explicit
1458 wait.
1459
1460 The wait command may also be used wait for a forked process using
1461 the arguments "-i -1". Unlike its use with spawned processes,
1462 this command can be executed at any time. There is no control
1463 over which process is reaped. However, the return value can be
1464 checked for the process id.
1465
1466
1468 Expect automatically knows about two built-in libraries for Expect
1469 scripts. These are defined by the directories named in the variables
1470 exp_library and exp_exec_library. Both are meant to contain utility
1471 files that can be used by other scripts.
1472
1473 exp_library contains architecture-independent files. exp_exec_library
1474 contains architecture-dependent files. Depending on your system, both
1475 directories may be totally empty. The existence of the file
1476 $exp_exec_library/cat-buffers describes whether your /bin/cat buffers
1477 by default.
1478
1480 A vgrind definition is available for pretty-printing Expect scripts.
1481 Assuming the vgrind definition supplied with the Expect distribution is
1482 correctly installed, you can use it as:
1483
1484 vgrind -lexpect file
1485
1486
1488 It many not be apparent how to put everything together that the man
1489 page describes. I encourage you to read and try out the examples in
1490 the example directory of the Expect distribution. Some of them are
1491 real programs. Others are simply illustrative of certain techniques,
1492 and of course, a couple are just quick hacks. The INSTALL file has a
1493 quick overview of these programs.
1494
1495 The Expect papers (see SEE ALSO) are also useful. While some papers
1496 use syntax corresponding to earlier versions of Expect, the accompany‐
1497 ing rationales are still valid and go into a lot more detail than this
1498 man page.
1499
1501 Extensions may collide with Expect's command names. For example, send
1502 is defined by Tk for an entirely different purpose. For this reason,
1503 most of the Expect commands are also available as "exp_XXXX". Commands
1504 and variables beginning with "exp", "inter", "spawn", and "timeout" do
1505 not have aliases. Use the extended command names if you need this com‐
1506 patibility between environments.
1507
1508 Expect takes a rather liberal view of scoping. In particular, vari‐
1509 ables read by commands specific to the Expect program will be sought
1510 first from the local scope, and if not found, in the global scope. For
1511 example, this obviates the need to place "global timeout" in every pro‐
1512 cedure you write that uses expect. On the other hand, variables writ‐
1513 ten are always in the local scope (unless a "global" command has been
1514 issued). The most common problem this causes is when spawn is executed
1515 in a procedure. Outside the procedure, spawn_id no longer exists, so
1516 the spawned process is no longer accessible simply because of scoping.
1517 Add a "global spawn_id" to such a procedure.
1518
1519 If you cannot enable the multispawning capability (i.e., your system
1520 supports neither select (BSD *.*), poll (SVR>2), nor something equiva‐
1521 lent), Expect will only be able to control a single process at a time.
1522 In this case, do not attempt to set spawn_id, nor should you execute
1523 processes via exec while a spawned process is running. Furthermore,
1524 you will not be able to expect from multiple processes (including the
1525 user as one) at the same time.
1526
1527 Terminal parameters can have a big effect on scripts. For example, if
1528 a script is written to look for echoing, it will misbehave if echoing
1529 is turned off. For this reason, Expect forces sane terminal parameters
1530 by default. Unfortunately, this can make things unpleasant for other
1531 programs. As an example, the emacs shell wants to change the "usual"
1532 mappings: newlines get mapped to newlines instead of carriage-return
1533 newlines, and echoing is disabled. This allows one to use emacs to
1534 edit the input line. Unfortunately, Expect cannot possibly guess this.
1535
1536 You can request that Expect not override its default setting of termi‐
1537 nal parameters, but you must then be very careful when writing scripts
1538 for such environments. In the case of emacs, avoid depending upon
1539 things like echoing and end-of-line mappings.
1540
1541 The commands that accepted arguments braced into a single list (the
1542 expect variants and interact) use a heuristic to decide if the list is
1543 actually one argument or many. The heuristic can fail only in the case
1544 when the list actually does represent a single argument which has mul‐
1545 tiple embedded \n's with non-whitespace characters between them. This
1546 seems sufficiently improbable, however the argument "-nobrace" can be
1547 used to force a single argument to be handled as a single argument.
1548 This could conceivably be used with machine-generated Expect code.
1549 Similarly, -brace forces a single argument to be handle as multiple
1550 patterns/actions.
1551
1552
1554 It was really tempting to name the program "sex" (for either "Smart
1555 EXec" or "Send-EXpect"), but good sense (or perhaps just Puritanism)
1556 prevailed.
1557
1558 On some systems, when a shell is spawned, it complains about not being
1559 able to access the tty but runs anyway. This means your system has a
1560 mechanism for gaining the controlling tty that Expect doesn't know
1561 about. Please find out what it is, and send this information back to
1562 me.
1563
1564 Ultrix 4.1 (at least the latest versions around here) considers time‐
1565 outs of above 1000000 to be equivalent to 0.
1566
1567 Digital UNIX 4.0A (and probably other versions) refuses to allocate
1568 ptys if you define a SIGCHLD handler. See grantpt page for more info.
1569
1570 IRIX 6.0 does not handle pty permissions correctly so that if Expect
1571 attempts to allocate a pty previously used by someone else, it fails.
1572 Upgrade to IRIX 6.1.
1573
1574 Telnet (verified only under SunOS 4.1.2) hangs if TERM is not set.
1575 This is a problem under cron, at and in cgi scripts, which do not
1576 define TERM. Thus, you must set it explicitly - to what type is usu‐
1577 ally irrelevant. It just has to be set to something! The following
1578 probably suffices for most cases.
1579
1580 set env(TERM) vt100
1581
1582
1583 Tip (verified only under BSDI BSD/OS 3.1 i386) hangs if SHELL and HOME
1584 are not set. This is a problem under cron, at and in cgi scripts,
1585 which do not define these environment variables. Thus, you must set
1586 them explicitly - to what type is usually irrelevant. It just has to
1587 be set to something! The following probably suffices for most cases.
1588
1589 set env(SHELL) /bin/sh
1590 set env(HOME) /usr/local/bin
1591
1592
1593
1594 Some implementations of ptys are designed so that the kernel throws
1595 away any unread output after 10 to 15 seconds (actual number is imple‐
1596 mentation-dependent) after the process has closed the file descriptor.
1597 Thus Expect programs such as
1598
1599 spawn date
1600 sleep 20
1601 expect
1602
1603 will fail. To avoid this, invoke non-interactive programs with exec
1604 rather than spawn. While such situations are conceivable, in practice
1605 I have never encountered a situation in which the final output of a
1606 truly interactive program would be lost due to this behavior.
1607
1608 On the other hand, Cray UNICOS ptys throw away any unread output imme‐
1609 diately after the process has closed the file descriptor. I have
1610 reported this to Cray and they are working on a fix.
1611
1612 Sometimes a delay is required between a prompt and a response, such as
1613 when a tty interface is changing UART settings or matching baud rates
1614 by looking for start/stop bits. Usually, all this is require is to
1615 sleep for a second or two. A more robust technique is to retry until
1616 the hardware is ready to receive input. The following example uses
1617 both strategies:
1618
1619 send "speed 9600\r";
1620 sleep 1
1621 expect {
1622 timeout {send "\r"; exp_continue}
1623 $prompt
1624 }
1625
1626
1627 trap -code will not work with any command that sits in Tcl's event
1628 loop, such as sleep. The problem is that in the event loop, Tcl dis‐
1629 cards the return codes from async event handlers. A workaround is to
1630 set a flag in the trap code. Then check the flag immediately after the
1631 command (i.e., sleep).
1632
1633 The expect_background command ignores -timeout arguments and has no
1634 concept of timeouts in general.
1635
1636
1638 There are a couple of things about Expect that may be non-intuitive.
1639 This section attempts to address some of these things with a couple of
1640 suggestions.
1641
1642 A common expect problem is how to recognize shell prompts. Since these
1643 are customized differently by differently people and different shells,
1644 portably automating rlogin can be difficult without knowing the prompt.
1645 A reasonable convention is to have users store a regular expression
1646 describing their prompt (in particular, the end of it) in the environ‐
1647 ment variable EXPECT_PROMPT. Code like the following can be used. If
1648 EXPECT_PROMPT doesn't exist, the code still has a good chance of func‐
1649 tioning correctly.
1650
1651 set prompt "(%|#|\\$) $" ;# default prompt
1652 catch {set prompt $env(EXPECT_PROMPT)}
1653
1654 expect -re $prompt
1655
1656 I encourage you to write expect patterns that include the end of what‐
1657 ever you expect to see. This avoids the possibility of answering a
1658 question before seeing the entire thing. In addition, while you may
1659 well be able to answer questions before seeing them entirely, if you
1660 answer early, your answer may appear echoed back in the middle of the
1661 question. In other words, the resulting dialogue will be correct but
1662 look scrambled.
1663
1664 Most prompts include a space character at the end. For example, the
1665 prompt from ftp is 'f', 't', 'p', '>' and <blank>. To match this
1666 prompt, you must account for each of these characters. It is a common
1667 mistake not to include the blank. Put the blank in explicitly.
1668
1669 If you use a pattern of the form X*, the * will match all the output
1670 received from the end of X to the last thing received. This sounds
1671 intuitive but can be somewhat confusing because the phrase "last thing
1672 received" can vary depending upon the speed of the computer and the
1673 processing of I/O both by the kernel and the device driver.
1674
1675 In particular, humans tend to see program output arriving in huge
1676 chunks (atomically) when in reality most programs produce output one
1677 line at a time. Assuming this is the case, the * in the pattern of the
1678 previous paragraph may only match the end of the current line even
1679 though there seems to be more, because at the time of the match that
1680 was all the output that had been received.
1681
1682 expect has no way of knowing that further output is coming unless your
1683 pattern specifically accounts for it.
1684
1685 Even depending on line-oriented buffering is unwise. Not only do pro‐
1686 grams rarely make promises about the type of buffering they do, but
1687 system indigestion can break output lines up so that lines break at
1688 seemingly random places. Thus, if you can express the last few charac‐
1689 ters of a prompt when writing patterns, it is wise to do so.
1690
1691 If you are waiting for a pattern in the last output of a program and
1692 the program emits something else instead, you will not be able to
1693 detect that with the timeout keyword. The reason is that expect will
1694 not timeout - instead it will get an eof indication. Use that instead.
1695 Even better, use both. That way if that line is ever moved around, you
1696 won't have to edit the line itself.
1697
1698 Newlines are usually converted to carriage return, linefeed sequences
1699 when output by the terminal driver. Thus, if you want a pattern that
1700 explicitly matches the two lines, from, say, printf("foo\nbar"), you
1701 should use the pattern "foo\r\nbar".
1702
1703 A similar translation occurs when reading from the user, via
1704 expect_user. In this case, when you press return, it will be trans‐
1705 lated to a newline. If Expect then passes that to a program which sets
1706 its terminal to raw mode (like telnet), there is going to be a problem,
1707 as the program expects a true return. (Some programs are actually for‐
1708 giving in that they will automatically translate newlines to returns,
1709 but most don't.) Unfortunately, there is no way to find out that a
1710 program put its terminal into raw mode.
1711
1712 Rather than manually replacing newlines with returns, the solution is
1713 to use the command "stty raw", which will stop the translation. Note,
1714 however, that this means that you will no longer get the cooked line-
1715 editing features.
1716
1717 interact implicitly sets your terminal to raw mode so this problem will
1718 not arise then.
1719
1720 It is often useful to store passwords (or other private information) in
1721 Expect scripts. This is not recommended since anything that is stored
1722 on a computer is susceptible to being accessed by anyone. Thus, inter‐
1723 actively prompting for passwords from a script is a smarter idea than
1724 embedding them literally. Nonetheless, sometimes such embedding is the
1725 only possibility.
1726
1727 Unfortunately, the UNIX file system has no direct way of creating
1728 scripts which are executable but unreadable. Systems which support
1729 setgid shell scripts may indirectly simulate this as follows:
1730
1731 Create the Expect script (that contains the secret data) as usual.
1732 Make its permissions be 750 (-rwxr-x---) and owned by a trusted group,
1733 i.e., a group which is allowed to read it. If necessary, create a new
1734 group for this purpose. Next, create a /bin/sh script with permissions
1735 2751 (-rwxr-s--x) owned by the same group as before.
1736
1737 The result is a script which may be executed (and read) by anyone.
1738 When invoked, it runs the Expect script.
1739
1741 Tcl(3), libexpect(3)
1742 "Exploring Expect: A Tcl-Based Toolkit for Automating Interactive Pro‐
1743 grams" by Don Libes, pp. 602, ISBN 1-56592-090-2, O'Reilly and Asso‐
1744 ciates, 1995.
1745 "expect: Curing Those Uncontrollable Fits of Interactivity" by Don
1746 Libes, Proceedings of the Summer 1990 USENIX Conference, Anaheim, Cali‐
1747 fornia, June 11-15, 1990.
1748 "Using expect to Automate System Administration Tasks" by Don Libes,
1749 Proceedings of the 1990 USENIX Large Installation Systems Administra‐
1750 tion Conference, Colorado Springs, Colorado, October 17-19, 1990.
1751 "Tcl: An Embeddable Command Language" by John Ousterhout, Proceedings
1752 of the Winter 1990 USENIX Conference, Washington, D.C., January 22-26,
1753 1990.
1754 "expect: Scripts for Controlling Interactive Programs" by Don Libes,
1755 Computing Systems, Vol. 4, No. 2, University of California Press Jour‐
1756 nals, November 1991.
1757 "Regression Testing and Conformance Testing Interactive Programs", by
1758 Don Libes, Proceedings of the Summer 1992 USENIX Conference, pp.
1759 135-144, San Antonio, TX, June 12-15, 1992.
1760 "Kibitz - Connecting Multiple Interactive Programs Together", by Don
1761 Libes, Software - Practice & Experience, John Wiley & Sons, West Sus‐
1762 sex, England, Vol. 23, No. 5, May, 1993.
1763 "A Debugger for Tcl Applications", by Don Libes, Proceedings of the
1764 1993 Tcl/Tk Workshop, Berkeley, CA, June 10-11, 1993.
1765
1767 Don Libes, National Institute of Standards and Technology
1768
1770 Thanks to John Ousterhout for Tcl, and Scott Paisley for inspiration.
1771 Thanks to Rob Savoye for Expect's autoconfiguration code.
1772
1773 The HISTORY file documents much of the evolution of expect. It makes
1774 interesting reading and might give you further insight to this soft‐
1775 ware. Thanks to the people mentioned in it who sent me bug fixes and
1776 gave other assistance.
1777
1778 Design and implementation of Expect was paid for in part by the U.S.
1779 government and is therefore in the public domain. However the author
1780 and NIST would like credit if this program and documentation or por‐
1781 tions of them are used.
1782
1783
1784
1785 29 December 1994 EXPECT(1)