This command reference outlines the basic usage of Expect for Windows. It provides descriptions of the commands in the Expect package and some short examples of how these commands can be used.
In this document, "Expect" with an uppercase "E" refers to the
Expect package while "expect" with a lowercase "e" refers to the
expect
command within the Expect package
For differences between the Windows and Unix versions of Expect, see Porting Expect Scripts to Windows in the Expect for Windows Usage section.
Expect for Windows is implemented as a Tcl package (as opposed
to as a stand-alone executable). It must be called with a
package require Expect
statement. For example:
#!/bin/sh # \ exec tclsh "$0" ${1+"$@"} package require Expect . . .
A Tutorial and Demos are available to show how to build Expect scripts in Tcl. A detailed guide on how to use Expect can be found in Using ActiveState Expect for Windows.
Expect uses Tcl (Tool Command Language). Tcl provides
control flow, expression evaluation and several other features such
as recursion, procedure definition, etc. Commands used here but not
defined (e.g., set
, if
,
exec
) are Tcl commands (described in the Tcl
documentation). Expect supports additional commands, described
below. Unless otherwise specified, commands return the empty
string.
For quick reference, commands are listed alphabetically. New
users may find it easier to start by reading the descriptions of
exp_spawn
, exp_send
, and
expect
, in that
order.
With the exception of the expect
command, all
commands listed are prefixed with "exp_" or "expect_". Though most
of them can be called without these prefixes, they are generally
used in the form presented in order to clearly differentiate them
from other global commands in Tcl. The reason for the command name
overlap is that Expect was the very first extension to Tcl, and
several of the command names it uses were Expect commands before
they were core Tcl commands.
This command closes the connection to the current process. Most
interactive programs will detect EOF on their stdin and exit; thus
exp_close
usually suffices to kill the process as
well. The -i
flag declares the process to close
corresponding to the named spawn_id.
The expect
command will
detect when the current process exits and implicitly do an
exp_close
. But if you kill the process by another
method such as "exec kill $pid
", you will need to
explicitly call exp_close
.
The -onexec
flag determines whether the spawn id
will be closed in any new spawned processes or if the process is
overlaid. To leave a spawn id open, use the value 0. A non-zero
integer value will force the spawn closed (the default) in any new
processes.
The -slave
flag is not supported on
Windows. On Unix systems, this closes the slave associated
with the spawn id. (See "exp_spawn
-pty
".) When the connection is closed, the slave is
automatically closed as well if still open.
Regardless of whether the connection is closed implicitly or
explicitly, you should call exp_wait
to clear up the corresponding
kernel process slot. The exp_close
command does not
call exp_wait
since there is no guarantee that closing
a process connection will cause it to exit. See
exp_wait
for more information.
The command exp_continue
allows expect
itself to continue executing rather than returning as it normally
would. By default exp_continue
resets the timeout
timer. The -continue_timer flag prevents the timer from
being restarted. See expect
for
more information.
Not applicable on Windows. On Unix systems, this disconnects a forked process from the terminal and continues running in the background.
This command causes Expect to exit or otherwise prepare to do so.
The -onexit
flag causes the next argument to be
used as an exit handler. Without an argument, the current exit
handler is returned.
The -noexit
flag causes Expect to prepare to exit
but stop short of actually returning control to the operating
system. The user-defined exit handler is run as well as Expect's
own internal handlers. No further Expect commands should be
executed. This is useful if you are running Expect with other Tcl
extensions. The current interpreter remains (as does the main
window in the Tk environment) so that other Tcl extensions can
clean up. If Expect's exp_exit
is called again
(however this might occur), the handlers are not rerun.
Upon exiting, all connections to spawned processes are closed.
Closure will be detected as an EOF by spawned processes. The
exp_exit
command takes no other actions beyond what
the normal _exit
procedure does.
The status (or 0 if not specified) is returned as the
exit status of Expect. The exp_exit
command is
implicitly executed if the end of the script is reached.
Not applicable on Windows. On Unix systems, this command creates a new copy of the current Expect process.
The exp_getpid
command is deprecated. Tcl's
pid
command should be used instead.
Not currently implemented on Windows. On Unix systems,
exp_inter_return
causes interact
to cause
a return in its caller.
Not currently implemented on Windows. On Unix systems, this command gives control of the current process to the user, so that keystrokes are sent to the current process, and the stdout and stderr of the current process are returned.
This causes further commands to send diagnostic information internal to Expect to stderr if value is nonzero. This output is disabled if value is 0. The diagnostic information includes every character received, and every attempt made to match the current output against the patterns.
If the optional file is supplied, all normal and debugging output is written to that file (regardless of the value of value). Any previous diagnostic output file is closed.
The -info
flag causes exp_internal
to
return a description of the most recent non-info arguments
given.
This command causes the user to be interactively prompted for Expect and Tcl commands. The result of each command is printed.
Actions such as break
and continue
cause control structures (i.e., for
,
proc
) to behave in the usual way. However return
causes exp_interpreter
to return to its caller, while
exp_inter_return
(not currently implemented in
Expect for Windows) causes exp_interpreter
to
cause a return in its caller. For example, if "proc
foo
" called exp_interpreter
, which then
executed the action exp_inter_return
,
proc
foo
would return. Any other command
causes exp_interpreter
to continue prompting for new
commands.
By default, the prompt contains two integers. The first integer
describes the depth of the evaluation stack (i.e., how many times
Tcl_Eval
has been called). The second integer is the Tcl history identifier.
The prompt can be set by defining a procedure called "prompt1"
whose return value becomes the next prompt. If a statement has open
quotes, parentheses, braces, or brackets, a secondary prompt (by
default "+> ") is issued upon newline. The secondary prompt may
be set by defining a procedure called "prompt2".
During exp_interpreter
, cooked mode is used, even
if its caller was using raw mode.
If stdin is closed, exp_interpreter
will return
unless the -eof
flag is used, in which case the
subsequent argument is invoked.
If a filename is provided, exp_log_file
will record
a transcript of the session (beginning at that point) in the file.
The exp_log_file
command will stop recording if no
argument is given. Any previous log file is closed.
Instead of a filename, a Tcl file identifier may be provided by
using the -open
or -leaveopen
flags. This
is similar to the exp_spawn
command.
The -a
flag forces output to be logged that was
suppressed by the exp_log_user
command.
By default, the exp_log_file
command
appends to old files rather than truncating them, for the
convenience of being able to turn logging off and on multiple times
in one session. To truncate files, use the -noappend
flag.
The -info
flag causes exp_log_file
to
return a description of the most recent non-info arguments
given.
By default, the send/expect dialogue is logged to stdout (and a
log file if open). The logging to stdout is disabled by the command
"exp_log_user 0
" and re-enabled by "exp_log_user
1
". Logging to the log file is unchanged.
The -info
flag causes log_user to return a
description of the most recent non-info arguments given.
This command defines the size of the buffer (in bytes) used
internally by expect
. With no size argument,
the current size is returned.
With the -d
flag, the default size is set. (The
initial default is 2000.) With the -i
flag, the size
is set for the named spawn id, otherwise it is set for the current
process.
Not available on Windows. On Unix systems, this returns
a Tcl file identifier that corresponds to the original spawn id.
The file identifier can then be used as if it were opened by Tcl's
open
command.
Not applicable on Windows. On Unix systems, this executes program [args] in place of the current Expect program, which terminates.
This command defines whether parity should be retained or stripped from the output of spawned processes. If value is zero, parity is stripped, otherwise it is not stripped. With no value argument, the current value is returned.
With the -d
flag, the default parity value is set.
(The initial default is 1, i.e., parity is not stripped.) With the
-i
flag, the parity value is set for the named spawn
id, otherwise it is set for the current process.
This command returns the process id corresponding to the
currently spawned process. If the -i
flag is used, the
pid returned corresponds to that of the given spawn id.
This command defines whether nulls are retained or removed from the output of spawned processes before pattern matching or storing in the variable expect_out or interact_out. If value is 1, nulls are removed. If value is 0, nulls are not removed. With no value argument, the current value is returned.
With the -d
flag, the default value is set. (The
initial default is 1, i.e., nulls are removed.) With the
-i
flag, the value is set for the named spawn id,
otherwise it is set for the current process.
Whether or not nulls are removed, Expect will record null bytes to the log and stdout.
Sends string to the current process. For example, this command will send the characters, h e l l o <blank> w o r l d <return> to the current process:
exp_send "hello world\r"
Tcl includes a printf
-like command called format
,
which can build arbitrarily complex strings.
Characters are sent immediately, although programs with line-buffered input will not read the characters until a return character is sent. A return character is denoted "\r".
The --
flag forces the next argument to be
interpreted as a string rather than a flag. Any string can be
preceded by "--" whether or not it actually looks like a flag. This
provides a reliable mechanism to specify variable strings without
being confused by those that accidentally look like flags. (All
strings starting with "-" are reserved for future options.)
The -i
flag declares that the string be sent to the
named spawn_id. If the spawn_id is user_spawn_id, and the
terminal is in raw mode, newlines in the string are translated to
return-newline sequences so that they appear as if the terminal was
in cooked mode. The -raw
flag disables this
translation.
The -null
flag sends null characters (0 bytes). By
default, one null is sent. An integer may follow the
-null
to indicate how many nulls to send.
The -break
flag is not available on
Windows. On Unix systems, this flag generates a break
condition. This only makes sense if the spawn id refers to a tty
device opened via "exp_spawn -open". If you have spawned a process
such as tip, you should use tip's convention for generating a
break.
The -s
flag forces output to be sent "slowly", thus
avoiding the common situation where a computer outtypes an input
buffer that was designed for a human who would never outtype the
same buffer. This output is controlled by the value of the variable
"send_slow" which takes a two-element list. The first element is an
integer that describes the number of bytes to send atomically. The
second element is a real number that sets the number of seconds by
which the atomic sends must be separated. For example, "set
send_slow {10 .001}" would force "send -s" to send strings with 1
millisecond in between each 10 characters sent.
The -h
flag forces output to be sent (somewhat)
like a human actually typing. Human-like delays appear between the
characters. (The algorithm is based upon a Weibull distribution,
with modifications to suit this particular application.) This
output is controlled by the value of the variable "send_human",
which takes a five-element list:
As an example, the following command emulates a fast and consistent typist:
set send_human {.1 .3 1 .05 2} exp_send -h "I'm hungry. Let's do lunch."
The following might be more suitable after a hangover:
set send_human {.4 .4 .2 .5 100} exp_send -h "Goodd party lash night!"
Note that errors are not simulated, although you can set up
error correction situations yourself by embedding mistakes and
corrections in an exp_send
argument.
The flags for sending null characters, for sending breaks, for forcing slow output and for human-style output are mutually exclusive. Only the one specified last will be used. Furthermore, no string argument can be specified with the flags for sending null characters or breaks.
It is a good idea to precede the first exp_send
to
a process by an expect
. The
expect
command will wait for the process to start,
while exp_send
cannot. In particular, if the first
exp_send
completes before the process starts running,
you run the risk of having your data ignored. In situations where
interactive programs offer no initial prompt, you can precede
exp_send
by a delay as in:
# To avoid giving hackers hints on how to break in, # this system does not prompt for an external password. # Wait for 5 seconds for exec to complete. exp_spawn telnet very.secure.gov exp_sleep 5 exp_send password\r
Expect for Windows does not implement a parser for VT100 codes for special keypress codes such as "arrow up", F1, Home, etc.
This command is like exp_send
, except that the output is sent to
stderr rather than the current process.
This command is like exp_send
, except that the
string is only sent to the log file (see exp_log_file .) The arguments are
ignored if no log file is open.
This command is like exp_send
, except that the
output is sent to /dev/tty rather than the current process.
This command is like exp_send
, except that the
output is sent to stdout rather than the current process.
This command causes the script to sleep for the given number of
seconds. Seconds may be a decimal number. Interrupts (and Tk events
if you are using Expectk) are processed while Expect sleeps. It is
better to use Tcl's after
command instead.
This command creates a new process running program
args. Its stdin, stdout and stderr are connected to Expect, so
that they may be read and written by other Expect commands. The
connection is broken by exp_close
or by the process itself closing
any of the file identifiers.
When a process is started by exp_spawn
, the
variable spawn_id is set to a descriptor referring to that
process. The process described by spawn_id is considered
the current process. The spawn_id variable may be
read or written, in effect providing job control.
user_spawn_id is a global variable containing a
descriptor that refers to the user. For example, when
spawn_id is set to this value, expect
behaves like expect_user
.
error_spawn_id is a global variable containing a
descriptor that refers to the standard error. For example, when
spawn_id is set to this value, exp_send
behaves like exp_send_error
.
tty_spawn_id is a global variable containing a descriptor that refers to /dev/tty. If /dev/tty does not exist (such as in a cron, at, or batch script), then tty_spawn_id is not defined. This may be tested as:
if {[info vars tty_spawn_id]} { # /dev/tty exists } else { # /dev/tty doesn't exist # probably in cron, batch, or at script }
exp_spawn
returns the Unix process id. If no
process is spawned, 0 is returned. The variable
spawn_out(slave,name) is set to the name of the pty slave
device.
By default, exp_spawn
echoes the command name and
arguments. The -noecho
flag stops
exp_spawn
from doing this.
The -console
flag causes console output to be
redirected to the spawned process. This is not supported on all
systems.
Internally, exp_spawn
uses a pty, initialized the
same way as the user's tty. This is further initialized so that all
settings are "sane" (according to stty(1)). If the variable
stty_init is defined, it is interpreted in the style of
stty arguments as further configuration. For example, "set
stty_init raw
" will cause further spawned processes's
terminals to start in raw mode. The -nottycopy
flag
skips the initialization based on the user's tty. The
-nottyinit
flag skips the "sane" initialization.
Normally, exp_spawn
takes little time to execute.
If you notice spawn taking a significant amount of time, it is
probably encountering ptys that are wedged. A number of tests are
run on ptys to avoid entanglements with errant processes. (These
take 10 seconds per wedged pty.) Running Expect with the
-d
option will show if Expect is encountering many
ptys in odd states. If you cannot kill the processes to which these
ptys are attached, your only recourse may be to reboot.
If a program cannot be spawned successfully because
exec
fails (e.g. when the program doesn't exist), an
error message will be returned by the next expect
command as if the program had run and produced the error message as
output. This behavior is a natural consequence of the
implementation of exp_spawn
. Internally, spawn forks,
after which the spawned process has no way to communicate with the
original Expect process except by communication via the
spawn_id.
The -open
flag causes the next argument to be
interpreted as a Tcl file identifier (i.e., returned by
exp_open
.) The spawn id can then be used as if it were
a spawned process. (The file identifier should no longer be used.)
This lets you treat raw devices, files, and pipelines as spawned
processes without using a pty. 0 is returned to indicate there is
no associated process. When the connection to the spawned process
is closed, so is the Tcl file identifier. The
-leaveopen
flag is similar to -open
except that -leaveopen
causes the file identifier to
be left open even after the spawn id is closed.
The -pty
flag causes a pty to be opened but no
process to be spawned. 0 is returned to indicate there is no
associated process. spawn_id is set as usual.
The variable spawn_out(slave,fd) is set to a file identifier corresponding to the pty slave. It can be closed using "close -slave".
The -ignore
flag is not implemented on
Windows. On Unix systems, this flag names a signal to be
ignored in the spawned process. Otherwise, signals get the default
behavior. Signals are named as in the exp_trap
command, except that each signal requires a separate flag.
The -environment
flag takes a list of name/value
pairs in the form array
get
would return to represent the environment to
use.
The -directory
flag sets the starting directory for
the spawned process.
The -trap
flag is not available on
Windows.
This command causes following statements to be printed before being executed. (Tcl's trace command traces variables.) level indicates how far down in the call stack to trace. For example, the following command runs Expect while tracing the first 4 levels of calls, but none below that.
expect -c "strace 4" script.exp
The -info
flag causes strace to return a
description of the most recent non-info arguments given.
This command changes terminal modes similarly to the external
stty command. On Windows, exp_stty
does not do
redirection or accept the rows or columns options.
By default, the controlling terminal is accessed. On Unix systems, other terminals can be accessed by appending "< /dev/tty..." to the command. (Note that the arguments should not be grouped into a single argument.)
Requests for status return it as the result of the command. If no status is requested and the controlling terminal is accessed, the previous status of the raw and echo attributes are returned in a form that can later be used by the command.
For example, the arguments raw
or
-cooked
put the terminal into raw mode. The arguments
-raw
or cooked
put the terminal into
cooked mode. The arguments echo
and -echo
put the terminal into echo and noecho mode respectively.
The following example illustrates how to temporarily disable echoing. This could be used in otherwise automatic scripts to avoid embedding passwords.
exp_stty -echo exp_send_user "Password: " expect_user -re "(.*)\n" set password $expect_out(1,string) exp_stty echo
Not applicable on Windows - use Tcl's exec
command instead. On Unix systems, this gives args to
sh as input, just as if it had been typed as a command from a
terminal. Expect waits until the shell terminates. The return
status from sh is handled the same way that exec
handles its return status.
This command returns a timestamp. With no arguments, the number
of seconds since the epoch is returned. Use Tcl's
clock
command instead.
The -format
flag introduces a string that is
returned, but with substitutions made according to the POSIX rules
for strftime. For example %a
is replaced by an
abbreviated weekday name (i.e., Sat). Others are:
%a
- abbreviated weekday name%A
- full weekday name%b
- abbreviated month name%B
- full month name%c
- date-time as in: Wed Oct 6 11:45:56 1993%d
- day of the month (01-31)%H
- hour (00-23)%I
- hour (01-12)%j
- day (001-366)%m
- month (01-12)%M
- minute (00-59)%p
- am or pm%S
- second (00-61)%u
- day (1-7, Monday is first day of week)%U
- week (00-53, first Sunday is first day of
week one)%V
- week (01-53, ISO 8601 style)%w
- day (0-6)%W
- week (00-53, first Monday is first day of
week one)%x
- date-time as in: Wed Oct 6 1993%X
- time as in: 23:59:59%y
- year (00-99)%Y
- year as in: 1993%Z
- timezone (or nothing if not
determinable)%%
- a bare percent signOther % specifications are undefined. Other characters will be passed through untouched. Only the C locale is supported.
The -seconds
flag introduces a number of seconds
since the epoch to be used as a source from which to format.
Otherwise, the current time is used.
The -gmt
flag forces timestamp output to use the
GMT timezone. With no flag, the local timezone is used.
This causes the given command to be executed upon future receipt of any of the given signals. The command is executed in the global scope. If command is absent, the signal action is returned. If command is the string SIG_IGN, the signals are ignored. If command is the string SIG_DFL, the signals are reset to the system default. The signals argument is either a single signal or a list of signals.
Signal manipulation beyond the seven signals abstracted via
ANSI's signal.h is not supported on Windows, nor are
Windows-specific ones such as CTRL_SHUTDOWN_EVENT
.
With no arguments (or the argument -number
),
exp_trap
returns the signal number of the trap command
currently being executed.
The -code
flag uses the return code of the command
in place of whatever code Tcl was about to return when the command
originally started running.
The -interp
flag causes the command to be evaluated
using the interpreter active at the time the command started
running, rather than when the trap was declared.
The -name
flag causes the exp_trap
command to return the signal name of the trap command currently
being executed.
The -max
flag causes the exp_trap
command to return the largest signal number that can be set.
For example, the command "exp_trap {exp_send_user "Ouch!"}
SIGINT"
will print "Ouch!" each time the user presses
^C.
By default, SIGINT (which can usually be generated by pressing ^C) and SIGTERM cause Expect to exit. This is due to the following trap, created by default when Expect starts.
exp_trap exit {SIGINT SIGTERM}
If you use the -D flag to start the debugger, SIGINT is redefined to start the interactive debugger. This is due to the following trap:
exp_trap {exp_debug 1} SIGINT
The debugger trap can be changed by setting the environment variable EXPECT_DEBUG_INIT to a new trap command.
You can, of course, override both of these just by adding trap
commands to your script. In particular, if you have your own
"exp_trap exit SIGINT
", this will override the
debugger trap. This is useful if you want to prevent users from
getting to the debugger at all.
If you want to define your own trap on SIGINT but still trap to the debugger when it is running, use:
if {![exp_debug]} {exp_trap mystuff SIGINT}
Alternatively, you can trap to the debugger using some other signal.
The exp_trap
command will not let you override the
action for SIGALRM as this is used internally to Expect. The
disconnect command sets SIGALRM to SIG_IGN (ignore). You can
re-enable this as long as you disable it during subsequent spawn
commands.
This command is useful for assuring that the script is
compatible with the current version of Expect, however, the more
modern "package require Expect [version]
"
command should be used instead.
This command delays until a spawned process (or the current process if none is named) terminates.
exp_wait
normally returns a list of four integers.
The first integer is the pid of the process that was waited upon.
The second integer is the corresponding spawn id. The third integer
is -1 if an operating system error occurred, or 0 otherwise. If the
third integer was 0, the fourth integer is the status returned by
the spawned process. If the third integer was -1, the fourth
integer is the value of errno set by the operating system. The
global variable errorCode is also set.
This command waits until one of the patterns matches the output of a spawned process, a specified time period has passed, or an end-of-file is seen. If the final body is empty, it may be omitted.
Patterns from the most recent expect_before
command are implicitly
used before any other patterns. Patterns from the most recent
expect_after
command are
implicitly used after any other patterns.
If the arguments to the entire expect
statement
require more than one line, all arguments may be "braced" into one
so as to avoid terminating each line with a backslash. In this one
case, the usual Tcl substitutions will occur despite the
braces.
If a pattern is the keyword eof
, the corresponding
body is executed upon end-of-file. If a pattern is the keyword
timeout
, the corresponding body is executed upon
timeout. If no timeout keyword is used, an implicit null action is
executed upon timeout. The default timeout period is 10 seconds but
may be set, for example to 30, by the command "set timeout 30". An
infinite timeout may be designated by the value -1. If a pattern is
the keyword default
, the corresponding body is
executed upon either timeout or end-of-file.
If a pattern matches, then the corresponding body is executed.
The expect
command returns the result of the body (or
the empty string if no pattern matched). In the event that multiple
patterns match, the one appearing first is used to select a
body.
Each time new output arrives, it is compared to each of the
patterns in the order they are listed. Thus, you may test for
absence of a match by making the last pattern something guaranteed
to appear, such as a prompt. In situations where there is no
prompt, you must use timeout
as you would if you were
interacting with the program manually.
Patterns are specified in three ways. By default, patterns are
specified as with Tcl's string
match
command. (Such patterns are also similar to
C-shell regular expressions usually referred to as "glob"
patterns). The -gl
flag may be used to protect
patterns that might otherwise match expect
flags from
doing so. Any pattern beginning with a "-" should be protected this
way. (All strings starting with "-" are reserved for future
options.)
For example, the following fragment looks for a successful
login. Note that abort
is presumed to be a procedure
defined elsewhere in the script.
expect { busy {puts busy\n ; exp_continue} -re "failed|invalid password" abort timeout abort connected }
Quotes are necessary on the fourth pattern since it contains a space, which would otherwise separate the pattern from the action. Patterns with the same action (such as the 3rd and 4th) require listing the actions again. This can be avoided by using regexp-style patterns (see below). More information on forming glob patterns can be found in the Tcl manual.
Regexp-style patterns follow the syntax defined by Tcl's
regexp
(short for "regular expression") command. An introduction to
writing regular expressions can be found in the Regular Expression Primer. regexp
patterns are introduced with the flag -re
. The
previous example can be rewritten using a regexp as:
expect { busy {puts busy\n ; exp_continue} -re "failed|invalid password" abort timeout abort connected }
Both types of patterns are "unanchored". This means that patterns do not have to match the entire string, but can begin and end the match anywhere in the string (as long as everything else matches). Use ^ to match the beginning of a string, and $ to match the end. Note that if you do not wait for the end of a string, your responses can easily end up in the middle of the string as they are echoed from the spawned process. While still producing correct results, the output can look unnatural. Thus, use of $ is encouraged if you can exactly describe the characters at the end of a string.
Note that in many editors, the ^ and $ match the beginning and
end of lines respectively. However, because expect
is
not line oriented, these characters match the beginning and end of
the data (as opposed to lines) currently in the expect
matching buffer. (Also, see the note below on "system
indigestion.")
The -ex
flag causes the pattern to be matched as an
"exact" string. No interpretation of *, ^, etc is made (although
the usual Tcl conventions must still be observed). Exact patterns
are always unanchored.
The -nocase
flag causes uppercase characters of the
output to compare as if they were lowercase characters. The pattern
is not affected.
While reading output, more than 2000 bytes can force earlier
bytes to be "forgotten". This may be changed with the function
match_max
. (Note that excessively large values can
slow down the pattern matcher.) If patlist is
full_buffer
, the corresponding body is executed if
match_max
bytes have been received and no other
patterns have matched. Whether or not the full_buffer
keyword is used, the forgotten characters are written to
expect_out(buffer).
If patlist is the keyword null
, and nulls
are allowed (via the remove_nulls
command), the
corresponding body is executed if a single ASCII 0 is matched. It
is not possible to match 0 bytes via glob or regexp patterns.
Upon matching a pattern (or eof or full_buffer), any matching
and previously unmatched output is saved in the variable
expect_out(buffer). Up to 9 regexp substring matches are
saved in the variables expect_out(1,string) through
expect_out(9,string). If the -indices
flag is
used before a pattern, the starting and ending indices (in a form
suitable for lrange
)
of the 10 strings are stored in the variables
expect_out(X,start) and expect_out(X,end) where X
is a digit, corresponds to the substring position in the buffer. 0
refers to strings that matched the entire pattern and is generated
for glob patterns as well as regexp patterns. For example, if a
process has produced output of "abcdefgh\n", the result of:
expect "cd"
is as if the following statements had executed:
set expect_out(0,string) cd set expect_out(buffer) abcd
and "efgh\n" is left in the output buffer. If a process produced the output "abbbcabkkkka\n", the result of:
expect -indices -re "b(b*).*(k+)"
is as if the following statements had executed:
set expect_out(0,start) 1 set expect_out(0,end) 10 set expect_out(0,string) bbbcabkkkk set expect_out(1,start) 2 set expect_out(1,end) 3 set expect_out(1,string) bb set expect_out(2,start) 10 set expect_out(2,end) 10 set expect_out(2,string) k set expect_out(buffer) abbbcabkkkk
and "a\n" is left in the output buffer. The pattern "*" (and -re ".*") will flush the output buffer without reading any more output from the process.
Normally, the matched output is discarded from Expect's internal
buffers. This may be prevented by prefixing a pattern with the
-notransfer
flag. This flag is especially useful in
experimenting (and can be abbreviated to "-not
" for
convenience).
The spawn id associated with the matching output (or eof or full_buffer) is stored in expect_out(spawn_id).
The -timeout
flag causes the current expect command
to use the following value as a timeout instead of using the value
of the timeout variable.
By default, patterns are matched against output from the current
process, however the -i
flag declares the output from
the named spawn_id list be matched against any following patterns
(up to the next -i
). The spawn_id list should either
be a whitespace separated list of spawn_ids or a variable referring
to such a list of spawn_ids.
For example, the following example waits for "connected" from the current process, or "busy", "failed" or "invalid password" from the spawn_id named by $proc2.
expect { -i $proc2 busy {puts busy\n ; exp_continue} -re "failed|invalid password" abort timeout abort connected }
The value of the global variable any_spawn_id may be
used to match patterns to any spawn_ids that are named with all
other - i flags in the current expect
command. The spawn_id from a -i
flag with no
associated pattern (i.e., followed immediately by another
-i
) is made available to any other patterns in the
same expect
command associated with
any_spawn_id.
The -i
flag may also name a global variable, in
which case the variable is read for a list of spawn ids. The
variable is reread whenever it changes. This provides a way of
changing the I/O source while the command is in execution. Spawn
ids provided this way are called "indirect" spawn ids.
Actions such as break
and continue
cause control structures (i.e., for
,
proc
)
to behave in the usual way. The command exp_continue
allows expect
itself to continue executing rather than returning as it normally
would.
This is useful for avoiding explicit loops or repeated expect
statements. The following example is part of a fragment to automate
rlogin. The exp_continue
avoids having to write a
second expect
statement (to look for the prompt again)
if the rlogin prompts for a password.
expect { Password: { exp_stty -echo exp_send_user "password (for $user) on $host: " expect_user -re "(.*)\n" exp_send_user "\n" exp_send "$expect_out(1,string)\r" exp_stty echo exp_continue } incorrect { send_user "invalid password or account\n" exit } timeout { send_user "connection to $host timed out\n" exit } eof { exp_send_user \ "connection to host failed: $expect_out(buffer)" exp_exit } -re $prompt }
For example, the following fragment might help a user guide an
interaction that is already totally automated. In this case, the
terminal is put into raw mode. If the user presses "+", a variable
is incremented. If "p" is pressed, several returns are sent to the
process, perhaps to poke it in some way.
In each case, the exp_continue
allows the current
expect
to continue pattern matching after executing
the current action.
stty raw -echo expect_after { -i $user_spawn_id "p" {send "\r\r\r"; exp_continue} "+" {incr foo; exp_continue} "quit" exit }
By default, exp_continue
resets the timeout timer.
The timer is not restarted, if exp_continue
is called
with the -continue_timer
flag.
This command works identically to the expect_before
command except that if
patterns from both expect
and
expect_after
can match, the expect
pattern is used.
This command takes the same arguments as expect
,
however it returns immediately. Patterns are tested whenever new
input arrives. The patterns timeout
and
default
are meaningless to
expect_background
and are silently discarded.
Otherwise, the expect_background
command uses
expect_before
and expect_after
patterns
just like expect
does.
When expect_background
actions are being evaluated,
background processing for the same spawn id is blocked. Background
processing is unblocked when the action completes. While background
processing is blocked, it is possible to do a (foreground)
expect
on the same spawn id.
It is not possible to execute an expect
while an
expect_background
is unblocked. The
expect_background
for a particular spawn id is deleted
by declaring a new expect_background
with the same
spawn id. Declaring expect_background
with no pattern
removes the given spawn id from the ability to match patterns in
the background.
This command takes the same arguments as expect
does, however it returns immediately.
Pattern-action pairs from the most recent
expect_before
with the same spawn id are implicitly
added to any following expect
commands. If a pattern
matches, it is treated as if it had been specified in the
expect
command itself, and the associated body is
executed in the context of the expect
command. If
patterns from both expect_before
and
expect
can match, the expect_before
pattern is used.
If no pattern is specified, the spawn id is not checked for any patterns.
Unless overridden by a -i
flag,
expect_before
patterns match against the spawn id
defined at the time that the expect_before
command was
executed (not when its pattern is matched).
The -info
flag causes expect_before
to
return the current specifications of what patterns it will match.
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
expect_before -info -i $proc
At the most, one spawn id specification may be given. The flag
-indirect
suppresses direct spawn ids that come only
from indirect specifications.
Instead of a spawn id specification, the flag -all
will cause -info
to report on all spawn ids.
The output of the -info
flag can be reused as the
argument to expect_before
.
This command is like expect
but it reads characters from /dev/tty (i.e. keystrokes from the
user). By default, reading is performed in cooked mode. Thus, lines
must end with a return in order for expect
to see
them. This may be changed via exp_stty
.
This command is like expect
but it reads characters from stdin (i.e. keystrokes from the user).
By default, reading is performed in cooked mode. Thus, lines must
end with a return in order for expect
to see them.
This may be changed via exp_stty
.
Expect automatically knows about two built-in libraries for
Expect scripts. These are defined by the directories named in the
variables exp_library
and
exp_exec_library
. Both are meant to contain utility
files that can be used by other scripts. exp_library contains
architecture-independent files. exp_exec_library contains
architecture-dependent files. Depending on your system, both
directories may be totally empty. The existence of the file
$exp_exec_library/catbuffers describes whether your /bin/cat
buffers by default.