简体   繁体   English

Linux Shell:我的`expect`脚本无法按预期工作

[英]Linux shell: my `expect` script doesn't work as expected

I've got a simple script like below, read 2 numbers from command line and add them together: 我有一个简单的脚本,如下所示,从命令行读取2个数字并将它们加在一起:

$cat runexp.sh
#!/bin/bash
echo "read 1st number"
read n1
echo "read 2nd number"
read n2
expr $n1 + $n2

It runs, no problem. 它可以运行,没问题。 Then I wrote an expect script like below: 然后我写了一个Expect脚本,如下所示:

$cat autorun.sh
#!/usr/bin/expect
spawn ./runexp.sh
expect 'read 1st number' {send "1"}
expect 'read 2nd number' {send "2"}
interact

Seems still it prompts to read from command line, after quite a long time, it ends. 似乎很长一段时间后,它仍然提示您从命令行读取,它结束了。

$./autorun.sh
spawn ./runexp.sh
read 1st number
5
4
3
5
4
3
read 2nd number
9

Where did I get wrong? 我在哪里弄错了? Thanks. 谢谢。

You have to send the newlines as well, otherwise it will just wait (at least until the default timeout, which I believe is ten seconds). 您还必须发送换行符,否则它将等待(至少直到默认超时,我认为是十秒)。

In addition, expect is not a fan of single quotes for enclosing strings. 另外, expect并不是封闭字符串的单引号的支持者。 Like Tcl (from whence it came), it wants either double quotes or braces. 就像Tcl(从何而来)一样,它需要双引号或大括号。 This works just fine: 这很好用:

#!/usr/bin/expect

spawn ./runexp.sh

expect "read 1st number" {send "1\n"}
expect {read 2nd number} {send "2\n"}

interact

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM