Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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% 

The 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?

like image 297
Joergen Bech Avatar asked Jul 01 '10 17:07

Joergen Bech


People also ask

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.


2 Answers

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. 
like image 63
DaVinci007 Avatar answered Sep 25 '22 09:09

DaVinci007


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.

like image 29
Joey Avatar answered Sep 24 '22 09:09

Joey