Batch argument/parameter variable expansion
In a batch file, the numbered variables %1
through %9
store the values of the arguments (or parameters) with which the batch file was called.
%0
stores the (relative) path and name of the batch file itself.
With variable expansion, the values of these numbered variables can be subsituted for related values:
Applying ~n
and ~x
gets the filename (with suffix) of the batch file:
@echo path and filename : %0
@echo filename with suffix: %~n0%~x0
Similarly, the (absolute) directory can be found by applying ~dp
on a variable:
@rem
@rem Note the trailing backslash
@rem
@set current_dir=%~dp0
@echo the currenct directory is %current_dir%
Table of modifiers
%~1 | Remove quotes |
%~f1 | Full (absolute) path (of possibly relative path) |
%~d1 | Drive letter |
%~p1 | Path (without drive or file) |
%~n1 | File name |
%~x1 | Extension of file name |
%~s1 | Like %~f1 but with short names |
%~a1 | File attributes |
%~t1 | Date and time of file |
%~z1 | Size of file |
%~$PATH:1 | First directory in %PATH% where %1 is found |
With such modifiers, the working directory of a batch file can be set to the directory where the batch file is located so that the batch file can be executed from any location:
@rem
@rem CD into «own» directory
@rem
@cd %~dp0
@echo Current directory is %cd%
@echo %time% >> run-in-own-dir-run-times
Name of bat file
These variable expansion technique allows to assign the name of a script (without .bat
suffix) to a variable which then can be used, for example, for debugging messages:
@echo off
rem
rem Assign name of bat file (without .bat
rem suffix) to variable bat_file:
rem
set bat_file=%~n0
echo Bat file is %bat_file%