1 .TH EXPECT 1 "29 December 1994"
3 expect \- programmed dialogue with interactive programs, Version 5
24 is a program that "talks" to other interactive programs according to a
25 script. Following the script,
27 knows what can be expected from
28 a program and what the correct response should be. An interpreted
29 language provides branching and high-level control structures to
30 direct the dialogue. In addition, the user can take control
31 and interact directly when desired, afterward returning control to the
45 can also be used directly in C or C++ (that is, without Tcl).
48 The name "Expect" comes from the idea of
51 by uucp, kermit and other modem control programs.
54 is generalized so that it can be run as a user-level command
55 with any program and task in mind.
57 can actually talk to several programs at the same time.
59 For example, here are some things
65 Cause your computer to dial you back,
66 so that you can login without paying for the call.
69 Start a game (e.g., rogue) and if the optimal configuration doesn't appear,
70 restart it (again and again) until it does,
71 then hand over control to you.
74 Run fsck, and in response to its questions, answer "yes", "no" or give control back to you,
75 based on predetermined criteria.
78 Connect to another network or BBS (e.g., MCI Mail, CompuServe) and
79 automatically retrieve your mail so that it appears as if
80 it was originally sent to your local system.
83 Carry environment variables, current directory,
84 or any kind of information across rlogin, telnet, tip, su, chgrp, etc.
87 There are a variety of reasons why the shell cannot perform these tasks.
94 is useful for running any program which requires
95 interaction between the program and the user.
96 All that is necessary is that the interaction can be characterized
99 can also give the user back control
100 (without halting the program being controlled) if desired.
101 Similarly, the user can return control to the script at any time.
106 for a list of commands to execute.
108 may also be invoked implicitly on systems which support the #! notation
109 by marking the script executable, and making the first line in your script:
111 #!/usr/local/bin/expect \-f
113 Of course, the path must accurately describe where
115 lives. /usr/local/bin is just an example.
119 flag prefaces a command to be executed before any in the script.
120 The command should be quoted to prevent being broken up by the shell.
121 This option may be used multiple times.
122 Multiple commands may be
123 executed with a single
125 by separating them with semicolons.
126 Commands are executed in the order they appear.
127 (When using Expectk, this option is specified as
132 flag enables some diagnostic output, which
133 primarily reports internal activity of commands such as
137 This flag has the same effect as "exp_internal 1" at the beginning of an Expect
138 script, plus the version of
143 command is useful for tracing statements, and the
145 command is useful for tracing variable assignments.)
146 (When using Expectk, this option is specified as
151 flag enables an interactive debugger. An integer value should follow.
152 The debugger will take control before the next Tcl procedure
153 if the value is non-zero
154 or if a ^C is pressed (or a breakpoint is hit, or other appropriate debugger
155 command appears in the script). See the README file or SEE ALSO (below)
156 for more information on the debugger.
157 (When using Expectk, this option is specified as
162 flag prefaces a file from which to read commands from.
163 The flag itself is optional as it is only useful when using
164 the #! notation (see above),
165 so that other arguments may be supplied on the command line.
166 (When using Expectk, this option is specified as
169 By default, the command file is read into memory and executed in its entirety.
170 It is occasionally desirable to read files one line at a time. For example,
171 stdin is read this way. In order to force arbitrary files to be handled this
175 (When using Expectk, this option is specified as
176 .BR \-buffer .) Note that stdio-buffering may still take place however this shouldn't cause problems when reading from a fifo or stdin.
178 If the string "\-" is supplied as a filename, standard input is read instead.
179 (Use "./\-" to read from a file actually named "\-".)
185 to interactively prompt for commands instead of reading
187 Prompting is terminated via the
192 (below) for more information.
194 is assumed if neither a command file nor
197 (When using Expectk, this option is specified as
201 may be used to delimit the end of the options. This is useful if
202 you want to pass an option-like argument to your script without it being
205 This can usefully be placed in the #! line to prevent any flag-like
206 interpretation by Expect. For example, the following will leave the
207 original arguments (including the script name) in the variable
210 #!/usr/local/bin/expect \-\-
212 Note that the usual getopt(3) and execve(2) conventions must be observed
213 when adding arguments to the #! line.
215 The file $exp_library/expect.rc is sourced automatically if present, unless
219 (When using Expectk, this option is specified as
221 Immediately after this,
222 the file ~/.expect.rc is sourced automatically, unless the
224 flag is used. If the environment variable DOTDIR is defined,
225 it is treated as a directory and .expect.rc is read from there.
226 (When using Expectk, this option is specified as
228 This sourcing occurs only after executing any
233 causes Expect to print its version number and exit. (The corresponding flag
234 in Expectk, which uses long flag names, is \-version.)
238 are constructed into a list and stored in the variable named
241 is initialized to the length of argv.
244 is defined to be the name of the script (or binary if no script is used).
246 the following prints out the name of the script and the first three arguments:
249 send_user "$argv0 [lrange $argv 0 2]\\n"
256 (Tool Command Language).
257 Tcl provides control flow (e.g., if, for, break),
258 expression evaluation and several other features such as recursion,
259 procedure definition, etc.
260 Commands used here but not defined (e.g.,
264 are Tcl commands (see tcl(3)).
266 supports additional commands, described below.
267 Unless otherwise specified, commands return the empty string.
269 Commands are listed alphabetically so that they can be quickly located.
270 However, new users may find it easier to start by reading the descriptions
279 Note that the best introduction to the language (both Expect and Tcl)
280 is provided in the book "Exploring Expect" (see SEE ALSO below).
281 Examples are included in this man page but they are very limited since
282 this man page is meant primarily as reference material.
284 Note that in the text of this man page, "Expect" with an uppercase "E"
287 program while "expect" with a lower-case "e" refers to the
294 .BI close " [-slave] [\-onexec 0|1] [\-i spawn_id]"
295 closes the connection to the current process.
296 Most interactive programs will detect EOF on their stdin and exit;
299 usually suffices to kill the process as well.
302 flag declares the process to close corresponding to the named spawn_id.
308 will detect when the current process exits and implicitly do a
310 But if you kill the process by, say, "exec kill $pid",
311 you will need to explicitly call
316 flag determines whether the spawn id will be closed in any new spawned
317 processes or if the process is overlayed. To leave a spawn id open,
318 use the value 0. A non-zero integer value will force the spawn closed
319 (the default) in any new processes.
323 flag closes the slave associated with the spawn id. (See "spawn -pty".)
324 When the connection is closed, the slave is automatically closed as
327 No matter whether the connection is closed implicitly or explicitly,
330 to clear up the corresponding kernel process slot.
334 since there is no guarantee that closing a process connection will cause
340 .BI debug " [[-now] 0|1]"
341 controls a Tcl debugger allowing you to step through statements, set
344 With no arguments, a 1 is returned if the debugger is not running, otherwise
347 With a 1 argument, the debugger is started. With a 0 argument, the
348 debugger is stopped. If a 1 argument is preceded by the
350 flag, the debugger is started immediately (i.e., in the middle of the
352 command itself). Otherwise, the debugger is started with the next
357 command does not change any traps. Compare this to starting Expect with the
361 See the README file or SEE ALSO (below)
362 for more information on the debugger.
365 disconnects a forked process from the terminal. It continues running in the
366 background. The process is given its own process group (if possible).
367 Standard I/O is redirected to /dev/null.
369 The following fragment uses
371 to continue running the script in the background.
379 The following script reads a password, and then runs a program
380 every hour that demands a password each time it is run. The script supplies
381 the password so that you only have to type it once.
384 command which demonstrates how to turn off password echoing.)
387 send_user "password?\\ "
388 expect_user -re "(.*)\\n"
390 if {[fork]!=0} {sleep 3600;continue}
394 send "$expect_out(1,string)\\r"
400 An advantage to using
402 over the shell asynchronous process feature (&) is that
405 save the terminal parameters prior to disconnection, and then later
406 apply them to new ptys. With &,
408 does not have a chance
409 to read the terminal's parameters since the terminal is already
410 disconnected by the time
414 .BI exit " [\-opts] [status]"
417 to exit or otherwise prepare to do so.
421 flag causes the next argument to be used as an exit handler.
422 Without an argument, the current exit handler is returned.
428 to prepare to exit but stop short of actually returning control to the
429 operating system. The user-defined exit handler is run as well as Expect's
430 own internal handlers.
431 No further Expect commands should be executed.
432 This is useful if you are running Expect with other Tcl extensions.
433 The current interpreter (and main window if in the Tk environment) remain
434 so that other Tcl extensions can clean up. If Expect's
436 is called again (however this might occur), the handlers are not rerun.
439 all connections to spawned processes are closed. Closure will be detected
440 as an EOF by spawned processes.
442 takes no other actions beyond what the normal _exit(2) procedure does.
443 Thus, spawned processes that do not check for EOF may continue to run.
444 (A variety of conditions are important to determining, for example, what
445 signals a spawned process will be sent, but these are system-dependent,
446 typically documented under exit(3).)
447 Spawned processes that continue to run will be inherited by init.
450 (or 0 if not specified) is returned as the exit status of
453 is implicitly executed if the end of the script is reached.
455 \fBexp_continue\fR [-continue_timer]
461 executing rather than returning as it normally would. By
464 resets the timeout timer. The
466 flag prevents timer from being restarted. (See
468 for more information.)
470 .BI exp_internal " [\-f file] value"
471 causes further commands to send diagnostic information internal to
475 is non-zero. This output is disabled if
477 is 0. The diagnostic information includes every character received,
478 and every attempt made to match the current output against the patterns.
482 is supplied, all normal and debugging output is written to that file
483 (regardless of the value of
485 Any previous diagnostic output file is closed.
489 flag causes exp_internal to return a description of the
490 most recent non-info arguments given.
492 .BI exp_open " [args] [\-i spawn_id]"
493 returns a Tcl file identifier that corresponds to the original spawn id.
494 The file identifier can then be used as if it were opened by Tcl's
496 command. (The spawn id should no longer be used. A
498 should not be executed.
502 flag leaves the spawn id open for access through
505 must be executed on the spawn id.
507 .BI exp_pid " [\-i spawn_id]"
508 returns the process id corresponding to the currently spawned process.
511 flag is used, the pid returned corresponds to that of the given spawn id.
533 .BI exp_version " [[\-exit] version]"
534 is useful for assuring that the script is compatible with the current
537 With no arguments, the current version of
539 is returned. This version
540 may then be encoded in your script. If you actually know that you are not
541 using features of recent versions, you can specify an earlier version.
543 Versions consist of three numbers separated by dots. First
544 is the major number. Scripts written for versions of
547 different major number will almost certainly not work.
549 returns an error if the major numbers do not match.
551 Second is the minor number. Scripts written for a version with a
552 greater minor number than the current version
553 may depend upon some new feature and might not run.
555 returns an error if the major numbers match, but the script minor number
556 is greater than that of the running
559 Third is a number that plays no part in the version comparison.
560 However, it is incremented when the
563 distribution is changed in any way, such as by additional documentation
564 or optimization. It is reset to 0 upon each new minor version.
570 prints an error and exits if the version is out of date.
572 .BI expect " [[\-opts] pat1 body1] ... [\-opts] patn [bodyn]"
573 waits until one of the patterns matches the output of a spawned process,
574 a specified time period has passed, or an end-of-file is seen.
575 If the final body is empty, it may be omitted.
577 Patterns from the most recent
579 command are implicitly used before any other patterns.
580 Patterns from the most recent
582 command are implicitly used after any other patterns.
584 If the arguments to the entire
586 statement require more than one line,
587 all the arguments may be "braced" into one so as to avoid terminating each
588 line with a backslash. In this one case, the usual Tcl substitutions will
589 occur despite the braces.
591 If a pattern is the keyword
593 the corresponding body is executed upon end-of-file.
594 If a pattern is the keyword
596 the corresponding body is executed upon timeout. If no timeout keyword
597 is used, an implicit null action is executed upon timeout.
598 The default timeout period is 10 seconds but may be set, for example to 30,
599 by the command "set timeout 30". An infinite timeout may be designated
601 If a pattern is the keyword
603 the corresponding body is executed upon either timeout or end-of-file.
605 If a pattern matches, then the corresponding body is executed.
607 returns the result of the body (or the empty string if no pattern matched).
608 In the event that multiple patterns match, the one appearing first is
609 used to select a body.
611 Each time new output arrives, it is compared to each pattern in the order
612 they are listed. Thus, you may test for absence of a match by making
613 the last pattern something guaranteed to appear, such as a prompt.
614 In situations where there is no prompt, you must use
616 (just like you would if you were interacting manually).
618 Patterns are specified in three ways. By default,
619 patterns are specified as with Tcl's
621 command. (Such patterns are also similar to C-shell regular expressions
622 usually referred to as "glob" patterns). The
625 be used to protect patterns that might otherwise match
628 Any pattern beginning with a "-" should be protected this way. (All strings
629 starting with "-" are reserved for future options.)
632 For example, the following fragment looks for a successful login.
635 is presumed to be a procedure defined elsewhere in the script.)
638 .ta \w' expect 'u +\w'invalid password 'u
640 busy {puts busy\\n ; exp_continue}
642 "invalid password" abort
648 Quotes are necessary on the fourth pattern since it contains a space, which
649 would otherwise separate the pattern from the action.
650 Patterns with the same action (such as the 3rd and 4th) require listing the
651 actions again. This can be avoid by using regexp-style patterns (see below).
652 More information on forming glob-style patterns can be found in the Tcl manual.
654 Regexp-style patterns follow the syntax defined by Tcl's
656 (short for "regular expression") command.
657 regexp patterns are introduced with the flag
659 The previous example can be rewritten using a regexp as:
662 .ta \w' expect 'u +\w'connected 'u
664 busy {puts busy\\n ; exp_continue}
665 \-re "failed|invalid password" abort
671 Both types of patterns are "unanchored". This means that patterns
672 do not have to match the entire string, but can begin and end the
673 match anywhere in the string (as long as everything else matches).
674 Use ^ to match the beginning of a string, and $ to match the end.
675 Note that if you do not wait for the end of a string, your responses
676 can easily end up in the middle of the string as they are echoed from
677 the spawned process. While still producing correct results, the output
678 can look unnatural. Thus, use of $ is encouraged if you can exactly
679 describe the characters at the end of a string.
681 Note that in many editors, the ^ and $ match the beginning and end of
682 lines respectively. However, because expect is not line oriented,
683 these characters match the beginning and end of the data (as opposed
684 to lines) currently in the expect matching buffer. (Also, see the
685 note below on "system indigestion.")
689 flag causes the pattern to be matched as an "exact" string. No
690 interpretation of *, ^, etc is made (although the usual Tcl
691 conventions must still be observed).
692 Exact patterns are always unanchored.
697 flag causes uppercase characters of the output to compare as if they were
698 lowercase characters. The pattern is not affected.
700 While reading output,
701 more than 2000 bytes can force earlier bytes to be "forgotten".
702 This may be changed with the function
704 (Note that excessively large values can slow down the pattern matcher.)
709 the corresponding body is executed if
711 bytes have been received and no other patterns have matched.
714 keyword is used, the forgotten characters are written to
721 and nulls are allowed (via the
723 command), the corresponding body is executed if a single ASCII
725 It is not possible to
726 match 0 bytes via glob or regexp patterns.
728 Upon matching a pattern (or eof or full_buffer),
729 any matching and previously unmatched output is saved in the variable
730 .IR expect_out(buffer) .
731 Up to 9 regexp substring matches are saved in the variables
732 .I expect_out(1,string)
734 .IR expect_out(9,string) .
737 flag is used before a pattern,
738 the starting and ending indices (in a form suitable for
741 10 strings are stored in the variables
742 .I expect_out(X,start)
745 where X is a digit, corresponds to the substring position in the buffer.
746 0 refers to strings which matched the entire pattern
747 and is generated for glob patterns as well as regexp patterns.
748 For example, if a process has produced output of "abcdefgh\\n", the result of:
754 is as if the following statements had executed:
757 set expect_out(0,string) cd
758 set expect_out(buffer) abcd
761 and "efgh\\n" is left in the output buffer.
762 If a process produced the output "abbbcabkkkka\\n", the result of:
765 expect \-indices \-re "b(b*).*(k+)"
768 is as if the following statements had executed:
771 set expect_out(0,start) 1
772 set expect_out(0,end) 10
773 set expect_out(0,string) bbbcabkkkk
774 set expect_out(1,start) 2
775 set expect_out(1,end) 3
776 set expect_out(1,string) bb
777 set expect_out(2,start) 10
778 set expect_out(2,end) 10
779 set expect_out(2,string) k
780 set expect_out(buffer) abbbcabkkkk
783 and "a\\n" is left in the output buffer. The pattern "*" (and -re ".*") will
784 flush the output buffer without reading any more output from the
787 Normally, the matched output is discarded from Expect's internal buffers.
788 This may be prevented by prefixing a pattern with the
790 flag. This flag is especially useful in experimenting (and can be
791 abbreviated to "-not" for convenience while experimenting).
793 The spawn id associated with the matching output (or eof or
794 full_buffer) is stored in
795 .IR expect_out(spawn_id) .
799 flag causes the current expect command to use the following value
800 as a timeout instead of using the value of the timeout variable.
803 patterns are matched against output from the current process, however the
805 flag declares the output from the named spawn_id list be matched against
806 any following patterns (up to the next
808 The spawn_id list should either be a whitespace separated list of spawn_ids
809 or a variable referring to such a list of spawn_ids.
811 For example, the following example waits for
812 "connected" from the current process, or "busy", "failed" or "invalid
813 password" from the spawn_id named by $proc2.
817 \-i $proc2 busy {puts busy\\n ; exp_continue}
818 \-re "failed|invalid password" abort
824 The value of the global variable
826 may be used to match patterns to any spawn_ids that are named
834 flag with no associated pattern (i.e., followed immediately
837 is made available to any other patterns
840 command associated with
845 flag may also name a global variable in which case the variable is read
846 for a list of spawn ids. The variable is reread whenever it changes.
847 This provides a way of changing the I/O source while the command is in
848 execution. Spawn ids provided this way are called "indirect" spawn ids.
854 cause control structures (i.e.,
857 to behave in the usual way.
863 executing rather than returning as it normally would.
865 This is useful for avoiding explicit loops or repeated expect statements.
866 The following example is part of a fragment to automate rlogin. The
868 avoids having to write a second
870 statement (to look for the prompt again) if the rlogin prompts for a password.
876 send_user "password (for $user) on $host: "
877 expect_user -re "(.*)\\n"
879 send "$expect_out(1,string)\\r"
883 send_user "invalid password or account\\n"
886 send_user "connection to $host timed out\\n"
890 "connection to host failed: $expect_out(buffer)"
896 For example, the following fragment might help a user guide
897 an interaction that is already totally automated. In this case, the terminal
898 is put into raw mode. If the user presses "+", a variable is incremented.
899 If "p" is pressed, several returns are sent to the process,
900 perhaps to poke it in some way, and "i" lets the user interact with the
901 process, effectively stealing away control from the script.
906 to continue pattern matching after executing the
913 "p" {send "\\r\\r\\r"; exp_continue}
914 "+" {incr foo; exp_continue}
915 "i" {interact; exp_continue}
923 resets the timeout timer. The timer is not restarted, if
929 .BI expect_after " [expect_args]"
930 works identically to the
932 except that if patterns from both
938 pattern is used. See the
940 command for more information.
942 .BI expect_background " [expect_args]"
943 takes the same arguments as
945 however it returns immediately.
946 Patterns are tested whenever new input arrives.
952 .BR expect_background
953 and are silently discarded.
966 actions are being evaluated, background processing for the same
967 spawn id is blocked. Background processing is unblocked when
968 the action completes. While background processing is blocked,
969 it is possible to do a (foreground)
971 on the same spawn id.
973 It is not possible to execute an
979 for a particular spawn id is deleted by
980 declaring a new expect_background with the same spawn id. Declaring
982 with no pattern removes the given spawn id
983 from the ability to match patterns in the background.
985 .BI expect_before " [expect_args]"
986 takes the same arguments as
988 however it returns immediately.
989 Pattern-action pairs from the most recent
991 with the same spawn id are implicitly added to any following
993 commands. If a pattern matches, it is treated as if it had been
996 command itself, and the associated body is executed in the context
1000 If patterns from both
1008 If no pattern is specified, the spawn id is not checked for any patterns.
1010 Unless overridden by a
1014 patterns match against the spawn id defined at the time that the
1016 command was executed (not when its pattern is matched).
1018 The \-info flag causes
1020 to return the current specifications of what patterns it will match.
1021 By default, it reports on the current spawn id. An optional spawn id specification may be given for information on that spawn id. For example
1024 expect_before -info -i $proc
1027 At most one spawn id specification may be given. The flag \-indirect
1028 suppresses direct spawn ids that come only from indirect specifications.
1030 Instead of a spawn id specification, the flag "-all" will cause
1031 "-info" to report on all spawn ids.
1033 The output of the \-info flag can be reused as the argument to expect_before.
1035 .BI expect_tty " [expect_args]"
1038 but it reads characters from /dev/tty (i.e. keystrokes from the user).
1039 By default, reading is performed in cooked mode.
1040 Thus, lines must end with a return in order for
1043 This may be changed via
1049 .BI expect_user " [expect_args]"
1052 but it reads characters from stdin (i.e. keystrokes from the user).
1053 By default, reading is performed in cooked mode.
1054 Thus, lines must end with a return in order for
1057 This may be changed via
1064 creates a new process. The new process is an exact copy of the current
1066 process. On success,
1068 returns 0 to the new (child) process and returns the process ID of the child
1069 process to the parent process.
1070 On failure (invariably due to lack of resources, e.g., swap space, memory),
1072 returns \-1 to the parent process, and no child process is created.
1074 Forked processes exit via the
1076 command, just like the original process.
1077 Forked processes are allowed to write to the log files. If you do not
1078 disable debugging or logging in most of the processes, the result can be
1081 Some pty implementations may be confused by multiple readers and writers,
1082 even momentarily. Thus, it is safest to
1084 before spawning processes.
1086 .BI interact " [string1 body1] ... [stringn [bodyn]]"
1087 gives control of the current process to the user, so that
1088 keystrokes are sent to the current process,
1089 and the stdout and stderr of the current process are returned.
1091 String-body pairs may be specified as arguments, in which case the
1092 body is executed when the corresponding string is entered. (By default, the
1093 string is not sent to the current process.) The
1095 command is assumed, if the final body is missing.
1097 If the arguments to the entire
1099 statement require more than one line,
1100 all the arguments may be "braced" into one so as to avoid terminating each
1101 line with a backslash. In this one case, the usual Tcl substitutions will
1102 occur despite the braces.
1104 For example, the following command runs interact with the following
1105 string-body pairs defined: When ^Z is pressed,
1110 flag restores the terminal modes.)
1111 When ^A is pressed, the user sees "you typed a control-A" and the
1112 process is sent a ^A. When $ is pressed, the user sees the date.
1115 exits. If "foo" is entered, the user sees "bar".
1116 When ~~ is pressed, the
1118 interpreter runs interactively.
1121 .ta \w' interact 'u +\w'$CTRLZ 'u +\w'{'u
1124 -reset $CTRLZ {exec kill \-STOP [pid]}
1125 \\001 {send_user "you typed a control\-A\\n";
1128 $ {send_user "The date is [clock format [clock seconds]]."}
1130 foo {send_user "bar"}
1136 In string-body pairs, strings are matched in the order they are listed
1137 as arguments. Strings that partially match are not sent to the
1138 current process in anticipation of the remainder coming. If
1139 characters are then entered such that there can no longer possibly be
1140 a match, only the part of the string will be sent to the process that cannot
1141 possibly begin another match. Thus, strings that are substrings of
1142 partial matches can match later, if the original strings that was attempting
1143 to be match ultimately fails.
1145 By default, string matching is exact with no wild cards. (In contrast,
1148 command uses glob-style patterns by default.) The
1150 flag may be used to protect patterns that might otherwise match
1152 flags from doing so.
1153 Any pattern beginning with a "-" should be protected this way. (All strings
1154 starting with "-" are reserved for future options.)
1158 flag forces the string to be interpreted as a regexp-style pattern. In this
1159 case, matching substrings are stored in the variable
1161 similarly to the way
1163 stores its output in the variable
1167 flag is similarly supported.
1171 introduces an action that is
1172 executed upon end-of-file. A separate
1174 pattern may also follow the
1176 flag in which case it is matched if an eof is detected while writing output.
1179 action is "return", so that
1181 simply returns upon any EOF.
1185 introduces a timeout (in seconds) and action that is executed
1186 after no characters have been read for a given time.
1189 pattern applies to the most recently specified process.
1190 There is no default timeout.
1191 The special variable "timeout" (used by the
1193 command) has no affect on this timeout.
1195 For example, the following statement could be used to autologout users who have
1196 not typed anything for an hour but who still get frequent system
1200 interact -input $user_spawn_id timeout 3600 return -output \\
1205 If the pattern is the keyword
1207 and nulls are allowed (via the
1209 command), the corresponding body is executed if a single ASCII
1211 It is not possible to
1212 match 0 bytes via glob or regexp patterns.
1214 Prefacing a pattern with the flag
1217 .I interact_out(spawn_id)
1218 to be set to the spawn_id which matched the pattern
1225 cause control structures (i.e.,
1228 to behave in the usual way.
1231 causes interact to return to its caller, while
1235 to cause a return in its caller. For example, if "proc foo" called
1237 which then executed the action
1240 would return. (This means that if
1244 interactively typing
1246 will cause the interact to continue, while
1248 will cause the interact to return to its caller.)
1252 raw mode is used so that all characters may be passed to the current process.
1253 If the current process does not catch job control signals,
1254 it will stop if sent a stop signal (by default ^Z).
1255 To restart it, send a continue signal (such as by "kill \-CONT <pid>").
1256 If you really want to send a SIGSTOP to such a process (by ^Z),
1257 consider spawning csh first and then running your program.
1258 On the other hand, if you want to send a SIGSTOP to
1260 itself, first call interpreter (perhaps by using an escape character), and then press ^Z.
1262 String-body pairs can be used as a shorthand for avoiding having
1263 to enter the interpreter and execute commands interactively. The previous
1264 terminal mode is used while the body of a string-body pair is being executed.
1266 For speed, actions execute in raw mode by default. The
1268 flag resets the terminal to the mode it had before
1270 was executed (invariably, cooked mode).
1271 Note that characters entered when the mode is being switched may be lost
1272 (an unfortunate feature of the terminal driver on some systems).
1273 The only reason to use
1276 depends on running in cooked mode.
1280 flag sends characters that match the following pattern back to the process
1281 that generated them as each character is read. This may be useful
1282 when the user needs to see feedback from partially typed patterns.
1284 If a pattern is being echoed but eventually fails to match,
1285 the characters are sent to the spawned process. If the spawned
1286 process then echoes them, the user will see the characters twice.
1288 is probably only appropriate in situations where the user is
1289 unlikely to not complete the pattern. For example, the following
1290 excerpt is from rftp, the recursive-ftp script, where the user is
1291 prompted to enter ~g, ~p, or ~l, to get, put, or list the current
1292 directory recursively. These are so far away from the normal ftp
1293 commands, that the user is unlikely to type ~ followed by anything
1294 else, except mistakenly, in which case, they'll probably just ignore
1299 -echo ~g {getcurdirectory 1}
1300 -echo ~l {getcurdirectory 0}
1301 -echo ~p {putcurdirectory}
1307 flag sends characters that match the following pattern on to
1308 the output process as characters are read.
1310 This is useful when you wish to let a program echo back the pattern.
1311 For example, the following might be used to monitor where a person is
1312 dialing (a Hayes-style modem). Each time "atd" is seen the script
1313 logs the rest of the line.
1317 interact -nobuffer -re "(.*)\\r" return
1318 puts $log "[clock format [clock seconds]]: dialed $interact_out(1,string)"
1321 interact -nobuffer "atd" lognumber
1329 is ignored. In particular,
1331 will force its output to be logged (sent to the standard output)
1332 since it is presumed the user doesn't wish to interact blindly.
1336 flag causes any following key-body pairs to be applied to the output of
1337 the current process.
1338 This can be useful, for example, when dealing with hosts that
1339 send unwanted characters during a telnet session.
1343 expects the user to be writing stdin and reading stdout of the
1349 flag (for "user") makes
1351 look for the user as the process named by its argument
1352 (which must be a spawned id).
1354 This allows two unrelated processes to be joined
1355 together without using an explicit loop. To aid in debugging, Expect
1356 diagnostics always go to stderr (or stdout for certain logging and
1357 debugging information). For the same reason, the
1359 command will read interactively from stdin.
1361 For example, the following fragment creates a login process.
1362 Then it dials the user (not shown), and finally connects the two together.
1363 Of course, any process may be substituted for login.
1364 A shell, for example, would allow the user to work without supplying an
1365 account and password.
1371 # dial back out to user
1372 # connect user to login
1376 To send output to multiple processes, list each spawn id list prefaced by a
1378 flag. Input for a group of output spawn ids may be determined
1379 by a spawn id list prefaced by a
1385 may take lists in the same form as the
1389 command, except that any_spawn_id is not meaningful in
1391 All following flags and
1392 strings (or patterns) apply to this input until another -input flag appears.
1397 implies "\-input $user_spawn_id \-output".
1398 (Similarly, with patterns that do not have
1402 is specified, it overrides $user_spawn_id. If a second
1405 it overrides $spawn_id. Additional
1407 flags may be specified.
1409 The two implied input processes default to having their outputs specified as
1410 $spawn_id and $user_spawn_id (in reverse).
1416 flag, characters from that process are discarded.
1420 flag introduces a replacement for the current spawn_id when no
1425 flags are used. A \-i flag implies a \-o flag.
1427 It is possible to change the processes that are being interacted with
1428 by using indirect spawn ids. (Indirect spawn ids are described in the
1429 section on the expect command.) Indirect spawn ids may be specified
1430 with the -i, -u, -input, or -output flags.
1432 .B interpreter " [args]"
1433 causes the user to be interactively prompted for
1436 The result of each command is printed.
1442 cause control structures (i.e.,
1445 to behave in the usual way.
1448 causes interpreter to return to its caller, while
1452 to cause a return in its caller. For example, if "proc foo" called
1454 which then executed the action
1458 Any other command causes
1460 to continue prompting for new commands.
1462 By default, the prompt contains two integers.
1463 The first integer describes the depth of
1464 the evaluation stack (i.e., how many times Tcl_Eval has been called). The
1465 second integer is the Tcl history identifier. The prompt can be set by
1466 defining a procedure called "prompt1" whose return value becomes the next
1467 prompt. If a statement has open quotes, parens, braces, or brackets, a
1468 secondary prompt (by default "+> ") is issued upon newline. The secondary
1469 prompt may be set by defining a procedure called "prompt2".
1473 cooked mode is used, even if the its caller was using raw mode.
1477 will return unless the
1479 flag is used, in which case the subsequent argument is invoked.
1481 .BI log_file " [args] [[\-a] file]"
1482 If a filename is provided,
1484 will record a transcript of the session (beginning at that point) in the file.
1486 will stop recording if no argument is given. Any previous log file is closed.
1488 Instead of a filename, a Tcl file identifier may be provided by using the
1492 flags. This is similar to the
1500 flag forces output to be logged that was suppressed by the
1508 to old files rather than truncating them,
1509 for the convenience of being able to turn logging off and on multiple
1510 times in one session.
1511 To truncate files, use the
1517 flag causes log_file to return a description of the
1518 most recent non-info arguments given.
1520 .BI log_user " -info|0|1"
1521 By default, the send/expect dialogue is logged to stdout
1522 (and a logfile if open).
1523 The logging to stdout is disabled by the command "log_user 0"
1524 and reenabled by "log_user 1". Logging to the logfile is unchanged.
1528 flag causes log_user to return a description of the
1529 most recent non-info arguments given.
1531 .BI match_max " [\-d] [\-i spawn_id] [size]"
1532 defines the size of the buffer (in bytes) used internally by
1536 argument, the current size is returned.
1540 flag, the default size is set. (The initial default is 2000.)
1543 flag, the size is set for the named spawn id, otherwise it is set for
1544 the current process.
1546 .BI overlay " [\-# spawn_id] [\-# spawn_id] [...] program [args]"
1549 in place of the current
1551 program, which terminates.
1552 A bare hyphen argument forces a hyphen in front of the command name as if
1553 it was a login shell.
1554 All spawn_ids are closed except for those named as arguments. These
1555 are mapped onto the named file identifiers.
1557 Spawn_ids are mapped to file identifiers for the new program to inherit.
1558 For example, the following line runs chess and allows it to be
1559 controlled by the current process \- say, a chess master.
1562 overlay \-0 $spawn_id \-1 $spawn_id \-2 $spawn_id chess
1565 This is more efficient than
1566 "interact \-u", however, it sacrifices the ability to do programmed
1567 interaction since the
1569 process is no longer in control.
1571 Note that no controlling terminal is provided. Thus, if you
1572 disconnect or remap standard input, programs that do
1573 job control (shells, login, etc) will not function properly.
1575 .BI parity " [\-d] [\-i spawn_id] [value]"
1576 defines whether parity should be retained or stripped from the output of
1577 spawned processes. If
1579 is zero, parity is stripped, otherwise it is not stripped.
1582 argument, the current value is returned.
1586 flag, the default parity value is set. (The initial default is 1, i.e.,
1587 parity is not stripped.)
1590 flag, the parity value is set for the named spawn id, otherwise it is set for
1591 the current process.
1593 .BI remove_nulls " [\-d] [\-i spawn_id] [value]"
1594 defines whether nulls are retained or removed from the output of
1595 spawned processes before pattern matching
1596 or storing in the variable
1602 is 1, nulls are removed. If
1604 is 0, nulls are not removed.
1607 argument, the current value is returned.
1611 flag, the default value is set. (The initial default is 1, i.e.,
1615 flag, the value is set for the named spawn id, otherwise it is set for
1616 the current process.
1618 Whether or not nulls are removed,
1620 will record null bytes to the log and stdout.
1622 .BI send " [\-flags] string"
1625 to the current process.
1626 For example, the command
1629 send "hello world\\r"
1632 sends the characters, h e l l o <blank> w o r l d <return> to the
1634 (Tcl includes a printf-like command (called
1636 which can build arbitrarily complex strings.)
1638 Characters are sent immediately although programs with line-buffered input
1639 will not read the characters until a return character is sent. A return
1640 character is denoted "\\r".
1644 flag forces the next argument to be interpreted as a string rather than a flag.
1645 Any string can be preceded by "\-\-" whether or not it actually looks
1646 like a flag. This provides a reliable mechanism to specify variable strings
1647 without being tripped up by those that accidentally look like flags.
1648 (All strings starting with "-" are reserved for future options.)
1652 flag declares that the string be sent to the named spawn_id.
1655 and the terminal is in raw mode, newlines in the string are translated
1657 sequences so that they appear as if the terminal was in cooked mode.
1660 flag disables this translation.
1664 flag sends null characters (0 bytes). By default, one null is sent.
1665 An integer may follow the
1667 to indicate how many nulls to send.
1671 flag generates a break condition. This only makes sense if the spawn
1672 id refers to a tty device opened via "spawn -open". If you have
1673 spawned a process such as tip, you should use tip's convention for
1678 flag forces output to be sent "slowly", thus avoid the common situation
1679 where a computer outtypes an input buffer that was designed for a
1680 human who would never outtype the same buffer. This output is
1681 controlled by the value of the variable "send_slow" which takes a two
1682 element list. The first element is an integer that describes the
1683 number of bytes to send atomically. The second element is a real
1684 number that describes the number of seconds by which the atomic sends
1685 must be separated. For example, "set send_slow {10 .001}" would force
1686 "send \-s" to send strings with 1 millisecond in between each 10
1691 flag forces output to be sent (somewhat) like a human actually typing.
1692 Human-like delays appear between the characters. (The algorithm is
1693 based upon a Weibull distribution, with modifications to suit this
1694 particular application.) This output is controlled by the value of
1695 the variable "send_human" which takes a five element list. The first
1696 two elements are average interarrival time of characters in seconds.
1697 The first is used by default. The second is used at word endings, to
1698 simulate the subtle pauses that occasionally occur at such
1699 transitions. The third parameter is a measure of variability where .1
1700 is quite variable, 1 is reasonably variable, and 10 is quite
1701 invariable. The extremes are 0 to infinity. The last two parameters
1702 are, respectively, a minimum and maximum interarrival time.
1703 The minimum and maximum are used last and "clip" the final time.
1704 The ultimate average can be quite different from the given average
1705 if the minimum and maximum clip enough values.
1708 example, the following command emulates a fast and
1712 set send_human {.1 .3 1 .05 2}
1713 send \-h "I'm hungry. Let's do lunch."
1716 while the following might be more suitable after a hangover:
1719 set send_human {.4 .4 .2 .5 100}
1720 send \-h "Goodd party lash night!"
1723 Note that errors are not simulated, although you can set up error
1724 correction situations yourself by embedding mistakes and corrections
1727 The flags for sending null characters, for sending breaks, for forcing slow
1728 output and for human-style output are mutually exclusive. Only the one
1729 specified last will be used. Furthermore, no
1731 argument can be specified with the flags for sending null characters or breaks.
1733 It is a good idea to precede the first
1738 will wait for the process to start, while
1741 In particular, if the first
1743 completes before the process starts running,
1744 you run the risk of having your data ignored.
1745 In situations where interactive programs offer no initial prompt,
1751 # To avoid giving hackers hints on how to break in,
1752 # this system does not prompt for an external password.
1753 # Wait for 5 seconds for exec to complete
1754 spawn telnet very.secure.gov
1762 If you are using Expectk or some other variant of Expect in the Tk environment,
1764 is defined by Tk for an entirely different purpose.
1766 is provided for compatibility between environments.
1767 Similar aliases are provided for other Expect's other send commands.
1769 .BI send_error " [\-flags] string"
1772 except that the output is sent to stderr rather than the current
1775 .BI send_log " [\--] string"
1778 except that the string is only sent to the log file (see
1780 The arguments are ignored if no log file is open.
1782 .BI send_tty " [\-flags] string"
1785 except that the output is sent to /dev/tty rather than the current
1788 .BI send_user " [\-flags] string"
1791 except that the output is sent to stdout rather than the current
1794 .BI sleep " seconds"
1795 causes the script to sleep for the given number of seconds.
1796 Seconds may be a decimal number. Interrupts (and Tk events if you
1797 are using Expectk) are processed while Expect sleeps.
1799 .BI spawn " [args] program [args]"
1800 creates a new process running
1801 .IR "program args" .
1802 Its stdin, stdout and stderr are connected to Expect,
1803 so that they may be read and written by other
1806 The connection is broken by
1808 or if the process itself closes any of the file identifiers.
1810 When a process is started by
1814 is set to a descriptor referring to that process.
1815 The process described by
1818 .IR "current process" .
1820 may be read or written, in effect providing job control.
1823 is a global variable containing a descriptor which refers to the user.
1826 is set to this value,
1833 is a global variable containing a descriptor which refers to the standard
1837 is set to this value,
1843 is a global variable containing a descriptor which refers to /dev/tty.
1844 If /dev/tty does not exist (such as in a cron, at, or batch script), then
1846 is not defined. This may be tested as:
1849 if {[info vars tty_spawn_id]} {
1852 # /dev/tty doesn't exist
1853 # probably in cron, batch, or at script
1859 returns the UNIX process id. If no process is spawned, 0 is returned.
1861 .I spawn_out(slave,name)
1862 is set to the name of the pty slave device.
1866 echoes the command name and arguments. The
1874 flag causes console output to be redirected to the spawned process.
1875 This is not supported on all systems.
1879 uses a pty, initialized the same way as the user's tty. This is further
1880 initialized so that all settings are "sane" (according to stty(1)).
1883 is defined, it is interpreted in the style of stty arguments
1884 as further configuration.
1885 For example, "set stty_init raw" will cause further spawned processes's
1886 terminals to start in raw mode.
1888 skips the initialization based on the user's tty.
1890 skips the "sane" initialization.
1894 takes little time to execute. If you notice spawn taking a
1895 significant amount of time, it is probably encountering ptys that are
1896 wedged. A number of tests are run on ptys to avoid entanglements with
1897 errant processes. (These take 10 seconds per wedged pty.) Running
1902 is encountering many ptys in odd states. If you cannot kill
1903 the processes to which these ptys are attached, your only recourse may
1908 cannot be spawned successfully because exec(2) fails (e.g. when
1910 doesn't exist), an error message will be returned by the next
1916 had run and produced the error message as output.
1917 This behavior is a natural consequence of the implementation of
1919 Internally, spawn forks, after which the spawned process has no
1920 way to communicate with the original
1922 process except by communication
1927 flag causes the next argument to be interpreted as a Tcl file identifier
1930 The spawn id can then be used as if it were a spawned process. (The file
1931 identifier should no longer be used.)
1932 This lets you treat raw devices, files, and
1933 pipelines as spawned processes without using a pty. 0 is returned to
1934 indicate there is no associated process. When the connection to
1935 the spawned process is closed, so is the Tcl file identifier.
1942 causes the file identifier to be left open even after the spawn id is closed.
1946 flag causes a pty to be opened but no process spawned. 0 is returned
1947 to indicate there is no associated process. Spawn_id is set as usual.
1950 .I spawn_out(slave,fd)
1951 is set to a file identifier corresponding to the pty slave.
1952 It can be closed using "close -slave".
1956 flag names a signal to be ignored in the spawned process.
1957 Otherwise, signals get the default behavior.
1958 Signals are named as in the
1960 command, except that each signal requires a separate flag.
1963 causes following statements to be printed before being executed.
1964 (Tcl's trace command traces variables.)
1966 indicates how far down in the call stack to trace.
1968 the following command runs
1970 while tracing the first 4 levels of calls,
1971 but none below that.
1974 expect \-c "strace 4" script.exp
1980 flag causes strace to return a description of the
1981 most recent non-info arguments given.
1984 changes terminal modes similarly to the external stty command.
1986 By default, the controlling terminal is accessed. Other terminals can
1987 be accessed by appending "< /dev/tty..." to the command. (Note that
1988 the arguments should not be grouped into a single argument.)
1990 Requests for status return it as the result of the command. If no status
1991 is requested and the controlling terminal is accessed, the previous
1992 status of the raw and echo attributes are returned in a form which can
1993 later be used by the command.
1995 For example, the arguments
1999 put the terminal into raw mode.
2004 put the terminal into cooked mode.
2009 put the terminal into echo and noecho mode respectively.
2011 The following example illustrates how to temporarily disable echoing.
2012 This could be used in otherwise-automatic
2013 scripts to avoid embedding passwords in them.
2014 (See more discussion on this under EXPECT HINTS below.)
2018 send_user "Password: "
2019 expect_user -re "(.*)\\n"
2020 set password $expect_out(1,string)
2029 just as if it had been typed as a command from a terminal.
2031 waits until the shell terminates.
2032 The return status from sh is handled the same way that
2034 handles its return status.
2038 which redirects stdin and stdout to the script,
2040 performs no redirection
2041 (other than that indicated by the string itself).
2042 Thus, it is possible to use programs which must talk directly to /dev/tty.
2043 For the same reason, the results of
2045 are not recorded in the log.
2047 .BI timestamp " [args]"
2048 returns a timestamp.
2049 With no arguments, the number of
2050 seconds since the epoch is returned.
2054 flag introduces a string which is returned but with
2055 substitutions made according to the
2056 POSIX rules for strftime. For example %a is replaced by an abbreviated
2057 weekday name (i.e., Sat). Others are:
2059 %a abbreviated weekday name
2060 %A full weekday name
2061 %b abbreviated month name
2063 %c date-time as in: Wed Oct 6 11:45:56 1993
2064 %d day of the month (01-31)
2072 %u day (1-7, Monday is first day of week)
2073 %U week (00-53, first Sunday is first day of week one)
2074 %V week (01-53, ISO 8601 style)
2076 %W week (00-53, first Monday is first day of week one)
2077 %x date-time as in: Wed Oct 6 1993
2078 %X time as in: 23:59:59
2081 %Z timezone (or nothing if not determinable)
2082 %% a bare percent sign
2085 Other % specifications are undefined. Other characters will be passed
2086 through untouched. Only the C locale is supported.
2090 flag introduces a number of seconds since the epoch to be used as a source
2091 from which to format. Otherwise, the current time is used.
2095 flag forces timestamp output to use the GMT timezone. With no flag,
2096 the local timezone is used.
2098 .BI trap " [[command] signals]"
2101 to be executed upon future receipt of any of the given signals.
2102 The command is executed in the global scope.
2105 is absent, the signal action is returned.
2108 is the string SIG_IGN, the signals are ignored.
2111 is the string SIG_DFL, the signals are result to the system default.
2113 is either a single signal or a list of signals. Signals may be specified
2114 numerically or symbolically as per signal(3). The "SIG" prefix may be omitted.
2116 With no arguments (or the argument \-number),
2118 returns the signal number of the trap command currently being executed.
2122 flag uses the return code of the command in place of whatever code Tcl
2123 was about to return when the command originally started running.
2127 flag causes the command to be evaluated using the interpreter
2128 active at the time the command started running
2129 rather than when the trap was declared.
2135 command to return the signal name of the trap command currently being executed.
2141 command to return the largest signal number that can be set.
2143 For example, the command "trap {send_user "Ouch!"} SIGINT" will print "Ouch!"
2144 each time the user presses ^C.
2146 By default, SIGINT (which can usually be generated by pressing ^C) and
2147 SIGTERM cause Expect to exit. This is due to the following trap, created
2148 by default when Expect starts.
2151 trap exit {SIGINT SIGTERM}
2154 If you use the -D flag to start the debugger, SIGINT is redefined
2155 to start the interactive debugger. This is due to the following trap:
2158 trap {exp_debug 1} SIGINT
2161 The debugger trap can be changed by setting the environment variable
2162 EXPECT_DEBUG_INIT to a new trap command.
2164 You can, of course, override both of these just by adding trap
2165 commands to your script. In particular, if you have your own "trap
2166 exit SIGINT", this will override the debugger trap. This is useful
2167 if you want to prevent users from getting to the debugger at all.
2169 If you want to define your own trap on SIGINT but still trap to the
2170 debugger when it is running, use:
2173 if {![exp_debug]} {trap mystuff SIGINT}
2176 Alternatively, you can trap to the debugger using some other signal.
2179 will not let you override the action for SIGALRM as this is used internally
2182 The disconnect command sets SIGALRM to SIG_IGN (ignore). You can reenable
2183 this as long as you disable it during subsequent spawn commands.
2185 See signal(3) for more info.
2188 delays until a spawned process (or
2189 the current process if none is named) terminates.
2192 normally returns a list of four integers.
2193 The first integer is the pid of the process that was waited upon.
2194 The second integer is the corresponding spawn id.
2195 The third integer is -1 if an operating system error occurred, or 0 otherwise.
2196 If the third integer was 0, the fourth integer is the status returned by
2197 the spawned process. If the third integer was -1, the fourth integer is
2198 the value of errno set by the operating system. The global variable
2199 errorCode is also set.
2201 Additional elements may appear at the end of the return value from
2203 An optional fifth element identifies a class of information.
2204 Currently, the only possible value for this element is CHILDKILLED in
2205 which case the next two values are the C-style signal name and a short
2206 textual description.
2210 flag declares the process to wait corresponding to the named spawn_id
2211 (NOT the process id).
2212 Inside a SIGCHLD handler,
2213 it is possible to wait for any spawned process by using the spawn id -1.
2217 flag causes the wait to return immediately with the indication of a
2218 successful wait. When the process exits (later), it will automatically
2219 disappear without the need for an explicit wait.
2223 command may also be used wait for a forked process using the arguments
2224 "-i -1". Unlike its use with spawned processes, this command can be
2225 executed at any time. There is no control over which process is
2226 reaped. However, the return value can be checked for the process id.
2229 Expect automatically knows about two built-in libraries for Expect scripts.
2230 These are defined by the directories named in the variables
2231 exp_library and exp_exec_library. Both are meant to contain utility
2232 files that can be used by other scripts.
2234 exp_library contains architecture-independent files. exp_exec_library
2235 contains architecture-dependent files. Depending on your system, both
2236 directories may be totally empty. The existence of the file
2237 $exp_exec_library/cat-buffers describes whether your /bin/cat buffers
2240 A vgrind definition is available for pretty-printing
2243 Assuming the vgrind definition supplied with the
2246 correctly installed, you can use it as:
2249 vgrind \-lexpect file
2253 It many not be apparent how to put everything together that the man page
2254 describes. I encourage you to read and try out the examples in
2255 the example directory of the
2258 Some of them are real programs. Others are simply illustrative
2259 of certain techniques, and of course, a couple are just quick hacks.
2260 The INSTALL file has a quick overview of these programs.
2264 papers (see SEE ALSO) are also useful. While some papers
2265 use syntax corresponding to earlier versions of Expect, the accompanying
2266 rationales are still valid and go into a lot more detail than this
2269 Extensions may collide with Expect's command names. For example,
2271 is defined by Tk for an entirely different purpose.
2272 For this reason, most of the
2274 commands are also available as "exp_XXXX".
2275 Commands and variables beginning with "exp", "inter", "spawn",
2276 and "timeout" do not have aliases.
2277 Use the extended command names if you need this compatibility between environments.
2280 takes a rather liberal view of scoping.
2281 In particular, variables read by commands specific to the
2283 program will be sought first from the local scope, and if not found, in the
2284 global scope. For example, this
2285 obviates the need to place "global timeout" in every
2286 procedure you write that uses
2288 On the other hand, variables written are always in the local scope (unless
2289 a "global" command has been issued). The most common problem this causes
2290 is when spawn is executed in a procedure. Outside the procedure,
2292 no longer exists, so the spawned process is no longer accessible
2293 simply because of scoping. Add a "global spawn_id" to such a procedure.
2295 If you cannot enable the multispawning capability
2296 (i.e., your system supports neither select (BSD *.*), poll (SVR>2),
2297 nor something equivalent),
2299 will only be able to control a single process at a time.
2300 In this case, do not attempt to set
2302 nor should you execute processes via exec while a spawned process
2303 is running. Furthermore, you will not be able to
2305 from multiple processes (including the user as one) at the same time.
2307 Terminal parameters can have a big effect on scripts. For example, if
2308 a script is written to look for echoing, it will misbehave if echoing
2309 is turned off. For this reason, Expect forces sane terminal
2310 parameters by default. Unfortunately, this can make things unpleasant
2311 for other programs. As an example, the emacs shell wants to change
2312 the "usual" mappings: newlines get mapped to newlines instead of
2313 carriage-return newlines, and echoing is disabled. This allows one to
2314 use emacs to edit the input line. Unfortunately, Expect cannot
2315 possibly guess this.
2317 You can request that Expect not override its default setting of
2318 terminal parameters, but you must then be very careful when writing
2319 scripts for such environments. In the case of emacs, avoid depending
2320 upon things like echoing and end-of-line mappings.
2322 The commands that accepted arguments braced into a single list (the
2326 use a heuristic to decide if the list is actually one argument or
2327 many. The heuristic can fail only in the case when the list actually
2328 does represent a single argument which has multiple embedded \\n's
2329 with non-whitespace characters between them. This seems sufficiently
2330 improbable, however the argument "\-nobrace" can be used to force a
2331 single argument to be handled as a single argument. This could
2332 conceivably be used with machine-generated Expect code. Similarly,
2333 -brace forces a single argument to be handle as multiple patterns/actions.
2336 It was really tempting to name the program "sex" (for either "Smart EXec"
2337 or "Send-EXpect"), but good sense (or perhaps just Puritanism) prevailed.
2339 On some systems, when a shell is spawned, it complains about not being
2340 able to access the tty but runs anyway. This means your system has a
2341 mechanism for gaining the controlling tty that
2343 doesn't know about. Please find out what it is, and send this information
2346 Ultrix 4.1 (at least the latest versions around here) considers
2347 timeouts of above 1000000 to be equivalent to 0.
2349 Digital UNIX 4.0A (and probably other versions) refuses to allocate
2350 ptys if you define a SIGCHLD handler. See grantpt page for more info.
2352 IRIX 6.0 does not handle pty permissions correctly so that if Expect
2353 attempts to allocate a pty previously used by someone else, it fails.
2354 Upgrade to IRIX 6.1.
2356 Telnet (verified only under SunOS 4.1.2) hangs if TERM is not set.
2357 This is a problem under cron, at and in cgi scripts, which do not
2358 define TERM. Thus, you must set it explicitly - to what type is
2359 usually irrelevant. It just has to be set to something! The
2360 following probably suffices for most cases.
2367 Tip (verified only under BSDI BSD/OS 3.1 i386) hangs if SHELL and HOME
2368 are not set. This is a problem under cron, at and in cgi scripts,
2369 which do not define these environment variables. Thus, you must set
2370 them explicitly - to what type is usually irrelevant. It just has to
2371 be set to something! The following probably suffices for most cases.
2374 set env(SHELL) /bin/sh
2375 set env(HOME) /usr/local/bin
2380 Some implementations of ptys are designed so that the kernel throws
2381 away any unread output after 10 to 15 seconds (actual number is
2382 implementation-dependent) after the process has closed the file
2393 will fail. To avoid this, invoke non-interactive programs with
2397 While such situations are conceivable, in practice I have never
2398 encountered a situation in which the final output of a truly
2399 interactive program would be lost due to this behavior.
2401 On the other hand, Cray UNICOS ptys throw away any unread output
2402 immediately after the process has closed the file descriptor. I have
2403 reported this to Cray and they are working on a fix.
2405 Sometimes a delay is required between a prompt and a response, such as
2406 when a tty interface is changing UART settings or matching baud rates
2407 by looking for start/stop bits. Usually, all this is require is to
2408 sleep for a second or two. A more robust technique is to retry until
2409 the hardware is ready to receive input. The following example uses
2413 send "speed 9600\\r";
2416 timeout {send "\\r"; exp_continue}
2422 trap \-code will not work with any command that sits in Tcl's event
2423 loop, such as sleep. The problem is that in the event loop, Tcl
2424 discards the return codes from async event handlers. A workaround is
2425 to set a flag in the trap code. Then check the flag immediately after
2426 the command (i.e., sleep).
2428 The expect_background command ignores -timeout arguments and has no
2429 concept of timeouts in general.
2432 There are a couple of things about
2434 that may be non-intuitive.
2435 This section attempts to address some of these things with a couple of
2438 A common expect problem is how to recognize shell prompts. Since
2439 these are customized differently by differently people and different
2440 shells, portably automating rlogin can be difficult without knowing
2441 the prompt. A reasonable convention is to have users store a regular
2442 expression describing their prompt (in particular, the end of it) in
2443 the environment variable EXPECT_PROMPT. Code like the following
2444 can be used. If EXPECT_PROMPT doesn't exist, the code still has a good chance of functioning correctly.
2447 set prompt "(%|#|\\\\$) $" ;# default prompt
2448 catch {set prompt $env(EXPECT_PROMPT)}
2453 I encourage you to write
2455 patterns that include the end of whatever
2456 you expect to see. This avoids the possibility of answering a question
2457 before seeing the entire thing. In addition, while you may well be
2458 able to answer questions before seeing them entirely, if you answer
2459 early, your answer may appear echoed back in the middle of the question.
2460 In other words, the resulting dialogue will be correct but look scrambled.
2462 Most prompts include a space character at the end.
2463 For example, the prompt from ftp is 'f', 't', 'p', '>' and <blank>.
2464 To match this prompt, you must account for each of these characters.
2465 It is a common mistake not to include the blank.
2466 Put the blank in explicitly.
2468 If you use a pattern of the form X*, the * will match all the output
2469 received from the end of X to the last thing received.
2470 This sounds intuitive but can be somewhat confusing because the phrase
2471 "last thing received" can vary depending upon the speed of the computer
2472 and the processing of I/O both by the kernel and the device driver.
2474 In particular, humans tend to see program output arriving in huge chunks
2475 (atomically) when in reality most programs produce output one
2476 line at a time. Assuming this is the case, the * in the pattern of the
2477 previous paragraph may only match the end of the current line even though
2478 there seems to be more, because at the time of the match that was all
2479 the output that had been received.
2482 has no way of knowing that further output is coming unless your
2483 pattern specifically accounts for it.
2485 Even depending on line-oriented buffering is unwise. Not only do programs
2486 rarely make promises about the type of buffering they do, but system
2487 indigestion can break output lines up so that lines break at seemingly
2488 random places. Thus, if you can express the last few characters
2489 of a prompt when writing patterns, it is wise to do so.
2491 If you are waiting for a pattern in the last output of a program
2492 and the program emits something else instead, you will not be able to
2493 detect that with the
2495 keyword. The reason is that
2497 will not timeout \- instead it will get an
2500 Use that instead. Even better, use both. That way if that line
2501 is ever moved around, you won't have to edit the line itself.
2503 Newlines are usually converted to carriage return, linefeed sequences
2504 when output by the terminal driver. Thus, if you want a pattern that
2505 explicitly matches the two lines, from, say, printf("foo\\nbar"),
2506 you should use the pattern "foo\\r\\nbar".
2508 A similar translation occurs when reading from the user, via
2510 In this case, when you press return, it will be
2511 translated to a newline. If
2513 then passes that to a program
2514 which sets its terminal to raw mode (like telnet), there is going to
2515 be a problem, as the program expects a true return. (Some programs
2516 are actually forgiving in that they will automatically translate
2517 newlines to returns, but most don't.) Unfortunately, there is no way to find
2518 out that a program put its terminal into raw mode.
2520 Rather than manually replacing newlines with returns, the solution is to
2521 use the command "stty raw", which will stop the translation.
2522 Note, however, that this means that you will no longer get the cooked
2523 line-editing features.
2526 implicitly sets your terminal to raw mode so this problem will not arise then.
2528 It is often useful to store passwords (or other private information)
2531 scripts. This is not recommended since anything that is
2532 stored on a computer is susceptible to being accessed by anyone.
2533 Thus, interactively prompting for passwords from a script is a smarter
2534 idea than embedding them literally. Nonetheless, sometimes such embedding
2535 is the only possibility.
2537 Unfortunately, the UNIX file system has no direct way of creating
2538 scripts which are executable but unreadable. Systems which support
2539 setgid shell scripts may indirectly simulate this as follows:
2543 script (that contains the secret data) as usual.
2544 Make its permissions be 750 (\-rwxr\-x\-\-\-) and owned by a trusted group,
2545 i.e., a group which is allowed to read it. If necessary, create a new
2546 group for this purpose. Next, create a /bin/sh script with
2547 permissions 2751 (\-rwxr\-s\-\-x) owned by the same group as before.
2549 The result is a script which may be executed (and read) by anyone.
2550 When invoked, it runs the
2558 "Exploring Expect: A Tcl-Based Toolkit for Automating Interactive Programs"
2559 \fRby Don Libes, pp. 602, ISBN 1-56592-090-2, O'Reilly and Associates, 1995.
2562 "expect: Curing Those Uncontrollable Fits of Interactivity" \fRby Don Libes,
2563 Proceedings of the Summer 1990 USENIX Conference,
2564 Anaheim, California, June 11-15, 1990.
2569 to Automate System Administration Tasks" \fRby Don Libes,
2570 Proceedings of the 1990 USENIX Large Installation Systems Administration
2571 Conference, Colorado Springs, Colorado, October 17-19, 1990.
2574 "Tcl: An Embeddable Command Language" \fRby John Ousterhout,
2575 Proceedings of the Winter 1990 USENIX Conference,
2576 Washington, D.C., January 22-26, 1990.
2579 "expect: Scripts for Controlling Interactive Programs" \fRby Don Libes,
2580 Computing Systems, Vol. 4, No. 2, University of California Press Journals,
2584 "Regression Testing and Conformance Testing Interactive Programs", \fRby Don
2585 Libes, Proceedings of the Summer 1992 USENIX Conference, pp. 135-144,
2586 San Antonio, TX, June 12-15, 1992.
2589 "Kibitz \- Connecting Multiple Interactive Programs Together", \fRby Don Libes,
2590 Software \- Practice & Experience, John Wiley & Sons, West Sussex, England,
2591 Vol. 23, No. 5, May, 1993.
2594 "A Debugger for Tcl Applications", \fRby Don Libes,
2595 Proceedings of the 1993 Tcl/Tk Workshop, Berkeley, CA, June 10-11, 1993.
2597 Don Libes, National Institute of Standards and Technology
2599 Thanks to John Ousterhout for Tcl, and Scott Paisley for inspiration.
2600 Thanks to Rob Savoye for Expect's autoconfiguration code.
2602 The HISTORY file documents much of the evolution of
2604 It makes interesting reading and might give you further insight to this
2605 software. Thanks to the people mentioned in it who sent me bug fixes
2606 and gave other assistance.
2608 Design and implementation of
2610 was paid for in part by the U.S. government and is therefore in the public
2612 However the author and NIST would like credit
2613 if this program and documentation or portions of them are used.