Something like a function/method in batch files?

2020-02-07 18:57发布

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 inside the batch file. I can't use a goto, because depending on the errorlevel created by those 5 lines I have different actions that follow. I tried putting my 5 lines inside a batch file 5lines.bat, but the original batch file original.bat only calls 5lines.bat and doesn't execute the commands after the call to 5lines.bat ): That's how my original.bat looks like:

5lines.bat
echo this gets never called, how to make sure this gets called?

There's no exit or something like this in 5lines.bat! How can I make sure the line after 5lines.bat gets called?

8条回答
叛逆
2楼-- · 2020-02-07 19:25

Just for completeness, you can also pass parameters to the function:

Function call

call :myDosFunc 100 "string val"

Function body

:myDosFunc
echo. Got Param#1 %~1
echo. Got Param#2 %~2
goto :eof
查看更多
家丑人穷心不美
3楼-- · 2020-02-07 19:27

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.

查看更多
登录 后发表回答