一般来说,我们在编写shell脚本时都是自动运行的,如果涉及到与用户的交付,如远程ssh终端输入用户名/密码。有时我们需要编写的脚本自动运行,而不需要人工干预,选择Expect实现是一个很好的方式。
来一个简单的例子:
hello.sh
#!/bin/sh
echo -n "What's your name?:"
read name
echo "Hello $name!"
exit 0
单独执行过程中需要在终端输入用户名称,执行结果如下,中间需要用户输入名称,脚本才会继续往下执行
执行截图:
nfssrv:/opt/mytest # sh hello.sh
What's your name?:
使用expect,编写一个应答脚本autoHello.sh,使hello.sh自动运行下去
autoHello.sh
#!/bin/bash
expect << END
spawn ./hello.sh
expect "name"
send "ssrs\n"
expect eof
exit
END
执行截图:
nfssrv:/opt/mytest # sh autoHello.sh
spawn ./hello.sh
What's your name?:ssrs
Hello ssrs!