如何设置读取命令以执行而无需在 shell 中按 Enter 按钮? [英] How to set read command to execute without having to press Enter button in shell?

查看:25
本文介绍了如何设置读取命令以执行而无需在 shell 中按 Enter 按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码将用户字符给定的值分配给变量 G:

I use the below code to assign a given by the user character to variable G:

read G

但是,为了继续执行我的脚本,我需要按 Enter 按钮.是否可以以某种方式设置读取命令,以便在收到来自 stdin 的一个字母后立即将进程显示到下一行?

However in order to move forward with executing of my script I need to press enter button. Is it possible to set the read command somehow that it show process forward to the next line immediately after it receive the one letter from stdin?

推荐答案

我认为 dd 可能能够做到这一点,所以我尝试了它,但没有取得任何进展.然而,谷歌发现 适合我,我在此处对其进行了调整:

I thought dd might be able to do this, so I tried it out and didn't get anywhere. However, Google found this for me and I adapted it here:

readOne () {
    local oldstty
    oldstty=$(stty -g)
    stty -icanon -echo min 1 time 0
    dd bs=1 count=1 2>/dev/null
    stty "$oldstty"
}

在脚本的开头定义一次这个函数,然后你可以像这样使用它:

Define this function once at the beginning of your script, then you can use it like this:

char=$(readOne)    # get the character
echo $char         # print the character (or you can do something else with it)

这篇关于如何设置读取命令以执行而无需在 shell 中按 Enter 按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆