4

I have a problem with the variable %CD% in a batch-file. It adds a backslash if the script is run from the root of a drive.

as an example: updatedir=%CD%\Update & echo %updatedir% will return something like

  • From a folder E:\New Folder\Update
  • From a drive root E:\\Update

Is there any way to get rid of the extra backslash if run from root?

Gary
  • 13,303
  • 18
  • 49
  • 71
Mantis
  • 41
  • 2

3 Answers3

4

Yes %CD% only has a trailing \ if the current directory is the root. You could get rid of any trailing backslash that might be there. But there is a simpler solution.

Use the undocumented %__CD__% instead, which always appends the trailing backslash. This makes it easy to build a clean path, regardless of the current directory.

set "updatedir=%__CD__%Update
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Holy cow! How do you even know that?! If this isn't in the _official_ documentation, is it at least documented _somewhere_? (I see that this works, but can you also point to a source?) – Wes Larson May 19 '16 at 18:46
  • 1
    @WesLarson - I think I first saw `%__CD__%` on a DosTips post by jeb, but I don't remember what the topic was. There is some unofficial documentation at http://ss64.com/nt/syntax-variables.html. You may be interested in http://stackoverflow.com/q/20156490/1012053. – dbenham May 20 '16 at 00:55
  • Looks like [WINE](https://winehq.org/) (`wineconsole`) doesn't support that undocumented variable. – palswim Nov 14 '19 at 21:24
  • @palswim - I think I would be surprised if it did. – dbenham Nov 14 '19 at 22:58
3

You can do something like this:

set "CurrentDir=%CD%"
if "%CD:~-1%"=="\" set "CurrentDir=%CD:~0,-1%"

Since you don't want to go changing the system variable %CD%, this sets a new variable %CurrentDir% to the current value of %CD%. Then, it checks to see if the last character in %CD% is a \, and if it is, sets %CurrentDir% to the value of %CD%, minus the last character.

This question/answer has more information on using substrings in batch files.

Community
  • 1
  • 1
Wes Larson
  • 1,042
  • 8
  • 17
3

replace every occurence of \\ with \.

echo %updatedir:\\=\%
Stephan
  • 53,940
  • 10
  • 58
  • 91