bash: non blocking read inside a loop
From help read
:
-t timeout time out and return failure if a complete line of input is
not read within TIMEOUT seconds. The value of the TMOUT
variable is the default timeout. TIMEOUT may be a
fractional number. If TIMEOUT is 0, read returns immediately,
without trying to read any data, returning success only if
input is available on the specified file descriptor. The
exit status is greater than 128 if the timeout is exceeded
So try:
while true
do
echo "$var"
IFS= read -r -t 0.5 -n 1 -s holder && var="$holder"
done
The holder
variable is used since a variable loses its contents when used with read
unless it is readonly (in which case it's not useful anyway), even if read
timed out:
$ declare -r a
$ read -t 0.5 a
bash: a: readonly variable
code 1
I couldn't find any way to prevent this.