1

I'm writing a Korn shell script, and it will read input from the user. I would like to clear the keyboard buffer before calling the "read" command, so that the user doesn't cause problems by impatiently typing ahead. I might add that the intended audience for this script is myself. 🙂

I'm using the OpenBSD ksh, which appears to be a variant of ksh88. I do have ksh93 available, but would prefer to NOT rely on Bash.

Example code:

# Would like to clear stdin buffer here
echo "Are you sure?"
read input

case $input in
    y*|Y*)
        echo "You said yes!"
        ;;
    *)
        echo "You said no!"
        exit 1
        ;;
esac

EDIT: Basically I want to clear ALL data from stdin before calling the "read".

I'm currently experimenting with setting a signal handler for SIGALRM and using trap to implement a timeout on doing a "pre-read".

  • How would you determine that the user had typed ahead one, two or fifteen lines? Or whether he/she was sending (correct) input by piping a text file into the script? – Kusalananda Sep 6 '17 at 16:50
2

try like this

read -t 1 garbage;
echo "Are you sure?"
read input

case $input in
    y*|Y*)
        echo "You said yes!"
        ;;
    *)
        echo "You said no!"
        exit 1
        ;;
esac

EDIT: I just realized that this will remove only the first line you can put it in a loop:

while read -t 1 garbage; do
  sleep 0
done

echo "Are you sure?"
read input

case $input in
    y*|Y*)
        echo "You said yes!"
        ;;
    *)
        echo "You said no!"
        exit 1
        ;;
esac
  • Assuming ksh93 in which -t 1 means a one second timeout? – Kusalananda Sep 7 '17 at 14:43
  • yes, try also with -t 0 , I didn't test it enough. it works btw :) – Diego Roccia Sep 7 '17 at 14:45
  • This works. It would have been nice to have done it easily in the default ksh88, but using ksh93 is acceptable to me. Thanks! – m0j0 Sep 7 '17 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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