stdoutexpect

expect output only stdout of the command and nothing else


How to write expect script which executes command and prints just the command's output?

I've tried various things but none works, e.g.

#!/usr/bin/expect
log_user 0
spawn bash
send "echo 1\r"
log_user 1
expect "1"
log_user 0
send "exit\r"
expect eof

Gives in output:

echo 1

While I need just "1" . I hope somebody knows simple solution how to fix my example


Solution

  • Capturing the output from sent commands is a bit of a pain in expect.

    Here's a more general case that does not rely on the log_user setting, it captures the output with a regular expression:

    #!/usr/bin/expect
    log_user 0
    spawn bash
    
    # set the prompt to a known value
    send "PS1='>'\r"
    expect -re {>$}
    
    # send a command: we don't know what the output is going to be
    send "echo \$RANDOM\r"
    
    # capture the portion of the output that occurs just before the prompt
    expect -re "\r\n(.*?)\r\n>$"
    puts "output is: $expect_out(1,string)"
    
    send "exit\r"
    expect eof
    

    A thought just occurred to me: if the command does not require any interaction, then expect is overkill: just use exec

    set output [exec bash -c {echo $RANDOM}]