[windows] Can a Windows batch file determine its own file name?

Can a Windows batch file determine its own file name?

For example, if I run the batch file C:\Temp\myScript.bat, is there a command within myScript.bat that can determine the string "myScript.bat"?

This question is related to windows batch-file cmd

The answer is


You can get the file name, but you can also get the full path, depending what you place between the '%~' and the '0'. Take your pick from

d -- drive
p -- path
n -- file name
x -- extension
f -- full path

E.g., from inside c:\tmp\foo.bat, %~nx0 gives you "foo.bat", whilst %~dpnx0 gives "c:\tmp\foo.bat". Note the pieces are always assembled in canonical order, so if you get cute and try %~xnpd0, you still get "c:\tmp\foo.bat"


Using the following script, based on SLaks answer, I determined that the correct answer is:

echo The name of this file is: %~n0%~x0
echo The name of this file is: %~nx0

And here is my test script:

@echo off
echo %0
echo %~0
echo %n0
echo %x0
echo %~n0
echo %dp0
echo %~dp0
pause

What I find interesting is that %nx0 won't work, given that we know the '~' char usually is used to strip/trim quotes off of a variable.


Below is my initial code:

@echo off
Set z=%%
echo.
echo %z%0.......%0
echo %z%~0......%~0
echo %z%n0......%n0
echo %z%x0......%x0
echo %z%~n0.....%~n0
echo %z%dp0.....%dp0
echo %z%~dp0....%~dp0
echo.

I noticed that file name given by %~0 and %0 is the way it was entered in the command-shell and not how that file is actually named. So if you want the literal case used for the file name you should use %~n0. However, this will leave out the file extension. But if you know the file name you could add the following code.

set b=%~0
echo %~n0%b:~8,4%

I have learned that ":~8,4%" means start at the 9th character of the variable and then show show the next 4 characters. The range is 0 to the end of the variable string. So %Path% would be very long!

fIlEnAmE.bat
012345678901

However, this is not as sound as Jool's solution (%~x0) above.

My Evidence:

C:\bin>filename.bat

%0.......filename.bat
%~0......filename.bat
. . .

C:\bin>fIlEnAmE.bat

%0.......fIlEnAmE.bat
%~0......fIlEnAmE.bat
%n0......n0
%x0......x0
%~n0.....FileName
%dp0.....dp0
%~dp0....C:\bin\

%~n0%b:~8,4%...FileName.bat

Press any key to continue . . .

C:\bin>dir
 Volume in drive C has no label.
 Volume Serial Number is CE18-5BD0

 Directory of C:\bin
. . .
05/02/2018  11:22 PM               208 FileName.bat

Here is the final code

@echo off
Set z=%%
set b=%~0
echo.
echo %z%0.......%0
echo %z%~0......%~0
echo %z%n0......%n0
echo %z%x0......%x0
echo %z%~n0.....%~n0
echo %z%dp0.....%dp0
echo %z%~dp0....%~dp0
echo.
echo A complex solution:
echo ===================================
echo %z%~n0%z%b:~8,4%z%...%~n0%b:~8,4%
echo ===================================
echo.
echo The preferred solution:
echo ===================================
echo %z%~n0%z%~x0.......%~n0%~x0
echo ===================================
pause

Try to run below example in order to feel how the magical variables work.

@echo off

SETLOCAL EnableDelayedExpansion

echo Full path and filename: %~f0
echo Drive: %~d0
echo Path: %~p0
echo Drive and path: %~dp0
echo Filename without extension: %~n0
echo Filename with    extension: %~nx0
echo Extension: %~x0

echo date time : %~t0
echo file size: %~z0

ENDLOCAL

The related rules are following.

%~I         - expands %I removing any surrounding quotes ("")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

Bear in mind that 0 is a special case of parameter numbers inside a batch file, where 0 means this file as given on the command line.

So if the file is myfile.bat, you could call it in several ways as follows, each of which would give you a different output from the %0 or %~0 usage:

myfile

myfile.bat

mydir\myfile.bat

c:\mydir\myfile.bat

"c:\mydir\myfile.bat"

All of the above are legal calls if you call it from the correct relative place to the directory in which it exists. %~0 strips the quotes from the last example, whereas %0 does not.

Because these all give different results, %0 and %~0 are very unlikely to be what you actually want to use.

Here's a batch file to illustrate:

@echo Full path and filename: %~f0
@echo Drive: %~d0
@echo Path: %~p0
@echo Drive and path: %~dp0
@echo Filename without extension: %~n0
@echo Filename with    extension: %~nx0
@echo Extension: %~x0
@echo Filename as given on command line: %0
@echo Filename as given on command line minus quotes: %~0
@REM Build from parts
@SETLOCAL
@SET drv=%~d0
@SET pth=%~p0
@SET fpath=%~dp0
@SET fname=%~n0
@SET ext=%~x0
@echo Simply Constructed name: %fpath%%fname%%ext%
@echo Fully  Constructed name: %drv%%pth%%fname%%ext%
@ENDLOCAL
pause

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)

Examples related to cmd

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH VSCode Change Default Terminal How to install pandas from pip on windows cmd? 'ls' in CMD on Windows is not recognized Command to run a .bat file VMware Workstation and Device/Credential Guard are not compatible How do I kill the process currently using a port on localhost in Windows? how to run python files in windows command prompt?