Utsav
Utsav

Reputation: 5918

expect to send answers unknown number of times in Unix

I am writing a wrapper script for a ruby script. My requirement is whenever to send y as an input unknown number of times as a interactive part.

#!/usr/bin/expect

set timeout 20

spawn "./rubyScript"

while(true){

    # I am unaware of how many times this interactive part can come

    expect "*(y/n)" 

    send "y\r"

    interact

}

Upvotes: 0

Views: 404

Answers (2)

Dinesh
Dinesh

Reputation: 16438

Instead of using while, exp_continue can be used which is much efficient though.

#!/usr/bin/expect

set timeout 20
spawn "./rubyScript"
expect { 
        "*(y/n)" { send "y\r";exp_continue; }
        timeout { break }
    }
}

The command exp_continue allows expect itself to continue executing rather than returning as it normally would. This is useful for avoiding explicit loops or repeated expect statements.

By default, exp_continue resets the timeout timer. The timer is not restarted, if exp_continue is called with the -continue_timer flag.

Upvotes: 2

Dummy00001
Dummy00001

Reputation: 17430

Trick is to catch the timeout event from the expect statement. When expect has failed to find the (y/n) prompt within the specified timeout, we can assume that application is ready to become interactive.

For example (untested, do not have expect at hand):

#!/usr/bin/expect

set timeout 20
spawn "./rubyScript"
while {1} {
    expect { 
        "*(y/n)" { send "y\r" }
        timeout { break }
    }
}
interact

Send y if (y/n) prompt. If no prompt was seen - break the loop and interact.

Upvotes: 0

Related Questions