繁体   English   中英

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

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

我需要在script.cmd里面区分这两种情况:

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

如何确定我的 script.cmd 是直接调用的,还是在使用 CALL 的上下文中调用的?

如果重要,请拨打 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.

任何人都知道“魔法在这里”会检测到已调用并设置调用=1?

目前,我看不出有什么办法可以检测到它,但作为一种变通方法,您始终可以强制使用哨兵。

@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_ %*

这将允许您使用指定的语法

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

发布的代码以随机退出代码结束脚本以进行测试。 当退出代码为 0 时将继续执行

注意:为了让它工作,至少在 XP 中,似乎对批处理文件的call必须是批处理文件中的最后一个代码

检查脚本的路径是否在 CMDCMDLINE 变量中。 如果没有,那么它可能被调用了。

在此示例中,我使用%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