在无限循环中读取bash中的输入并对它做出反应 [英] Reading input in bash in an infinite loop and reacting to it

查看:48
本文介绍了在无限循环中读取bash中的输入并对它做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想等待1秒钟进行某些输入(我稍后将实现的选项). 或者我想让程序打印一些东西(稍后也会实现).我在尝试读取该功能的1个字符时遇到问题,这是我的代码:

So I want to wait 1 second for some input (options that i will implement later). Or i want the program to print something(will implement later too). I have run into a problem tho, when trying to read that 1 char for the function, here is my code:

while true
   do read $var -t 1
      case $var in
          ("h")
              help
              ;;
      esac
done

如果我在这种情况下尝试回显,程序确实会等待1秒钟,问题是它无法识别我的h输入,我该如何解决?

If I try to echo after the case, the program does wait for 1 second, the problem is it doesnt recognise my h input, how would i fix that?

推荐答案

我已对您的示例进行了一些修改,使其可以正常工作.读取语句中有错误.使用read var代替read $var.现在,此更正后的样本还将识别h输入.

I've modified your sample slightly so that it works. There was an error in the read statement. use read varinstead of read $var. This corrected sample will now recognise also the h input.

与您的问题有关,为什么不等第二秒(这很难确定,所以我将超时时间稍微增加了;-))?这是因为当您输入内容时,读取超时会中断.就像参数名称说的那样,是用户输入的超时.因此,如果用户输入了某些内容,则超时将被中断.

Related to your question Why it doesn't wait the second (which was btw. hard to determine so i increased the timeout a bit ;-) )? This is because when you enter something, the read timeout is interrupted. It is as the parameter name say's a timeout for the user input. So if the user input's something the timeout is interrupted.

#!/bin/bash

while true 
do
      echo 'wait for input ...'

      read -t 10 var

      echo 'got input ...'

      case $var in
        h)
          echo 'help'
        ;;
      esac
done

这篇关于在无限循环中读取bash中的输入并对它做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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