Skip to main content

Example Windows batch script including function call/run order demonstration.

@setlocal
@echo off

::
:: https://jonlabelle.com/snippets/view/dos/example-windows-batch-script
::

set SCRIPTNAME=%~n0
set SCRIPTDIR=%~dp0

REM removes trailing backslash \
set SCRIPTDIR=%SCRIPTDIR:~0,-1%

if "%~1"=="" (
    echo.Please provide at least one argument to run this script.
)

if "%~1"=="/?" goto :usage
if "%~1"=="-h" goto :usage
if "%~1"=="--help" goto :usage

:init
    echo.Running :init, which was not called anywhere in script...
    goto :main

:step1
    setlocal
    echo.Running Step 1, called from main...
    call :step3
    endlocal
    goto :eof

:step2
    setlocal
    echo.Running Step 2, called from :main...
    endlocal
    goto :eof

:step3
    setlocal
    echo.Running Step 3, called inside step1...
    endlocal
    goto :eof

:usage
    echo.%SCRIPTNAME% ^[options^]
    @endlocal && exit /B 0

:main
    echo.Main...
    call :step1
    call :step2
    @endlocal && exit /B %errorlevel%

echo.This message is never displayed.