Search code examples
bashwhile-loopuser-inputsleep

Disable user input during sleep in while loop with read (bash)


I have this little bash script with a while loop, that waits for user input, does something and then sleeps for a while:

while true; do
  read input
  echo $input
  sleep 5
done

I don't want it to accept any user input during sleep. The problem is that any input entered in the shell during sleep is processed when the script continues. Is it possible to completely disable user input during the sleep period?

I've seen this: Disabling user input during an infinite loop in bash, but that doesn't really help me here, does it?

Hope someone can help me with this.


Solution

  • This is what's needed :

    #!/usr/bin/env bash
      
    hideinput(){
      [ -t 0 ] && stty -echo -icanon time 0 min 0
    }
    cleanup(){ 
      [ -t 0 ] && stty sane
    }
    trap cleanup EXIT
    trap hideinput CONT
    
    while true; do
      while read -t 0.001 -n 10000 discard; do :; done # Discard anything already inputted.
      cleanup
      read -p "Input something   :  " input
      hideinput
      echo "What you inputted : " $input
      sleep 5
    done