如何将read命令设置为执行而无需在shell中按Enter键?

goe*_*goe 4 unix shell

我使用下面的代码将用户角色的给定分配给变量G:

read G
Run Code Online (Sandbox Code Playgroud)

但是为了继续执行我的脚本,我需要按下回车键.是否有可能以某种方式将read命令设置为在收到stdin的一个字母后立即显示进程到下一行?

Mar*_*ers 5

如果你正在使用Bash:

read -n1 G
Run Code Online (Sandbox Code Playgroud)

您的系统默认配置和破折号使用破折号不支持此功能,因此你还需要改变你的脚本的第一行指定您希望您使用bash:

#!/bin/bash
Run Code Online (Sandbox Code Playgroud)


Pau*_*ce. 3

我想dd也许可以做到这一点,所以我尝试了一下,但没有任何进展。然而,谷歌为我找到了这个,我在这里进行了修改:

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

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

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