以下用于测试的脚本。我希望它能够连续读取行并打印读取的数量,但它只能在第一次输入之前工作。在我输入一些内容(甚至没有内容)并按下“输入”后 - 脚本冻结,我无法弄清楚原因,请解释。
这里是剧本:
#!/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'
答案 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.
在你的例子中: