Windows – Why do the .BAT files on Windows 7 not PAUSE properly

batch filewindows 7

I've been playing around with writing batch files on my computer for some time, and I am confused about why PAUSE doesn't work like I thought(maybe I'm just doing it wrong idk, just really confused).

Basically I have:

@echo off
echo Hello!
pause
echo Hi again!
pause
echo HEY HEY!!
pause

and when it runs I get:

Hello!
Press any key to continue...

I then press just one key and this occurs:

Hi again!
Press any key to continue...
HEY HEY!!
Press any key to continue...

I don't understand why it skips the second PAUSE…I've noticed that if I was to do:

@echo off
echo Hello!
pause
echo Hi again!
pause
pause
echo HEY HEY!!
pause

then it will pause on "Hi again!" opposed to executing it without pause(however it will print "Press any key to continue…" two times consecutively)

I'm just really lost and can not proceed with my life until I know why it does this o:

Best Answer

Probable, simple explanation:

If you press a "special" key¹, then the actual characters sent into the "stdin" file of the software² running in the selected window will be, not just one character, but several.

The ACTUAL characters sent depend on the software setup and possibly "terminal emualation"³ - for starters

¹) e.g. f1, ..., f12, cursor movement and probably some more similar (home, end, ...?)
²) i.e. cmd.exe or anything similar
³) e.g. ancient ansi.sys having been loaded or not


Proof, creating, compiling a simple c program (Bash, gcc, Linux):

$ cat showhex.c 
#include <stdio.h>

int main(void) {

  int c=0;
  char hex[]="0123456789abcdef";
  while ( ! feof(stdin) ) {
    c=fgetc(stdin);
    fputc(hex[ (c >> 4) & 0x0f], stdout);
    fputc(hex[  c       & 0x0f], stdout);
    fputc(' ', stdout);

  }
}

$ gcc -o showhex showhex.c 

$ chmod 755 ./showhex

$ ls -hl showhex
-rwxr-xr-x 1 hannu hannu 8,7K dec  5 23:01 showhex

$ ./showhex
^[[A
1b 5b 41 0a ^[[C
1b 5b 43 0a ^[[B
1b 5b 42 0a ^[[D
1b 5b 44 0a ff 
$ 

Pressing a key shows the actual characters first, then as you press ENTER, the corresponding hex codes get printed.

Hold CTRL and hit D (CTRL+D, bash) or CTRL+Z and then ENTER (cmd.exe) to stop

The above example is from pressing
Cursor up, Enter
Cursor right, Enter
Cursor down, Enter
Cursor left, Enter
CTRL+D

Related Question