从没有换行的键盘读取数据

问题描述 投票:2回答:1

例如,我有一个强制用户输入正确数据的任务

echo -e "Enter digit (choices: 2, 3, 4, 5)\c"
tput sc
read -p ": " DIGIT

while ! [[ ${DIGIT:0:1} =~ ^[[:digit:]]$ ]]; do
    tput rc; tput cuu1
    echo -e " [incorrect, try again or CTRL-C for exit]\c"
    read -p ": " DIGIT
done

这是我需要它的方式除了一个,如果用户输入不正确的值 - 不是数字,然后底部出现空行。

$ ./i.sh
Enter digit (choices: 2, 3, 4, 5) [incorrect, try again or CTRL-C for exit]:
{empty line here}

是否有可能输入字符串总是停留在一行而没有跳起来?

更新:用户的输入可以是工作版本中的任何长度

和测试的正则表达式也可以。

bash console newline
1个回答
0
投票

您可以使用-nread标志,它允许您从用户接收单个字符,而无需输入Enter并跳转到下一行。

echo -e "Enter digit (choices: 2, 3, 4, 5)\c"
tput sc

while true; do
    read -n 1 -p ": " DIGIT
    if [[ ${DIGIT:0:1} =~ ^[[:digit:]]$ ]]; then
        break
    fi
    tput rc;
    echo -e " [incorrect, try again or CTRL-C for exit]\c"
done

echo
© www.soinside.com 2019 - 2024. All rights reserved.