Search code examples
expect

use expect to check if command output contains a word (else error)


I want to check if there is an interface in the output of the command:

ip a

If there is not, then I want to stop the execution. I've tried this code:

#!/usr/bin/expect -f
spawn bash
set spi_bash $spawn_id
send "ip a\r"
expect {
    -re "docker0" {puts "docker0 is there\n"; exp_continue }
    timeout {puts "no docker0\n"; exit 1}
}
exit

but exp_continue continues to timeout case.


Solution

  • I'd suggest you don't need expect for this:

    set output [exec ip a]
    if {[string first docker0 $output] != -1} {
        puts "no docker0"
    }
    

    But if this is part of a larger expect program, you can write

    spawn bash
    set spi_bash $spawn_id
    
    # a regex matching your prompt: a dollar sign, a space, and end of input
    # adjust as required
    set prompt {\$ $}
    
    send "ip a\r"
    set has_docker false
    expect {
        -re "docker0" {set has_docker true; exp_continue}
        -re $prompt
    }
    
    send "exit\r"
    expect eof
    
    if {$has_docker}
        puts "docker0 is there"
    } else {
        puts "no docker0"
    }
    
    exit [expr {!$has_docker}]