The Batch files programming language is a powerful language but unfortunately, not many people know it that well. In an effort to pass the knowledge, in this article I am going to illustrate how to do function calls in Batch scripts.
Let’s get started!
The basics
The following example illustrates how to define and call a function:
@echo off :main call :hello call :world goto :eof :hello echo This is the Hello function goto :eof :world echo This is a second function call goto :eof
The following outputs:
This is the Hello function This is a second function call
From the example above, it is obvious how to call a function and return from it:
- Define a function as you would define a label
- Use the “CALL :function-name” syntax to call the function
- Use the “GOTO :EOF” to return from the function back to the caller
Recursive functions are also supported in the Batch language. Just make sure you avoid infinite recursion.
Functions with arguments
It is possible to pass arguments to called functions:
@echo off :main call :print + "Hello world" call :allargs Argument 1 Argument 2 "Arg 3" goto :eof :: print 1=prefix 2=message :print echo %1 %~2 goto :eof :: allargs 1*=All the arguments :allargs echo All arguments passed: %* goto :eof
To pass arguments to a function, just pass them after the function’s name at the call site. Inside the called function, each argument is accessible by prefixing its argument number with “%”. For instance, the first argument is accessed with “%1”, the second with “%2”, etc.
To get rid of the quotes passed in the argument, use the “%~N” syntax.
Functions with local variables
To use local variables in a function, make sure you encapsulate your Batch function code with SETLOCAL and ENDLOCAL:
@echo off :main set a=main call :func1 echo main: a=%a% goto :eof :func1 echo func1: on entry: a=%a% set a=func1 call :func2 echo func1: a=%a% goto :eof :func2 setlocal echo func2: on entry: a=%a% set a=func2 echo func2: modified a=%a% endlocal goto :eof
Its output is:
func1: on entry: a=main func2: on entry: a=func1 func2: modified a=func2 func1: a=func1 main: a=func1
The environment variable a is used/referenced by all the functions in question. func1 displays its value on entry, changes it and calls func2. Because func2 uses setlocal/endlocal, any modifications to the environment variables in that function are local to that function. When func2 returns, all environment variable values are restored and hence changes to a were reverted as well (as we can see from the output).
The Batchography book covers function calls and other topics in details:
Please check it out for more details.
You might also like: