Reputation: 171439
I know that %0
contains the full path of the batch script, e.g. c:\path\to\my\file\abc.bat
I want path
to be equal to c:\path\to\my\file
.
How can I achieve that?
Upvotes: 442
Views: 499295
Reputation: 62
One solution if you know the file name:
set fullpath=%~f0
set dirpath=%fullpath:NAME_OF_UR_FILE.EXT=%
You may be able to use vars like $n0
with this, but this was good enough for my use case
Upvotes: 0
Reputation: 41
Like mentioned above, %~dp0 will return the absolute drive and path of the current script. IMPORTANT NOTE: the implementation of %~dp0 is critically broken and will not work if the bat script is invoked via a path that is enclosed in quotes.
Microsoft is refusing to fix this bug due to cmd.exe being a legacy product. See https://github.com/microsoft/terminal/issues/15212 for details.
Upvotes: 2
Reputation: 1627
%~dp0 - return the path from where script executed
But, important to know also below one:
%CD% - return the current path in runtime, for example if you get into other folders using "cd folder1", and then "cd folder2", it will return the full path until folder2 and not the original path where script located
Upvotes: 15
Reputation: 1
%cd%
will give you the path of the directory from where the script is running.
Just run:
echo %cd%
Upvotes: -8
Reputation: 174
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.
Upvotes: 3
Reputation: 72668
%~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.
Upvotes: 731
Reputation: 383
%~dp0
may be a relative path.
To convert it to a full path, try something like this:
pushd %~dp0
set script_dir=%CD%
popd
Upvotes: 15
Reputation: 333
You can use following script to get the path without trailing "\"
for %%i in ("%~dp0.") do SET "mypath=%%~fi"
Upvotes: 15
Reputation: 15780
That would be the %CD%
variable.
@echo off
echo %CD%
%CD%
returns the current directory the batch script is in.
Upvotes: -12