How to close stdin from expect script

The problem is how to feed cat command from expect script and notify it about EOF.

The script:

#!/usr/bin/expect

spawn bash -c "echo READY; foo=\$(cat); echo DONE"
expect "READY\r\n"
send -- "Hello\n"

# This doesn't work
send \004

# This timesout
expect "DONE\r\n"

send \004 does nothing. Apparently, nothing converts this control sequence into EOF. How to fix/workaround it?

Running the script with expect -d:

$ expect -d test.exp
expect version 5.45
argv[0] = expect  argv[1] = -d  argv[2] = test.exp
set argc 0
set argv0 "test.exp"
set argv ""
executing commands from command file test.exp
spawn bash -c echo READY; foo=$(cat); echo DONE
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {36656}

expect: does "" (spawn_id exp4) match glob pattern "READY\r\n"? no
READY

expect: does "READY\r\n" (spawn_id exp4) match glob pattern "READY\r\n"? yes
expect: set expect_out(0,string) "READY\r\n"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "READY\r\n"
send: sending "Hello\n" to { exp4 }
send: sending "\u0004" to { exp4 }

expect: does "" (spawn_id exp4) match glob pattern "DONE\r\n"? no
Hello

expect: does "Hello\r\n" (spawn_id exp4) match glob pattern "DONE\r\n"? no
expect: timed out

  • your script works for me on macos and linux. try adding sleep 1 after send -- "Hello\n".

    – 

  • Thank you for trying it out! It doesn’t work on cygwin for me. Probably the issue is with pty config.

    – 

Leave a Comment