: " echo "string" 当输入两个字符并按下 Return 时,它输出: Enter-6ren">
gpt4 book ai didi

Linux Bash 'read' 和使用 -n nchars 处理换行符

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:01 27 4
gpt4 key购买 nike

以下代码:

read -n 3 -r -p "Enter up to 3 characters  -> : "
echo "string"

当输入两个字符并按下 Return 时,它输出:

Enter up to 3 characters  -> : 12
string

但是,当输入 3 个字符时,没有回车,它会产生:

Enter up to 3 characters  -> : 123string

我想看看:

Enter up to 3 characters  -> : 123
string

不幸的是,换行符\n 不是 $REPLY 变量的一部分,否则我可以检查它并在缺少换行符时输出回显。

我之所以需要这个是为了在输入无效时输出错误消息,所以使用 -N 或 -n 4 不是解决方案。

有什么想法吗?谢谢!

顺便说一句,我已经在考虑以下内容,它会产生我想要的输出,但不幸的是,我已经将“tput sc”用于其他用途,因此不能再次使用它。

echo; tput sc; tput cuu1
read -n 3 -r -p "Enter up to 3 characters -> : "
tput rc; echo "string"

最佳答案

您可以检查 REPLY 的长度是否符合您的预期。如果匹配,则没有按下 Enter,因此回显一个空行。

len=3
read -n $len -r -p "Enter up to 3 characters -> : "
(( ${#REPLY} == $len )) && echo
echo "string"

如果长度小于len,则必须按下Enter。

或者,如果用户绕过了输入控件,那么这可能并不重要,对吗?

关于Linux Bash 'read' 和使用 -n nchars 处理换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054450/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com