2013-07-23 39 views
1

我希望以下期望腳本在主bash腳本中設置變量。換句話說,我想將$ SSH_SUCCESS設置爲合格/不合格字符串。我曾嘗試使用$ expect_out和$ :: env(SSH_SUCCESS),但未成功。我如何設置一個bash變量來期望?如何獲得期望設置bash變量

expect << EOF 
log_user 0 
log_file $TEST_LOG 
set timeout 5 
spawn ssh [email protected]$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 
+1

腳本無法在另一個進程中設置變量。該腳本應該輸出結果,並且父腳本應該用'$(...)'來捕獲它。 – Barmar

+0

夠公平的。我將如何在條件語句中準備一個「標誌」,以及如何在父腳本中讀取它? – AFridgeTooFar

回答

1

我不知道期待,但我認爲這是這樣的

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

echo $SSH_SUCCESS 
0

沒有辦法設置一個變量。

這是另一種確定Expect退出狀態的方法。

expect << EOF 
log_user 0 
log_file $TEST_LOG 
set timeout 5 
spawn ssh [email protected]$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}