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:03

You could try to use the examples listed on this page

Alternatively, you could put the common lines into another batch file that you call from the main one

查看更多
放我归山
3楼-- · 2020-02-07 19:05

You could use the call command :

call:myDosFunc

And then define the function this way :

:myDosFunc    - here starts the function
echo.  here the myDosFunc function is executing a group of commands
echo.  it could do a lot of things
goto:eof

Source : Batch Functions

查看更多
做自己的国王
4楼-- · 2020-02-07 19:06

Solution:

@ECHO OFF     

call:header Start Some Operation

... put your business logic here
... make sure EXIT below is present
... so you don't run into actual functions without the call

call:header Operation Finished Successfully

EXIT /B %ERRORLEVEL%

:: Functions

:header
ECHO ================================================= 
ECHO %*
ECHO ================================================= 
EXIT /B 0

Important to put EXIT /B at the end of each function, as well as before function definitions start, in my example this is:

EXIT /B %ERRORLEVEL%

查看更多
成全新的幸福
5楼-- · 2020-02-07 19:10

Placing the reusable functions into a separate batch file would certainly work to simulate a function.

The catch is that you have to use the call command in order to ensure that control returns to the caller after the second batch file finishes executing.

call 5lines.bat
echo this will now get called
查看更多
我想做一个坏孩纸
6楼-- · 2020-02-07 19:21

For another great tutorial on writing reusable batch file code -- see Richie Lawrence's excellent library.

查看更多
Deceive 欺骗
7楼-- · 2020-02-07 19:22

I'm not sure if it was obvious from other answers but just to be explicit I'm posting this answer. I found other answers helpful in writing below code.

echo what
rem the third param gives info to which label it should comeback to
call :myDosFunc 100 "string val" ComeBack

:ComeBack
echo what what
goto :eof

:myDosFunc
echo. Got Param#1 %~1
echo. Got Param#2 %~2
set returnto=%~3
goto :%returnto%
查看更多
登录 后发表回答