Álvaro González
Álvaro González

Reputation: 146660

Conditional PAUSE (not in command line)

I like to have a final PAUSE in my *.bat scripts so I can just double click on them in Windows explorer and have the chance to read the output. However, the final PAUSE is an annoyance when I run the same script from the command line.

Is there any way to detect whether we are running the script from a command prompt (or not) and insert the PAUSE (or not) accordingly?

(Target environment is Windows XP and greater.)

Update

I've managed to compose this from Anders's answer:

(((echo.%cmdcmdline%)|find /I "%~0")>nul)
if %errorlevel% equ 0 (
    set GUI=1
) else (
    set CLI=1
)

Then, I can do stuff like this:

if defined GUI pause

Upvotes: 17

Views: 17543

Answers (3)

Anders
Anders

Reputation: 101764

@echo off
echo.Hello World
(((echo.%cmdcmdline%)|find /I "%~0")>nul)&&pause

...NT+ only, no %cmdcmdline% in Win9x probably.

As pointed out by E M in the comments, putting all of this on one line opens you up to some edge cases where %cmdcmdline% will escape out of the parenthesis. The workaround is to use two lines:

@echo off
echo.Hello World

echo.%cmdcmdline% | find /I "%~0" >nul
if not errorlevel 1 pause

Upvotes: 21

skataben
skataben

Reputation: 2152

I was hoping the answer by @Anders would work in its own .bat file. Unfortunately, it does not for me. Based on @DarinH's comment, perhaps it does for some. The script below should work for all, but requires an extra parameter.

The key lies in the %CmdCmdLine% environment variable, which I imagine might be a bit different for a few edge cases.


PauseIfGui.bat

@echo off
if "%~1" == "" ((echo.%CmdCmdLine%)|"%WinDir%\System32\find.exe" /I "%~0")>nul && pause & exit /b
((echo.%CmdCmdLine%)|"%WinDir%\System32\find.exe" /I "%~1")>nul && pause

This accepts one optional parameter: the full path of calling script. If no params are passed, it runs the same as @Anders script.


AnyOtherFile.bat

@echo off
call PauseIfGui.bat %~f0

If opened from Explorer (i.e. double-clicking) , AnyOtherFile.bat will pause. If called from a command prompt, it will not.

Upvotes: 0

Tom Smilack
Tom Smilack

Reputation: 2075

I doubt that there's a distinction, because I think it just starts a command prompt and then runs the bat when you double click on it.

However, if you make shortcuts to the bat files and go to Properties and add in an extra argument (something like "/p") in the "Target" field, then you could check for the presence of that argument at the end of the script and pause if it is set. Then, running from the shortcut would cause it to end in a pause and running from command line wouldn't.

Upvotes: 3

Related Questions