Skip to main content

Batch Script Functions

Functions

A function is a set of instructions organized together to perform a specific task.

More precisely, a function is a single complete unit (self-contained block) containing a block of code that performs a specific task.

The function performs the same task when called which avoids the need of rewriting the same code again and again.

Like in any other programming language, batch script functions also have:

  • function definition
  • function call
note

When defining the main program, it is necessary to ensure that the EXIT /B %ERRORLEVEL% statement is used in the main program to separate the main program code from the function.

Function Definition

In Batch Script, a function is defined using the label statement and followed by the code to be executed

Function Syntax
:function_name 
Some_Code
EXIT /B 0

As shown in the syntax, there are three main parts in function definition in a batch file:

  • You start by declaring a function with a label.
  • Then there is the body of the function, where the codes to perform a given task are written.
  • At the end EXIT /B 0 is used to ensure that functions terminate or exit correctly.

The following is an example of a simple function.

:Display 
SET /A index=2
echo The value of index is %index%
EXIT /B 0

Function Call

In Batch Script a function is called by using the call command.

:: To call function without parameters 
CALL :function_name

:: To call function with parameters
CALL :function_name param1, param2,...,paramN

:: To call function with return values
CALL :function_name return_value1,return_value2,..,return_valueN
note

To learn more about functions with parameters and recursive functions, see the following pages.