1
votes

I would like the following expect script to set a variable in the main bash script. In other words I would like to set $SSH_SUCCESS to a pass/fail string. I have tried using $expect_out and $::env(SSH_SUCCESS) but have been unsuccessful. How do I set a bash variable from expect?

expect << EOF
log_user 0
log_file $TEST_LOG
set timeout 5
spawn ssh root@$RADIO_IP

.....
....expect script, echoing the return of an SSH command...

send "echo\$?\n"
expect {
  "0" {
        send_user "SSH test: PASSED\r"
        SSH_SUCCESS="PASSED"
      }
  "1" {
        send_user "SSH test: FAILED\r"
        SSH_SUCCESS="FAILED"
      }


sleep 1
send_user "\n"
exit

EOF    

  echo $SSH_SUCCESS
2
There's no way for a script to set variables in another process. The script should output the results, and the parent script should capture it with $(...). - Barmar
Fair enough. How would I prepare a 'flag' in the conditional statement, and how would I read it in the parent script? - AFridgeTooFar

2 Answers

1
votes

I don't know Expect, but I think it's something like this

SSH_SUCCESS=$(expect <<EOF
...
expect {
  "0" {
        puts "PASSED"
      }
  "1" {
        puts "FAILED"
      }
...
EOF
)

echo $SSH_SUCCESS
0
votes

There is no way to set a variable.

This is another way to determine the exit status of Expect.

expect << EOF
log_user 0
log_file $TEST_LOG
set timeout 5
spawn ssh root@$RADIO_IP

.....
....expect script, echoing the return of an SSH command...

send "echo\$?\n"

expect -re "\[0-9\]+$"
#set latest command exit status to valiable "exit_code"
set exit_status \$expect_out(0,string)

if { \$exit_status == 0 } {
    send_user "SSH test: PASSED\r"
} else {
    send_user "SSH test: FAILED\r"
}

sleep 1
send_user "\n"
# exit expect as latest command exit status
exit \$exit_status
EOF

if [ $? -eq 0 ];then
    SSH_SUCCESS="PASSED"
else
    SSH_SUCCESS="FAILED"
fi
echo ${SSH_SUCCESS}