Batch Script 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
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.
In Batch Script, a function is defined using the label statement and followed by the code to be executed
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 0is used to ensure that functions terminate or exit correctly.
The following is an example of a simple function.
SET /A index=2
echo The value of index is %index%
EXIT /B 0
In Batch Script a function is called by using the call command.
:: To call function without parameters
:: 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
To learn more about functions with parameters and recursive functions, see the following pages.