Linux Bash 使用expect来处理脚本的交互场景

659 阅读1分钟

expect的简单示例 比如脚本需要输入一个变量的值,

$ cat ask
#!/bin/bash

echo -n "Input your something:"
read something

echo "your input is: $something"
echo "end of testing"

怎么自动化使用这个脚本

#!/usr/bin/expect -f

set timeout -1
spawn ./ask
match_max 100000
expect -exact "Input your something:"
send -- "something\r"
expect eof

expect eof 表示脚本的结束

这个expect脚本可以使用autoexpect 来产生 autoexpect

在shell中使用expect,参考如下代码

#!/bin/bash

echo "expect script demo"

echo "The following script automatically deal with interaction"

expect <<!
set timeout 1
spawn ./ask
expect "something"
send "go demo"
expect eof
!

echo "expect script demo end"