Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 7 down vote accepted

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
    read -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.

share|improve this answer
1  
What I've tried before was using again the -t option but without holder variable and it was not working. Turns out that read doesn't hold the variable value even if there is no input in the given timeout. –  Artak Begnazaryan Dec 11 '14 at 16:48
    
@ArtakBegnazaryan Yes, perhaps I should have mentioned that, but I was looking for ways to disable it and lost track. –  muru Dec 11 '14 at 16:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.