bash'read -t 0'在输入行后冻结

时间:2018-01-08 12:05:19

标签: bash

以下用于测试的脚本。我希望它能够连续读取行并打印读取的数量,但它只能在第一次输入之前工作。在我输入一些内容(甚至没有内容)并按下“输入”后 - 脚本冻结,我无法弄清楚原因,请解释。

这里是剧本:

#!/bin/bash

# test function
test()
{
  # read lines counter
  local x=0
  # read lines and count them
  while read -t 0 -s line; do ((x++)); done
  # print how many lines were read before cycle exits
  echo "exit after $x reads"
}

# read previous input
while read -t 0 -s; do :; done

# main loop
while true; do
  test
  sleep 1
done

这是它的输出:

root@devel:/xx/xxxx# ./rtest
exit after 0 reads
exit after 0 reads
exit after 0 reads
exit after 0 reads
exit after 0 reads
<== here I press 'Enter'
    and now I can only exit from it using 'Ctrl+C'

1 个答案:

答案 0 :(得分:2)

摘自bash手册页,关于read

If timeout is 0, read returns immediately, without trying to read any data.
The  exit  status is  0  if  input is available on the specified file
descriptor, non-zero otherwise.

在你的例子中:

  • 在您按“输入”之前,没有可用的数据,返回状态不为零,而且循环中断。
  • 一旦按下“输入”,数据就可用,但未读取,返回状态为零,while循环将永远继续(因为实际上从未读取过可用数据)。