Suppose I wish to get the absolute path of a batch script from within the batch script itself, but without a trailing backslash. Normally, I do it this way:
SET
Instead of removing the trailing backslash, adding a trailing dot is semantically equivalent for many software.
C:\Windows is equivalent to C:\Windows\.
echo %dp0
>C:\Windows\
echo %dp0.
>C:\Windows\.
This errors out:
robocopy "C:\myDir" %~dp0
This is successful:
robocopy "C:\myDir" %~dp0.
I'd like to point out that it is not safe to use the substring tricks on variables that contain file system paths, there are just too many symbols like !,^,% that are valid folder/file names and there is no way to properly escape them all
FOR /D seems to strip the trailing backslash, so here is a version that uses for:
setlocal enableextensions enabledelayedexpansion&set _CD=%CD%&cd /D "%~dp0"&(FOR /D %%a IN ("!CD!") DO ((cd /D !_CD!)&endlocal&set "BuildDir=%%~a"))
This requires Win2000 and will probably fail if the batch file is on a UNC path
Example script "c:\Temp\test.cmd":
@set BuildDir=%~dp0.
@echo Build directory: "%BuildDir%"
Run in console:
d:\> cmd /C c:\Temp\test.cmd
Build directory: "c:\Temp\."
The simplest solution that worked for me was
Instead of using : SET currentPath=%~dp0
USE : SET currentPath=%cd%
You can use the modifiers ability of the FOR variables.
for %%Q in ("%~dp0\.") DO set "BuildDir=%%~fQ"
The %%~fQ
results to the required path without trailing backslash (nor \.
)
And this creates still a valid absolute path for the case, when the batch file is in a root directory on any drive.
This solution returns D:\
, instead of D:
only by simply removing the trailing
character.
Only with delayed expansion when you write both statements into the same line:
set BuildDir=%~dp0&&set BuildDir=!BuildDir:~0,-1!
But that kinda defies the purpose.