IanWatson
IanWatson

Reputation: 1739

Expect send to other process

I have a expect script which does the following:

Spawns a.sh -> a.sh waits for user input

Spawns b.sh -> runs and finishes

I now want to send input to a.sh but having difficulties getting this working.

Below is my expect script

 #!/usr/bin/expect
    spawn "./a.sh"
    set a $spawn_id
    expect "enter"

    spawn "./b.sh"
    expect eof

    send -i $a "test\r"

a.sh is

read -p "enter " group
echo $group
echo $group to file > file.txt

and b.sh is

echo i am b
sleep 5
echo xx

Upvotes: 0

Views: 968

Answers (2)

Dinesh
Dinesh

Reputation: 16446

Basically, expect will work with two feasible commands such as send and expect. In this case, if send is used, then it is mandatory to have expect (in most of the cases) afterwards. (while the vice-versa is not required to be mandatory)

This is because without that we will be missing out what is happening in the spawned process as expect will assume that you simply need to send one string value and not expecting anything else from the session.

After the following code

send "ian\n"

we have to make the expect to wait for something afterwards. You have used expect eof for the spawned process a.sh . In a same way, it can be added for the b.sh spawned process as well.

"Well, then why interact worked ?". I heard you.

They both work in the same manner except that interact will expect some input from the user as an interactive session. It obviously expect from you. But, your current shell script is not designed to get input and it will eventually quit since there is no much further code in the script and which is why you are seeing the proper output. Or, even having an expect code alone (even without eof) can do the trick.

Have a look at the expect's man page to know more.

Upvotes: 1

IanWatson
IanWatson

Reputation: 1739

I've just got this working using

spawn "./a.sh"
set a $spawn_id
expect "enter"

spawn "./b.sh"
expect eof

set spawn_id $a
send "ian\n"

interact

My question now is why do you need interact at the end?

Upvotes: 0

Related Questions