How to get the path of a batch script without the trailing backslash in a single command?
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 BuildDir=%~dp0
SET BuildDir=%BuildDir:~0,-1%
Th开发者_开发技巧e first statement gets the path with the trailing backslash and the second line removes the last character, i.e. the backslash. Is there a way to combine these two statements into a single line of code?
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\.
For example, robocopy accepts only directories without trailing spaces.
This errors out:
robocopy "C:\myDir" %~dp0
This is successful:
robocopy "C:\myDir" %~dp0.
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.
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
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.
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%
精彩评论