How can I close batch file from any prompt in code?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Jer
Posts: 150
Joined: 23 Nov 2014 17:13
Location: California USA

How can I close batch file from any prompt in code?

#1 Post by Jer » 28 Mar 2019 13:39

I would like to add <shift+X> as an option to exit from the batch script from any of the
prompts for input, and not close the cmd window. Can this be done?
I searched a little and found no answer. I tried a goto :exitNow but the code flows
from the label that has exit /b, back to where the goto was executed.
The solution must be batch code only, as the goal of my project is to
conquer time (time to deliver a file), space (framed space) and colors, all 16,777,216 of them,
and do it all with batch code.

Here is a test script that I think illustrates my goal to immediately close a batch file
without having to backtrack to the main code level. I do not want to close the cmd
window as this would not be user-friendly.

Code: Select all

@echo off
rem goal: close the batch file from any prompt while keeping cmd window open
setlocal
:top
echo in main
set "rsp="
set /p "rsp=Press Enter to continue or enter X to exit from main "
If /I "%rsp%" equ "X" exit /b
call :fun1
goto :top
endlocal & exit /b

:fun1
setlocal
:fLoop
echo in fun1 .. enter X to immediately exit
set "rsp="
set /p "rsp="
If /I "%rsp%" equ "X" (
  echo X was entered--now how do I close the batch file from subroutine?
) Else (
  goto :fLoop
)
endlocal & exit /b

aGerman
Expert
Posts: 3563
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How can I close batch file from any prompt in code?

#2 Post by aGerman » 28 Mar 2019 14:23

EXIT (without /b) would close the console window. But since you can return a value using exit /b you better check the errorlevel in the main code.

Code: Select all

@echo off
rem goal: close the batch file from any prompt while keeping cmd window open
setlocal
:top
echo in main
set "rsp="
set /p "rsp=Press Enter to continue or enter X to exit from main "
If /I "%rsp%" equ "X" exit /b
call :fun1
if errorlevel 1 exit /b
goto :top
endlocal & exit /b

:fun1
setlocal
:fLoop
echo in fun1 .. enter X to immediately exit
set "rsp="
set /p "rsp="
If /I "%rsp%" equ "X" (
  echo X was entered--now how do I close the batch file from subroutine?
  endlocal & exit /b 1
) Else (
  goto :fLoop
)
endlocal & exit /b 0

Jer
Posts: 150
Joined: 23 Nov 2014 17:13
Location: California USA

Re: How can I close batch file from any prompt in code?

#3 Post by Jer » 28 Mar 2019 18:46

That works! And very easy to do. My code uses your :choice function, and uppercase X will be the
keypress (and also as an entry at the prompt for text input) to exit completely from any screen.
spacebar and Enter key are assigned error level 0 in the choice function. I'll use exit /b 50
to communicate between calling functions for immediate exit. This is solved.
Thanks.
Jerry

Post Reply