Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional PAUSE (not in command line)

Tags:

batch-file

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
like image 727
Álvaro González Avatar asked Oct 14 '10 15:10

Álvaro González


People also ask

How do you pause in CMD?

Execution of a batch script can also be paused by pressing CTRL-S (or the Pause|Break key) on the keyboard, this also works for pausing a single command such as a long DIR /s listing. Pressing any key will resume the operation. Pause is often used at the end of a script to give the user time to read some output text.

How do I put a timed pause in a batch file?

You can insert the pause command before a section of the batch file that you might not want to process. When pause suspends processing of the batch program, you can press CTRL+C and then press Y to stop the batch program.

How do I press the key to continue in CMD?

The cmd /c pause command displays the Press any key to continue . . . and pauses the execution until a key is pressed. Output: Copy Press any key to continue . . .


1 Answers

@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
like image 62
Anders Avatar answered Oct 02 '22 18:10

Anders