7

I am writing a batch file that does a number of operations in a folder that is specified relative to the first argument passed in to the batch file. Within the batch file, I would like to echo to the user the the folder I am working in. However, every time I echo the path, it contains the ....\ that I used to determine where to place my folder. For example.

set TempDir=%1\..\Temp
echo %TempDir%

So, if I run my batch file with a parameter \FolderA, the output of the echo statement is FolderA\..\Temp instead of \Temp as I would expect.

John Visser
  • 73
  • 1
  • 3
  • 1
    See also ... http://stackoverflow.com/questions/1645843/batch-file-resolve-absolute-path-from-relative-path-and-or-file-name – SteveC Oct 18 '13 at 07:44
  • If you're using Powershell, this is a good solution: https://stackoverflow.com/questions/495618/how-to-normalize-a-path-in-powershell – Andrew Koster Apr 23 '20 at 18:49
  • If you're not using Powershell, consider using Powershell to make the above solution available to you. – Andrew Koster Apr 23 '20 at 18:50

1 Answers1

10
SET "TempDir=%~1\..\Temp"
CALL :normalise "%TempDir%"
ECHO %TempDir%
…

:normalise
SET "TempDir=%~f1"
GOTO :EOF

…

The :normalise subroutine uses the %~f1 expression to transform the relative path into the complete one and store it back to TempDir.


UPDATE

Alternatively, you could use a FOR loop, like this:

SET "TempDir=%~1\..\Temp"
FOR /F "delims=" %%F IN ("%TempDir%") DO SET "TempDir=%%~fF"
ECHO %TempDir%
Andriy M
  • 76,112
  • 17
  • 94
  • 154