91

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?

1

10 Answers 10

95

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

3
  • 10
    goto :eof is the same as exit /b, both returns just after the calling CALL
    – jeb
    Jul 1, 2015 at 15:26
  • If I understand correctly, this is like you called this same batch, beginning at the :myDosFunc line.
    – insan-e
    Nov 30, 2017 at 22:08
  • @jeb it doesn't do what it means? No need to create your own return points?
    – Sandburg
    Feb 1, 2019 at 11:39
56

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
35

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
1
  • 3
    Interestingly, if you rename 5lines.bat to 5lines.cmd you will notice that call 5lines is sufficient without the need to specify the extension.
    – Noir
    Jul 6, 2019 at 5:29
24

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%

10

Coming from a Java background, I have tried to incorporate some familiar conventions when creating procedures for .bat scripts.

The script below demonstrates the definition of two procedures.

@ECHO OFF
SET firstInstanceVariable="Hello world!"
SET secondInstanceVariable="Good bye world!"
GOTO:MAIN

:firstMethodName
    SETLOCAL ENABLEDELAYEDEXPANSION
        SET firstArgumentPassedIn=%~1
        SET secondArgumentPassedIn=%~2
        
        ECHO %firstInstanceVariable%
        ECHO "The first argument passed in was %firstArgumentPassedIn%"
        ECHO "The second argument passed in was %secondArgumentPassedIn%"
    ENDLOCAL
EXIT /B 0

:secondMethodName
    SETLOCAL ENABLEDELAYEDEXPANSION
        SET firstArgumentPassedIn=%~1
        SET secondArgumentPassedIn=%~2
        
        ECHO %secondInstanceVariable%
        ECHO "The first argument passed in was %firstArgumentPassedIn%"
        ECHO "The second argument passed in was %secondArgumentPassedIn%"
    ENDLOCAL
EXIT /B 0


:MAIN
call:firstMethodName "The Quick Brown" "Fox Jumps Over"
call:secondMethodName "1 2 3 4" 3.14

Notice that an explicit GOTO:MAIN is necessary to skip over the procedure definitions. This is because you must skip over the procedure before deciding to read it. Otherwise, the procedure will be executed.

The code below demonstrates a close Java-equivalent of the above .bat script.

public class MyObject {
    private String firstInstanceVariable = "Hello world!";
    private String secondInstanceVariable = "Good bye world!";
    public void firstMethodName(Object... arguments) {
        String firstArgumentPassedIn = arguments[0].toString();
        String secondArgumentPassedIn = arguments[1].toString();
        System.out.println(firstInstanceVariable);
        System.out.format("The first argument passed in was %s", firstArgumentPassedIn);
        System.out.format("The second argument passed in was %s", secondArgumentPassedIn);
    }

    public void secondMethodName(Object... arguments) {
        String firstArgumentPassedIn = arguments[0].toString();
        String secondArgumentPassedIn = arguments[1].toString();
        System.out.println(secondInstanceVariable);
        System.out.format("The first argument passed in was %s", firstArgumentPassedIn);
        System.out.format("The second argument passed in was %s", secondArgumentPassedIn);
    }

    public static void main(String[] args) {
        MyObject myObject = new MyObject();
        myObject.firstMethodName("The Quick Brown", "Fox Jumps Over");
        myObject.secondMethodName(new Integer[]{1,2,3,4}, 3.14);
    }
}
7

You could try to use the examples listed on DOS Batch - Function Tutorial

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

0
5

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.

3

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

0
3

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%
1
  • 3
    Why use goto :%returnto%? goto :eof or just "end of file" will automatically return to the line next to call ... (that's the very purpose of call) and doesn't leave a orphaned JumpBackAddress on the stack. Too many of them will break your script with an errormessage.
    – Stephan
    Aug 14, 2018 at 8:15
3

Below may make it look like a function.

call :myFunc %para1% %para2%

:myFunc <para1> <para2>
    echo %1
    echo %2
    EXIT /B

Example

@echo off
echo PROGRAM_NAME:%~nx0 Start
echo.
================================

SET debugMode=%1
call :myFunc1 %debugMode%
call :myFunc2 para1 "para2 hello"

================================
echo PROGRAM_NAME:%~nx0 End & pause>nul
EXIT /B

:: 👇 define the function under below
:myFunc1 <isDebug>
    :: So that you can know the %1 means: isDebug.
    if "%1" == "1" (
        echo debug mode
    )
    EXIT /B

:myFunc2 <para1> <para2>
    :: output: para1
    echo %1

    :: output: "para2 hello"
    echo %2
    EXIT /B

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.