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

后端 未结 9 2004
眼角桃花
眼角桃花 2021-02-01 17:34

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.

相关标签:
9条回答
  • 2021-02-01 18:12

    This is only using the internal command. so effectively....

    EnableDelayedExpansion

    if "!cmdcmdline!" neq "!cmdcmdline:%~f0=!" pause >nul
    

    or

    if not "!cmdcmdline!" == "!cmdcmdline:%~f0=!" pause >nul
    

    DisableDelayedExpansion

    if "%cmdcmdline%" neq "%cmdcmdline:%~f0=%" pause >nul
    

    or

    if not "%cmdcmdline%" == "%cmdcmdline:%~f0=%" pause >nul
    
    0 讨论(0)
  • 2021-02-01 18:15

    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

    0 讨论(0)
  • 2021-02-01 18:17
    setlocal EnableDelayedExpansion
    
    if "!cmdcmdline!" neq "!cmdcmdline:%comspec%=!" ( pause>nul )
    

    Test is done in Windows 10. Using %windir%, it is a little dangerous or ambiguous. So %comspec% is super safe.

    0 讨论(0)
提交回复
热议问题