Something like a function/method in batch files?

后端 未结 9 452
忘了有多久
忘了有多久 2020-12-08 00:05

is there anything that mimicks a method like one knows it from Java, C# etc.? I have 5 lines of commands in a batch file, those 5 lines are used at more than one place insid

9条回答
  •  甜味超标
    2020-12-08 00:36

    Here's a 'hack' that will allow you to have "anonymous" functions in batch files:

    @echo off
    setlocal 
    set "anonymous=/?"
    
    :: calling the anonymous function
    call :%%anonymous%% a b c 3>&1 >nul
    
    :: here the anonymous function is defined
    if "%0" == ":%anonymous%" (
      echo(
      echo Anonymous call:
      echo %%1=%1 %%2=%2 %%3=%3
      exit /b 0
    )>&3
    ::end of the anonymous function
    

    The anonymous function block should be placed right after the call statement and must end with exit statement

    the trick is that CALL internally uses GOTO and then returns to the line where the CALL was executed. With the double expansion GOTO help message is triggered (with %%/?%% argument) and then continues the script. But after it is finished it returns to the CALL - that's why the if statement is needed.

提交回复
热议问题