October 13, 2017

Double click a Windows batch file (*.bat, *.cmd) and keep the command prompt open

Abstract

This is a quick tip about Windows batch files (.bat, .cmd). I often use these files to setup different development environments; setting environment variables, update %PATH%, different %JAVA_HOME%, etc. Sometimes it can be a challenge to do this, not lose these settings, and keep the command prompt (DOS window) open all at the same time. This is a technique I found which seems to do all this reliably.

Disclaimer

This post is solely informative. Critically think before using any information presented. Learn from it but ultimately make your own decisions at your own risk.

Example

This is an example run.cmd file. The basic idea is when you double-click this file, the script will actually call itself again which you can see in the :cmd section. After the script calls itself again, the :run section is where you put the details of your script.

Listing 1 - run.cmd

@echo off

REM Check the value of the 1st command line argument.
REM If the value is empty, go to the 'cmd' section
IF "%~1" == ""    GOTO cmd

REM Check the value of the 1st command line argument.
REM If the value is "run", go to the 'run' section
IF "%~1" == "run" GOTO run

REM If the 1st command line argument is not empty,
REM but not the value "run" then just 'end' because
REM this script doesn't know how to handle it.
ECHO Command line argument "%1" is not understood.
GOTO end

:cmd
REM In this section, use the %0 value in order to 
REM have this script call itself again.  By calling
REM itself with `cmd /K` you get a command prompt 
REM (DOS window) which won't automatically close
REM when this script is finished executing.
ECHO In the 'cmd' section
ECHO Script file=%0
cmd /K "%0 run"
GOTO end

:run
REM In this section, this is where you want to put
REM the work of your script.  You can execute whatever
REM you need and even call other scripts.  The
REM command prompt window will remain open because
REM of what the 'cmd' section does.
ECHO In the 'run' section

SET SOME_PROPERTY=foo
ECHO SOME_PROPERTY=%SOME_PROPERTY%

ECHO call env.cmd
call "%~dp0\env.cmd"

ECHO ENV_PROPERTY_1=%ENV_PROPERTY_1%
ECHO ENV_PROPERTY_2=%ENV_PROPERTY_2%
ECHO ENV_PROPERTY_3=%ENV_PROPERTY_3%

:end

Summary

That’s it. Really easy. Enjoy!

No comments:

Post a Comment