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

mousio’s solution is nice but I 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!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)