shell脚本中的交互式输入自动化

shell中有时我们需要交互,但是呢我们又不想每次从stdin输入,想让其自动化,这时我们就要使shell交互输入自动化了。
1    利用重定向
    重定向的方法应该是最简单的
例:
以下的test.sh是要求我们从stdin中分别输入no,name然后将输入的no,name打印出来
[root@localhost ~]# cat test.sh
#! /bin/bash
read -p "enter number:" number
read -p "enter name:" name
echo you have entered $number, $name
 
以下是作为输入的文件内容:
[root@localhost ~]# cat input.data 
001
balabala
 
然后我们利用重定向来完成交互的自动化:
[root@localhost ~]# ./test.sh < input.data 
you have entered 001,balabala
 
2 利用管道完成交互的自动化
这个就是利用管道特点,让前个命令的输出作为后个命令的输入完成的
也用上面例子举例:
[root@localhost test]# echo -e "001alalbala " | sh test.sh 
you have entered 001, balabala
上面中的 "001alabala " 中的“ ”是换行符的意思。
 
3   利用expect
expect是专门用来交互自动化的工具,但它有可能不是随系统就安装好的,有时需要自己手工安装该命令
查看是否已经安装:rpm -qa | grep expect
安装命令:yum install expect.x86_64
以下脚本完成跟上述相同的功能
[root@localhost ~]# cat expect_test.sh 
#! /usr/bin/expect
spawn sh test.sh
expect "enter number:"
send "001 "
expect "enter name:"
send "balabala "
expect off
 
注意:第一行是/usr/bin/expect,这个是选用解释器的意思,我们shell一般选的是 /bin/bash,这里不是
spawn: 指定需要将哪个命令自动化
expect:需要等待的消息
send:是要发送的命令
expect off:指明命令交互结束
 
运行命令可用:expect expect_test.sh
或把expect加入环境变量(测试未成功)
原文地址:https://www.cnblogs.com/rzxiaojia/p/6639479.html