Dos - (Batch) Script

> Procedural Languages > Dos (Win32 Shell Scripting) and Utilities

1 - About

The batch script is a text file with the extension .bat or .cmd that is interpreted by a batch interpreter.

Advertising

3 - How to

3.1 - Call a script from a script

You can call a batch script by :

  • writing its name in the source script: The script execution will stop and continue in the called batch
  • using the following commands:
    • call: Calls one batch program from another. The script execution will continue after the called batch is completed
    • start: Starts a separate window to run a specified program or command.

If the script is called from Explorer with a double-click on the batch file, an exit will automatically be performed at the end of the execution.

3.2 - Determine the directory of the script

See argument modifiers for more options.

  • for a file (not a symlink)
SET SCRIPT_PATH=%~dp0

REM I see also after
FOR %%i IN ("%SCRIPT_PATH%") DO SET SCRIPT_PATH=%%~fsi

REM or
call "%~dp0script.cmd"
  • for a symlink, we need the target directory.
:: The directory of the called file (the symlink)
SET SCRIPT_DIR=%~dp0

:: If this is a symlink, the DIR command gives us the symlink target directory between [ ]
SET SCRIPT_PATH=%~dpnx0
for /F "usebackq tokens=2 delims=[]" %%H in  (`dir /a:l %SCRIPT_PATH%`) do (
	set SCRIPT_DIR=%%~dpH
)
echo %SCRIPT_DIR%
Advertising

3.3 - Name

Thanks to argument modifiers - the file name (ie script.bat)

SET SCRIPT_NAME=%~nx0 

3.4 - Path

%~dpnx0

3.5 - Control a argument

argument

set allowedvalues=1 2 3
for %%i in ( %allowedvalues% ) do (
    if %1 == %%i set allowed=true
)

4 - Example

4.1 - Show a banner

set BASE_PATH=%~dp0
type "%BASE_PATH%banner.txt"

where:

Advertising

4.2 - Activate Advance Modes

4.3 - Java

if defined JAVA_HOME if exist "%JAVA_HOME%\bin\java.exe" PATH "%JAVA_HOME%\bin";%PATH%
java.exe -version >nul 2>&1 || ( echo Java cannot be found on the system! & exit /b 2 )
for /f  tokens^=2^,3^,4^ delims^=_.^"  %%J in ('java.exe -version 2^>^&1') do set "jver=%%J%%K%%L" && goto :break_loop
:break_loop
IF %jver%0 LSS 1600 ( echo Current Java version is older than 1.6.0 & endlocal & exit /b 2 )

where: