Bash脚本运行顺序,为什么它将读取命令排队?

时间:2012-08-17 13:19:59

标签: linux bash shell unix

此刻我很困惑。

我想要做的是创建一个等待两个命令的侦听器函数 - 事情是它应该每两百毫秒监听一次并忽略用户的其他输入。

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键(或UP键)十次,它会将“选项A”写入十次(尽管,慢慢地) - 当它应该只有时间写入最多三次时。为什么 - 我该如何解决?

3 个答案:

答案 0 :(得分:3)

您的终端缓冲您的程序输入。为了使程序忽略它在休眠时收到的输入,你应该在调用read之前清除输入缓冲区。据我所知,在bash中无法做到这一点。

答案 1 :(得分:0)

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

  {
    sleep 0.2
  } <&- 

或者,您可以在睡眠后立即清除(读取和丢弃)stdin缓冲区:

sleep 0.2
read -t 1 -n 10000 discard

答案 2 :(得分:0)

这就是我提出的有效方法。 非常很好,但它确实有效。

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