Skip to content

Batch Script Functions

Learn how to define and call functions in batch scripting using labels and the CALL command, including parameter passing and proper termination with EXIT /B.

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

Function Definition

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

Function Syntaxbatch
: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
Navigation