期望命令输出存储在变量中

时间:2010-07-21 12:32:27

标签: expect

我写了下面的剧本。


#! /usr/bin/expect
set timeout 180
spawn /vobs/iov/rnc/bin/moshell/moshell -d db.dat
expect {
  -re "OFFLINE_DB.DAT.*" { }
        timeout        { 
     error "\n######## Timeout - when logging in\n"
 }
        eof            { 
     error "\n######## eof - when logging in\n"
 } 
}

set db_prompt "SQL>"
send "select id from motype_r1 where data = 'PlugInUnit';\r"
expect {
  -re "OFFLINE_DB.DAT>"  
}    
 exit

现在,我想在变量中得到表的输出,即

+------+
| id   |
+------+
|   19 |
+------+
Query Done: 1 record selected

并匹配正则表达式以在另外一个变量中得到'19'。

任何人都可以帮我解决这个问题。

/ Akshya

1 个答案:

答案 0 :(得分:1)

在这段代码中,您应该能够使用正则表达式来匹配SELECT查询的输出,然后将其存储在变量中。

send "select id from motype_r1 where data = 'PlugInUnit';\r"
expect {
  -re {(\|[^\d]*(\d+).*\|)} { set id $expect_out(1,string) ; exp_continue }
  -re "OFFLINE_DB.DAT>"  
}

(请原谅我使用的有点丑陋的正则表达式,但它应该匹配return语句中的最后一个数字id。)

$expect_out(1,string)引用正则表达式中的第一个字符串匹配,然后exp_continue将导致期望继续期望输出,直到它看到“OFFLINE_DB.DAT”消息(我认为不需要{{顺便说一下,1}}前缀。

希望有效!