简体   繁体   English

在 Windows CMD.EXE shell 中,如何检测脚本是否被调用或直接调用?

[英]How do I detect if script was CALL'ed or invoked directly, in Windows CMD.EXE shell?

I need to distinguish these two situations inside script.cmd:我需要在script.cmd里面区分这两种情况:

C:\> call script.cmd
C:\> script.cmd

How can I determine if my script.cmd was invoked directly, or invoked in the context of using a CALL?如何确定我的 script.cmd 是直接调用的,还是在使用 CALL 的上下文中调用的?

If it matters, this is on Windows 7.如果重要,请拨打 Windows 7。

@echo off
set invoked=0
rem ---magic goes here---
if %invoked%==0 echo Script invoked directly.
if %invoked%==1 echo Script invoked by a CALL.

Anyone know the "magic goes here" which would detect having been CALL'ed and set invoked=1?任何人都知道“魔法在这里”会检测到已调用并设置调用=1?

At this moment, I see no way to detect it, but as a workaround you can always force the use of the sentinel.目前,我看不出有什么办法可以检测到它,但作为一种变通方法,您始终可以强制使用哨兵。

@echo off
    setlocal enableextensions
    rem If "flag" is not present, use CALL command
    if not "%~1"=="_flag_" goto :useCall
    rem Discard "flag"
    shift /1

    rem Here the main code

    set /a "randomExitCode=%random% %% 2"   
    echo [%~1] exit with code %randomExitCode%
    exit /b %randomExitCode%
    goto :eof


rem Retrieve a correct full reference to the current batch file    
:getBatchReference returnVar
    set "%~1=%~f0" & goto :eof

rem Execute     
:useCall
    setlocal enableextensions disabledelayedexpansion
    call :getBatchReference _f0
    endlocal & call "%_f0%" _flag_ %*

This will allow you to use the indicated syntax这将允许您使用指定的语法

script.cmd first && script.cmd second && script.cmd third

The posted code ends the script with a random exit code for testing.发布的代码以随机退出代码结束脚本以进行测试。 Execution will continue when the exit code is 0当退出代码为 0 时将继续执行

NOTE: For it to work, at least in XP, it seems the call to the batch file MUST be the last code in the batch file注意:为了让它工作,至少在 XP 中,似乎对批处理文件的call必须是批处理文件中的最后一个代码

Check if the script's path is in the CMDCMDLINE variable.检查脚本的路径是否在 CMDCMDLINE 变量中。 If not, then it was probably called.如果没有,那么它可能被调用了。

In this example I use %CMDCMDLINE:"=/% to turn the quotes into forward-slashes (the FIND command can't search for quotes) and I echo it with <NUL SET/P="" so that certain characters in the file path (like ampersands) don't break the script.在此示例中,我使用%CMDCMDLINE:"=/%将引号转换为正斜杠(FIND 命令无法搜索引号),并使用<NUL SET/P=""回显它,以便文件路径(如&符号)不要破坏脚本。

<NUL SET/P="%CMDCMDLINE:"=/%" | FIND "/%~0/">NUL || (
    REM Commands to perform if script was called
    GOTO:EOF
)

::AND/OR

<NUL SET/P="%CMDCMDLINE:"=/%" | FIND "/%~0/">NUL && (
    REM Commands to perform if script was NOT called
    GOTO:EOF
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM