2

When a Windows batch job has launched a program (executable), the user may press Ctrl-C to stop the program.

This causes Windows batch job to show "Terminate batch job (Y/N)" prompt and to wait for key presses.

How can I suppress this prompt and the need to press any key?

KTaTK
  • 21
  • 2

2 Answers2

0

You can use conditional execution in the command that launches the executable:

my_executable.exe && exit 0 || exit 1

This suppresses any prompting and exits the batch job with code 0 or 1, depending on the exit code of the executable.

This works both for Ctrl-C and Ctrl-Break.

KTaTK
  • 21
  • 2
  • 1
    This is related to [this superuser.com question](https://superuser.com/questions/35698/how-to-supress-terminate-batch-job-y-n-confirmation). – KTaTK Feb 19 '22 at 11:26
0

Given that CTRL-BREAK or CTRL-C already is a keypress, you may be looking for an answer that stops a batch script without the requirement to press CTRL-C or CTRL-BREAK.

This answer is in case that is your goal.

In Batch, you can use labels and IF statements to jump around in your script.

For example:

    @echo off

::  -- Lets print something to the screen.
    echo This is a test before the loop starts

::  -- Lets set a counter variable to 0, just to be sure.
    set counter=0
    
::  -- Set loop beginning point
:begin

::  -- Increase the counter by one but don't display the result to the screen
    set /a counter=counter+1 >nul
    
::  -- now, write it to the screen our way.
    echo Progress: %counter% of 10
    
::  -- pause the script for a second but without any displaying...
    ping localhost -n 2 >nul
    
::  -- see if we reached 10, if so jump to the exit point of the script.
    if %counter%==10 goto exit
    
::  -- if we reached this point, we have not jumped to the exit point.
::  -- so instead, lets jump back to the beginning point.
::  -- identation is used so the loop clearly stands out in the script
goto begin
    
::  -- set exit point for this script
:exit

::  -- lets print a message. We don't have to, but its nice, right?
    echo End of the script has been reached.

This produces the following output, assuming we wrote c:\temp\counter.cmd:

c:\temp>counter
This is a test before the loop starts
Progress: 1 of 10
Progress: 2 of 10
Progress: 3 of 10
Progress: 4 of 10
Progress: 5 of 10
Progress: 6 of 10
Progress: 7 of 10
Progress: 8 of 10
Progress: 9 of 10
Progress: 10 of 10
End of the script has been reached.
LPChip
  • 59,229
  • 10
  • 98
  • 140