Bash: non blocking read inside a loop

bashreadshell-script

I have a following small bash script

var=a

while true :
do
    echo $var
    sleep 0.5
    read -n 1 -s var
done

It just prints the character entered by the user and waits for the next input. What I want to do is actually not block on the read, i.e. every 0.5 second print the last character entered by the user. When user presses some key then it should continue to print the new key infinitely until the next key press and so on.

Any suggestions?

Best Answer

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.

Related Question