Expect: How to get the exit code from spawned process
I am not quite sure if it a good idea to create a new Thread or "reopen" this 3-year old Thread, if you think it's better to reopened it, please excuse my spam in this Forum but I have the same Problem and don't get a solution out of the information of the thread. At the Moment I had a script that looks like this:
#!/usr/bin/expect -f
set pass [lindex $argv 0]
spawn <CMD>
expect {
-re "Password: " {
send "$pass\r"
}
expect eof
catch wait result
}
exit [lindex $result 3]
but wenn I execute this Script I get the error
can't read "result": no such variable
while executing
"lindex $result 3"
invoked from within
"exit [lindex $result 3]"
(file "./call_tests.exp" line 13)
I already found out that probably the problem is that the SSH-Session is already closed when I try to read the exit code. But I started yesterday to understand the expect-command so I am a complete newbie and I would very thanks full if someone can help me out. best regards Dan
You should write like this:
expect {
-re "Password: " {
send "$pass\r"
}
}
expect eof
catch wait result
exit [lindex $result 3]
or this:
expect {
-re "Password: " {
send "$pass\r"
exp_continue
}
eof {
catch wait result
}
}
exit [lindex $result 3]
According to expect's man page:
expect [[-opts] pat1 body1] ... [-opts] patn [bodyn]
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 recentexpect_after
command are implicitly used after any other patterns.If the arguments to the entire expect statement require more than one line, all the 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.