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