Advertisement
Advertisement


How to get the path of the batch script in Windows?


Question

I know that %0 contains the full path of the batch script, e.g. c:\path\to\my\file\abc.bat

I would path to be equal to c:\path\to\my\file

How could I achieve that ?

2017/03/07
1
337
3/7/2017 9:40:25 AM

Accepted Answer

%~dp0 will be the directory. Here's some documentation on all of the path modifiers. Fun stuff :-)

To remove the final backslash, you can use the :n,m substring syntax, like so:

SET mypath=%~dp0
echo %mypath:~0,-1%

I don't believe there's a way to combine the %0 syntax with the :~n,m syntax, unfortunately.

2018/12/03
575
12/3/2018 10:36:56 AM

You can use following script to get the path without trailing "\"

for %%i in ("%~dp0.") do SET "mypath=%%~fi"
2016/04/01

%~dp0 may be a relative path. To convert it to a full path, try something like this:

pushd %~dp0
set script_dir=%CD%
popd
2017/03/31

You can use %~dp0, d means the drive only, p means the path only, 0 is the argument for the full filename of the batch file.

For example if the file path was C:\Users\Oliver\Desktop\example.bat then the argument would equal C:\Users\Oliver\Desktop\, also you can use the command set cpath=%~dp0 && set cpath=%cpath:~0,-1% and use the %cpath% variable to remove the trailing slash.

2019/02/21

%cd% will give you the path of the directory from where the script is running.

Just run:

echo %cd%
2020/03/31

That would be the %CD% variable.

@echo off
echo %CD%

%CD% returns the current directory the batch script is in.

2010/09/30

Source: https://stackoverflow.com/questions/3827567
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]