Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in a batch script to keep the console open only if invoked from Windows Manager?

I have a DOS batch script that invokes a java application which interacts with the user through the console UI. For the sake of argument, let's call it runapp.bat and its contents be

java com.example.myApp

If the batch script is invoked in a console, everything works fine. However, if the script is invoked from the Window Manager, the newly opened console closes as soon as the application finishes executing. What I want is for the console to stay open in all cases.

I know of the following tricks:

  • add a pause command at the end of the script. This is a bit ugly in case runapp.bat is invoked from the command line.

  • create a new shell using cmd /K java com.example.myApp This is the best solution I found so far, but leaves an extra shell environment when invoked from the command line, so that calling exit doesn't actually close the shell.

Is there a better way?

like image 475
ykaganovich Avatar asked Feb 04 '09 05:02

ykaganovich


People also ask

How do I keep the console open after executing a batch file?

Edit your bat file by right clicking on it and select “Edit” from the list. Your file will open in notepad. Now add “PAUSE” word at the end of your bat file. This will keep the Command Prompt window open until you do not press any key.

How do I run a batch file without closing a window?

If you're creating a batch file and want the MS-DOS window to remain open, add PAUSE to the end of your batch file. This prompts the user to Press any key. Until the user presses any key, the window remains open instead of closing automatically.

What is @echo off in batch script?

batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.

How do you make a batch file that won't open cmd?

You cannot hide the cmd window with any batch file command. You can launch the batch file from a vbscript and have it run as a background process which hides the cmd window. You could put powershell -window hidden -command "" in your script.


1 Answers

See this question: Detecting how a batch file was executed

This script will not pause if run from the command console, but will if double-clicked in Explorer:

@echo off
setlocal enableextensions

set SCRIPT=%0
set DQUOTE="

:: Detect how script was launched
@echo %SCRIPT:~0,1% | findstr /l %DQUOTE% > NUL
if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1

:: Run your app
java com.example.myApp

:EXIT
if defined PAUSE_ON_CLOSE pause
like image 70
Patrick Cuff Avatar answered Oct 03 '22 22:10

Patrick Cuff