Skip to content
Advertisement

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:

$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:

$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.

Advertisement

Answer

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. Like Tcl (from whence it came), it wants either double quotes or braces. This works just fine:

#!/usr/bin/expect

spawn ./runexp.sh

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

interact
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement