linux把做事的命令寫成一個.sh(二)

原文:https://blog.csdn.net/lufubo/...

shell中交互輸入自動化

shell中有時我們需要交互,但是呢我們又不想每次從stdin輸入,想讓其自動化,這時我們就要使shell交互輸入自動化了。這個功能很有用的喲。好好學習。

1 利用重定向

重定向的方法應該是最簡單的

例:

以下的test.sh是要求我們從stdin中分別輸入no,name然後將輸入的no,name打印出來

[root@localhost test]# cat test.sh

! /bin/bash

read -p "enter number:" no

read -p "enter name:" name

echo you have entered $no, $name

以下是作爲輸入的文件內容:

[root@localhost test]# cat input.data

1

lufubo

然後我們利用重定向來完成交互的自動化:

[root@localhost test]# ./test.sh < input.data

you have entered 1, lufubo

看吧!效果不錯吧!哈哈

2 利用管道完成交互的自動化

這個就是利用管道特點,讓前個命令的輸出作爲後個命令的輸入完成的

也用上面例子舉例:

[root@localhost test]# echo -e "1nlufbon" | ./test.sh

you have entered 1, lufbo

上面中的 "1nlufbon" 中的“n”是換行符的意思,這個比較簡單的。

3 利用expect

expect是專門用來交互自動化的工具,但它有可能不是隨系統就安裝好的,有時需要自己手工安裝該命令

查看是否已經安裝:rpm -qa | grep expect

以下腳本完成跟上述相同的功能

[root@localhost test]# cat expect_test.sh

! /usr/bin/expect

spawn ./test.sh

expect "enter number:"

send "1n"

expect "enter name:"

send "lufubon"

expect off

注意:第一行是/usr/bin/expect,這個是選用解釋器的意思,我們shell一般選的是 /bin/bash,這裏不是

spawn: 指定需要將哪個命令自動化

expect:需要等待的消息

send:是要發送的命令

expect off:指明命令交互結束

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章