Code Monkey home page Code Monkey logo

Comments (3)

azl397985856 avatar azl397985856 commented on June 10, 2024

交互式输入的原理

我们可以用 read 命令阻塞当前进程,请求标准输入。 当得到输入之后请求继续。

一个简单的例子:

#!/bin/bash

function confirm() {
    question="$1"
    read -n1 -p ${question} answer
    case ${answer} in
    Y | y) echo
        echo "Accepted";;
    N | n) echo
        echo "WA"
        exit;;
    esac
}
q="lucife.age<17"

confirm ${q}

采用类似的方法,我们可以获得不同类似的输入。 甚至可以让用户使用光标代替打字输入等。

如何自动化

知道了原理就好办了。但是仅仅知道上面的还不够,我们还需要知道一点,那就是标准输入时怎么一回事,以及我们可以模拟标准输入么?

我们知道管道实际上就是将前一个命令的标准输出定向到下一个的标准输入了。比如:

echo y | bash ./lucifer

其中 ./lucifer 就是上面我给的例子的脚步的磁盘地址。

可以看到,这次不再阻塞了,我们可以直接看到输出了Accepted。

扩展

有趣的是,有一个命令 yes 就是做这个事情的。 你一旦输入了 yes ,那么就会产生无数的 y。 上面的例子可以用 yes 改造:

yes | bash ./lucifer

效果是一样的。

from fe-interview.

stale avatar stale commented on June 10, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

from fe-interview.

stale avatar stale commented on June 10, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

from fe-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.