Zlyuuka
Zlyuuka

Reputation: 400

bash 'read -t 0' freezes after input line

The following script used for test. I expect it to continuously read the lines and print how many were read, but it works only until first input. After I input something (or even nothing) and press 'Enter' - script freezes and I can't figure out why, please explain.

Here the script:

#!/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

Here its output:

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'

Upvotes: 2

Views: 332

Answers (1)

user803422
user803422

Reputation: 2814

Excerpt from the bash man page, about 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.

In your example:

  • before you press 'Enter', no data is available, the return status is different from zero and the while-loop breaks.
  • as soon as you press 'Enter', data is available, but not read, the return status is zero, the while-loop continues forever (because the available data is never actually read).

Upvotes: 2

Related Questions