Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if bat file is running via double click or from cmd window

Tags:

windows

cmd

I have a bat file that does a bunch of things and closes the cmd window which is fine when user double clicks the bat file from explorer. But if I run the bat file from a already open cmd window as in cmd>c:\myfile.bat then I do not want the bat file to close the cmd window (END) since I need to do other things. I need bat dos command code that will do something like

if (initiated_from_explorer) then else endif 

Is this possible ? thanks

like image 916
Gullu Avatar asked May 02 '11 16:05

Gullu


People also ask

How can I tell if a task is running in CMD?

Use Of Tasklist Command Click on the cmd utility icon; it opens a command-line window. Type Tasklist in it and press the enter key. This command shows all the running processes in your system.


2 Answers

mousio's solution is nice; however, I personally did not manage to make it work in an "IF" statement because of the double quotes in the value of %cmdcmdline% (with or without double quotes around %cmdcmdline%).

In constrast, the solution using %0 works fine. I used the following block statement and it works like a charm:

IF %0 == "%~0"  pause 

The following solution, which expands %~0 to a fully qualified path, might also work if the previous does not (cf. Alex Essilfie's comment):

IF %0 EQU "%~dpnx0" PAUSE 

However, note that this solution with %~dpnx0 fails when

  1. the .bat file is located somewhere in the %USERPROFILE% directory, and
  2. your %USERNAME% contains one or more uppercase characters

because... wait for it... the d in %~dpnx0 forces your %USERPROFILE% username to lowercase, while plain %0 does not. So they're never equal if your username contains an uppercase character. ¯\_(ツ)_/¯

[Edit 18 June 2021 - thanks to JasonXA]

You can solve this lowercase issue with case-insensitive comparison (magic /I):

IF /I %0 EQU "%~dpnx0" PAUSE 

This might be the best solution of all!

like image 103
Jean-Francois T. Avatar answered Oct 12 '22 15:10

Jean-Francois T.


%cmdcmdline% gives the exact command line used to start the current Cmd.exe.

  • When launched from a command console, this var is "%SystemRoot%\system32\cmd.exe".
  • When launched from explorer this var is cmd /c ""{full_path_to_the_bat_file}" ";
    this implicates that you might also check the %0 variable in your bat file, for in this case it is always the full path to the bat file, and always enclosed in double quotes.

Personally, I would go for the %cmdcmdline% approach (not %O), but be aware that both start commands can be overridden in the registry…

like image 44
mousio Avatar answered Oct 12 '22 13:10

mousio