Skip to content

Instantly share code, notes, and snippets.

@maphew
Created December 7, 2021 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maphew/9f6ba713d30eb1d0f67e7f0b2a338ba5 to your computer and use it in GitHub Desktop.
Save maphew/9f6ba713d30eb1d0f67e7f0b2a338ba5 to your computer and use it in GitHub Desktop.
Detect if bat file is running via double click or from cmd window
T:\ENV.558>if /I "C:\WINDOWS\system32\cmd.exe /c ``T:\ENV.558\setenv-testing.bat` `" EQU "`C:\WINDOWS\system32\cmd.exe` /C ``T:\ENV.558\setenv-testing.bat` `" pause
@REM https://stackoverflow.com/questions/6961153/is-it-possible-to-distinguish-when-shell-is-run-from-command-line-or-from-other
@REM Testing https://stackoverflow.com/a/61511609/14420 by @simon-streicher
if /i "%comspec% /c ``%~0` `" equ "%cmdcmdline:"=`%" pause
@heetbeet
Copy link

heetbeet commented Jan 12, 2022

Thanks, the command is incorrect because the if statement doesn't follow up with a command, e.g. if /i "%comspec% /c %~0 " equ "%cmdcmdline:"=%" echo Passed

But what I gathered from your output:

The syntax of the command is incorrect.

C:\temp>if /i "C:\Windows\system32\cmd.exe /c C:\temp\setenv-testing.bat " equ "C:\Windows\system32\cmd.exe /C C:\temp\setenv-testing.bat "

It seems like the expansion did match successfully, i.e. lhs "C:\Windows\system32\cmd.exe /c C:\temp\setenv-testing.bat " equals rhs "C:\Windows\system32\cmd.exe /C C:\temp\setenv-testing.bat " when using the case insensitive /i flag.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment