Expect script: How to set return value of a command to a variable and exit from script if the return value is not 0?

157 Views Asked by At

I am running a command in expect script and I want to exit the expect script if command return value is not 0. I set the variable ret to "$?" like this, which is not working:

send "./$SCRIPT_NAME >> out.txt &\r"
expect "~#"
set ret $?
if { $ret != 0} {
    exit $ret
}

But I get this output:

expected integer but got "$?"
    while executing
"exit $ret"
    invoked from within
"if { $ret != 0} {
    exit $ret
}"

What is the equivalent of $? in expect?

1

There are 1 best solutions below

4
glenn jackman On BEST ANSWER

This is a bit of a pain in expect.

Firstly, since you need to get the exit status, you don't want to launch the script in the background. You'd have to use the shell's wait command anyway to get the exit status.

Next, you have to ask the shell to print out the exit status and capture that with the expect command. Note that expect returns \r\n for line endings.

send "./$SCRIPT_NAME >> out.txt; echo $?\r"

expect -re {(\d+)\r\n~#}
# ..........^^^^^
# exit status is captured in the 1st set of parens

set ret $expect_out(1,string)
if { $ret != 0} {
    exit $ret
}