How to expect a newline in expect script

expectnewlines

Consider this interactive script:

#!/usr/bin/env bash
set -eu
while true; do
    read -p '> '
    if [ "$REPLY" == quit ]; then
        break
    fi
    echo "'$REPLY'"
done

Now I want expect to interact with it:

#!/usr/bin/env bash
set -eu
echo '
    spawn ./1.sh
    expect >
    send cmd1\n
    expect {\n> }
    send quit\n
' | expect -d

But when I run it, it says:

...
expect: does " cmd1\r\n'cmd1'\r\n> " (spawn_id exp6) match glob pattern "\n> "? no
expect: timed out
send: sending "quit\n" to { exp6 }

Why doesn't it match? How can I detect appearing of a new prompt (finishing a command)?

Best Answer

In the expect tcl language, there is a difference between strings quoted with "" and {}. You can see this in the 2 examples:

$ expect -c 'puts "a\nb"'
a
b
~ $ expect -c 'puts {a\nb}'
a\nb

Your glob pattern {\n> } consists of 4 characters to match for, but the \n is not specially interpreted as an escape. If you use pattern "\n> " your match should work. Or you can use flag -re instead of the default glob pattern, and the two characters will be interpreted by the regexp code as an escape, -re {\n> }.

Related Question