Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch-file variable %CD% adding a backslash when run from drive root

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?

like image 677
Mantis Avatar asked Dec 25 '22 05:12

Mantis


2 Answers

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
like image 88
dbenham Avatar answered Jan 24 '23 09:01

dbenham


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.

like image 23
Wes Larson Avatar answered Jan 24 '23 09:01

Wes Larson