bash读取超时仅针对用户输入的第一个字符 [英] bash read timeout only for the first character entered by the user

查看:45
本文介绍了bash读取超时仅针对用户输入的第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的解决方案,该解决方案将读取具有以下功能的用户输入:

  • 如果没有用户输入,则在10秒后超时
  • 如果在开始的10秒钟内键入了第一个字符,用户将有无限的时间来完成答案.

我在

如果用户在输入第一个字符之前等待10秒钟,则输出将为:

 您叫什么名字?>(超时) 

如果用户在10秒钟内键入第一个字符,则他没有时间来完成此任务.输出将如下所示:

 您叫什么名字?>奥立佛你的名字叫奥利弗(Oliver) 

但是,有以下 caveat :第一个字符一旦输入就不可编辑,而其他所有字符都可以编辑(退格和重新键入).

您是否有解决警告的想法,或者您对请求的行为有其他简单的解决方案?

启用 readline 并添加 $ a 作为第二次读取的默认值.

 #读了一个字母,但不显示阅读-s -N 1 -t 10 -p您叫什么名字?>" a如果[-n"$ a"];然后#现在提供第一个字母,然后让用户输入#其余的都闲着.读-ei"$ a" b&&回声您的名字是$ b"别的回声(超时)"科幻 

在回答第一个字母后,它仍然显示第二个提示,但是我认为没有更好的方法来处理此问题.您无法取消" read 的超时.理想的解决方案是使用命令 other 而不是 read ,但是您必须自己编写该命令(可能是C语言中的可加载内置程序).

I have searched for a simple solution that will read user input with the following features:

  • timeout after 10 seconds, if there is no user input at all
  • the user has infinite time to finish his answer if the first character was typed within the first 10 sec.

I have found a solution to a similar request (timeout after each typed character) on Linux Read - Timeout after x seconds *idle*. Still, this is not exactly the feature, I was looking for, so I have developed a two line solution as follows:

read -N 1 -t 10 -p "What is your name? > " a
[ "$a" != "" ] && read b && echo "Your name is $a$b" || echo "(timeout)"

In case the user waits 10 sec before he enters the first character, the output will be:

What is your name? > (timeout)

If the user types the first character within 10 sec, he has unlimited time to finish this task. The output will look like follows:

What is your name? > Oliver
Your name is Oliver

However, there is following caveat: the first character is not editable, once it was typed, while all other characters can be edited (backspace and re-type).

Do you have any ideas for a resolution of the caveat or do you have another simple solution to the requested behavior?

解决方案

Enable readline and add $a as the default value for the second read.

# read one letter, but don't show it
read -s -N 1 -t 10 -p "What is your name? > " a

if [ -n "$a" ]; then
  # Now supply the first letter and let the user type
  # the rest at their leisure.
  read -ei "$a" b && echo "Your name is $b"
else
  echo "(timeout)"
fi

This still displays a second prompt after the first letter is answered, but I don't think there's a better way to handle this; there's no way to "cancel" a timeout for read. The ideal solution would be to use some command other than read, but you would have to write that yourself (probably as a loadable built-in, in C).

这篇关于bash读取超时仅针对用户输入的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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