输入脚本:
#!/bin/bash
#file name : interactive.sh
read -p "input number:" num;
read -p "input string:" str
echo num: $num str:$str;
命令行输入:
echo -e "1\nhelloworld\n" | ./interactive.sh
输入内容较多时也可以用单独的文件,从文件中导入交互式输入数据:
echo -e "1\nhelloworld\n" > input.data
./interactive.sh < input.data
用expect实现自动化:
expect默认情况下没有附带于常见的linux发行版,需要安装。
ubuntu14.04下安装:sudo apt-get install expect
#!/usr/bin/expect
#expect.sh
spawn ./interactive.sh
expect "input number"
send "1\n"
expect "intput string"
send "helloworld\n"
expect eof
#运行: ./expect.sh
命令解释:
spawn:参数指定需要自动化哪个命令
expect:参数提供需要等待的i消息
send:要发送的消息
expect eof 指明指令交互结束
注意头命令#!/usr/bin/expect,如果出现安装了expect但是找不到相关命令,请参考:
对于expect的隐式调用,所以需要在第一行声明对于本脚本代码的解释器。
具体解释不再详细论述,请见博文:http://blog.csdn.net/sanwu2010/article/details/14454237