views:

50

answers:

2

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%

The first statement gets the path with the trailing backslash and the second line removes the last character, i.e. the backslash.

My question is:

Is there a way to combine these two statements into a single line of code?

+1  A: 

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.

Joey
+1  A: 

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

Anders