zoukankan      html  css  js  c++  java
  • shell中交互输入自动化

    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 "1 lufbo " | ./test.sh 
    you have entered 1, lufbo
    上面中的 "1 lufbo " 中的“ ”是换行符的意思,这个比较简单的。
     
    3    利用expect
    expect是专门用来交互自动化的工具,但它有可能不是随系统就安装好的,有时需要自己手工安装该命令
    查看是否已经安装:rpm -qa | grep expect
    以下脚本完成跟上述相同的功能
    [root@localhost test]# cat expect_test.sh 
    #! /usr/bin/expect
    spawn ./test.sh
    expect "enter number:"
    send "1 "
    expect "enter name:"
    send "lufubo "
    expect off
     
    注意:第一行是/usr/bin/expect,这个是选用解释器的意思,我们shell一般选的是 /bin/bash,这里不是
    spawn: 指定需要将哪个命令自动化
    expect:需要等待的消息
    send:是要发送的命令
    expect off:指明命令交互结束
  • 相关阅读:
    什么是Flex 布局
    wx.navigateTo、wx.redirectTo和wx.switchTab三种导航方式的区别
    Ajax 工作原理 及 实例
    NodeJS之 Express框架 app.use(express.static)
    Parcel 入门 (一)
    打包工具的介绍
    CSS网页布局
    《拖延心理学》阅读要点
    PHP实现页面静态化
    PHP中的魔术方法
  • 原文地址:https://www.cnblogs.com/xingyunfashi/p/7888852.html
Copyright © 2011-2022 走看看