使用 expect 检查命令输出是否包含单词(否则错误)
use expect to check if command output contains a word (else error)
我想查看命令输出中是否有接口:
ip a
如果没有,那我要停止执行。我试过这段代码:
#!/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
但 exp_continue
继续 timeout
案例。
我建议你不需要为此期待:
set output [exec ip a]
if {[string first docker0 $output] != -1} {
puts "no docker0"
}
但是如果这是一个更大的 expect 程序的一部分,你可以这样写
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}]
我想查看命令输出中是否有接口:
ip a
如果没有,那我要停止执行。我试过这段代码:
#!/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
但 exp_continue
继续 timeout
案例。
我建议你不需要为此期待:
set output [exec ip a]
if {[string first docker0 $output] != -1} {
puts "no docker0"
}
但是如果这是一个更大的 expect 程序的一部分,你可以这样写
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}]