Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux Bash脚本的运行顺序,为什么要将read命令排队?_Linux_Bash_Shell_Unix - Fatal编程技术网

Linux Bash脚本的运行顺序,为什么要将read命令排队?

Linux Bash脚本的运行顺序,为什么要将read命令排队?,linux,bash,shell,unix,Linux,Bash,Shell,Unix,我现在很困惑 我想做的是创建一个侦听器函数,它等待两个命令——问题是它应该只每隔200毫秒侦听一次,而忽略用户的其他输入 function foo() { read -sN1 _input case "${_input}" in A) echo 'Option A';; B) echo 'Option B';; esac } while true; do sleep 0.2 foo done 如果我“敲击”A键(或

我现在很困惑

我想做的是创建一个侦听器函数,它等待两个命令——问题是它应该只每隔200毫秒侦听一次,而忽略用户的其他输入

function foo() {

    read -sN1 _input

    case "${_input}" in

        A) echo 'Option A';;
        B) echo 'Option B';;
    esac
}

while true; do
    sleep 0.2
    foo
done

如果我“敲击”A键(或向上键)十次,它会写“选项A”十次(尽管速度很慢)——而它最多只能写三次。这是为什么?我该如何修复它?

您的终端将输入缓冲到您的程序中。为了使您的程序在睡眠时忽略接收到的输入,您应该在调用
read
之前清除输入缓冲区。据我所知,在bash中没有这样做的方法。

您可以将睡眠功能放在stdin关闭的块中:

  {
    sleep 0.2
  } <&- 

这就是我想出的有效方法。这不是很好,但很管用

function inputCommand() {

    _now=`date +%s%N | cut -b1-13`
    _time=$(($_now-$_timeout))

    if [ $_time -gt 500 ]; then
            $1
            _timeout=`date +%s%N | cut -b1-13`
    fi
}

function keyPressUp() {

    echo "Key Press Up"
}

function waitForInput() {

    unset _input
    read -sN1 _input

    case "${_input}" in

            A) inputCommand "keyPressUp";;
    esac
}

while true; do

        waitForInput
done

您的
读取也需要一个超时,否则您的程序将在最初的200毫秒睡眠后无限期地等待输入。这听起来是个好主意,但从未让它工作过。它以某种方式干扰了第二个read命令,没有任何内容被读取。然而,我提出了一个不同的解决方案——见下文。
function inputCommand() {

    _now=`date +%s%N | cut -b1-13`
    _time=$(($_now-$_timeout))

    if [ $_time -gt 500 ]; then
            $1
            _timeout=`date +%s%N | cut -b1-13`
    fi
}

function keyPressUp() {

    echo "Key Press Up"
}

function waitForInput() {

    unset _input
    read -sN1 _input

    case "${_input}" in

            A) inputCommand "keyPressUp";;
    esac
}

while true; do

        waitForInput
done