Search code examples
shellexpect

how to use caret ^ in expect statement


I want to use ^ in an expect script just like in the shell: grep '^god'. Running:

echo -e "abc god 1st line\ngod 2nd line" | grep ^god

Returns:

god 2nd line

But ^ seems not to work when run in the following expect script:

spawn myscript
expect "^god" {puts "catch line start with god"}

Solution

  • In expect, ^ matches the beginning of the buffer, which may not necessarily be the beginning of a line. (Similarly, $ matches the end of the buffer). For example,

    log_user 0
    spawn -noecho printf {a\nb\nc\n}
    expect  "^a" {puts ok}
    

    will work, because a is the first character output. However, matching for "^b" will not work. Instead you would need to match for newline, eg:

    expect "\nb" {puts ok2}
    

    Note that these are glob patterns; you can add the -gl prefix to be explicit. ^ and $ act the same in globs and regexps (-re prefix). You can use the -ex prefix to your pattern to instead match exactly for the caret character.