Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if batch script has been started/executed from the command line (cmd) -or- To pause or not to pause?

Tags:

I like to have a typical "usage:" line in my cmd.exe scripts — if a parameter is missing, user is given simple reminder of how the script is to be used.

The problem is that I can't safely predict whether potential user would use GUI or CLI. If somebody using GUI double-clicks this script in Explorer window, they won't have chance to read anything, unless I pause the window. If they use CLI, pause will bother them.

So I'm looking for a way to detect it.

@echo off if _%1_==__ (     echo usage: %nx0: filename     rem now pause or not to pause? ) 

Is there a nice solution on this?

like image 841
Alois Mahdal Avatar asked Feb 23 '12 19:02

Alois Mahdal


People also ask

What does pause command do in cmd?

When placed in a batch file, pause stops the file from running until you press a key to continue.

How do I pause a batch file after execution?

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.

Which command is used to suspend execution of the batch file and displays the message?

If you press Ctrl-C or Ctrl-Break while PAUSE is waiting for a key, execution of an alias will be terminated, and execution of a batch file will be suspended while you are asked whether to cancel the batch job. In a batch file, you can handle Ctrl-C and Ctrl-Break yourself with the ON BREAK command.


1 Answers

You can check the value of %CMDCMDLINE% variable. It contains the command that was used to launch cmd.exe.

I prepared a test .bat file:

@Echo Off echo %CMDCMDLINE% pause 

When run from inside of open cmd.exe window, the script prints "C:\Windows\system32\cmd.exe". When run by double-clicking, it prints cmd /c ""C:\Users\mbu\Desktop\test.bat" "

So to check if your script was launched by double-clicking you need to check if %cmdcmdline% contains the path to your script. The final solution would look like this:

@echo off  set interactive=1 echo %cmdcmdline% | find /i "%~0" >nul if not errorlevel 1 set interactive=0  rem now I can use %interactive% anywhere  if _%1_==__ (     echo usage: %~nx0 filename     if _%interactive%_==_0_ pause ) 

Edit: implemented fixes for issues changes discussed in comments; edited example to demonstrate them

like image 147
MBu Avatar answered Oct 03 '22 06:10

MBu