leander
leander

Reputation: 8737

How to gobble any buffered STDIN before "pause" in a batch file?

A fair number of our "automate a group of installers" .bat files end with something like:

:success
ECHO Success! (as far as I can tell)
ECHO.
ECHO.
ECHO Press any key to reboot...
ECHO.
ECHO.
PAUSE >NUL
shutdown -r
EXIT /b

If the prior commands have taken a while, there's a good chance the user has accidentally hit a key well before we reach the :success label. Since STDIN seems to be buffered, this will cause the PAUSE to be dismissed instantly.

What I'd rather have is something like:

GOBBLE_STDIN_SOMEHOW
PAUSE >NUL
shutdown -r

How would I "flush" STDIN, consuming anything that was there, but not waiting if there's nothing buffered?

Upvotes: 1

Views: 1206

Answers (2)

jeb
jeb

Reputation: 82390

I don't see your problem, as pause seems to work like you want.
It flushes the input buffer before waiting.

Tested with this (I used Vista)

@echo off
echo Press now some keys
ping -n 3 localhost > nul
echo Stop pressing
ping -n 3 localhost > nul
echo Now Pause starts (and waits)
pause

Upvotes: 0

Aacini
Aacini

Reputation: 67236

I suggest you to use an alternate method:

:success
ECHO Success! (as far as I can tell)
ECHO.
ECHO.
ECHO Press ENTER key to reboot...
ECHO.
ECHO.
SET /P DUMMY=
shutdown -r
EXIT /b

However, this method fail if the user accidentally hit ENTER...

Upvotes: 1

Related Questions