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

后端 未结 6 1123
闹比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: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

提交回复
热议问题