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 "001\balalbala\n" | sh test.sh
you have entered 001, balabala
上⾯中的 "001\balabala\n" 中的“\n”是换⾏符的意思。
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\n"
expect "enter name:"
shell最简单脚本
send "balabala\n"
expect off
注意:第⼀⾏是/usr/bin/expect,这个是选⽤解释器的意思,我们shell⼀般选的是 /bin/bash,这⾥不是
spawn: 指定需要将哪个命令⾃动化expect:需要等待的消息
send:是要发送的命令
expect off:指明命令交互结束
运⾏命令可⽤:expect expect_test.sh
或把expect加⼊环境变量(测试未成功)