Something like a function/method in batch files?

后端 未结 9 407
忘了有多久
忘了有多久 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:23

    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%
    
    0 讨论(0)
  • 2020-12-08 00:24

    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
    
    0 讨论(0)
  • 2020-12-08 00:31

    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
    
    0 讨论(0)
  • 2020-12-08 00:33

    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

    0 讨论(0)
  • 2020-12-08 00:34

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

    0 讨论(0)
  • 2020-12-08 00:36

    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%

    0 讨论(0)
提交回复
热议问题