How to get the path of a batch script without the trailing backslash in a single command?

后端 未结 6 1122
闹比i
闹比i 2021-02-02 07:49

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          


        
相关标签:
6条回答
  • 2021-02-02 08:12

    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.
    
    0 讨论(0)
  • 2021-02-02 08:21

    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

    0 讨论(0)
  • 2021-02-02 08:23

    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\."
    
    0 讨论(0)
  • 2021-02-02 08:25

    The simplest solution that worked for me was

    Instead of using : SET currentPath=%~dp0

    USE : SET currentPath=%cd%

    0 讨论(0)
  • 2021-02-02 08:29

    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.

    0 讨论(0)
  • 2021-02-02 08:30

    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.

    0 讨论(0)
提交回复
热议问题