0

I'm writting a batch file and I want to move some files from root path to cd .. root.

I use %~dp0 to find the root path.

Whats the best method to go back one step from root path?

Thanks a lot

Paul F.
  • 17
  • 1
  • 8

2 Answers2

1

%~dp0 points to the parent directory of the current batch file (including a trailing \), %~dp0.. therefore points to the grand-parent directory of the batch file.

You can use a for loop and the ~f modifier of its variable reference (%%I) to resolve the path:

for %%I in ("%~dp0..") do echo/%%~fI
aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • Apart from the typo, your answer leaves me with more questions. Does `%~dp0.` point to the parent directory and `%~dp0...` point to the great grand-parent etc. If `%~dp0` expands to the drive letter and path, why do I need to use the `~f ` modifier. Is `"%~dp0.."` not expanded during the parentheses evaluation, therefore passing the fully expanded drive and path to a string as variable `"%%I"`. Why does it need another expansion with `~f`? – Compo Sep 22 '17 at 10:05
  • @Compo, why should `%~dp0..` automatically become resolved? `%~dp0` simply expands to drive (`d`) and path (`p`) to the parent directory of the current batch file with trailing `\ `, no matter whether you prepend or append anything like `..`. A `.` points to the same directory (so `anydir\middir\subdir` is the same as `anydir\middir\subdir\.`), `..` points to the parent directory (so `anydir\middir\subdir\..` is the same as `anydir`); there is no `...` (you need to do `anydir\middir\subdir\..\..` to point to `anydir`)... – aschipfl Sep 22 '17 at 10:27
  • @Compo, and what do you mean by "parentheses evaluation"? you mean, that `for` resolves the part after `in` automatically? no, it does not; it does never resolve paths like `anydir\middir\subdir\..\.\..\file.ext`, it only resolves wild-cards (`*`, `?`) when such appear in the last path element (so behind the last `\ `); you need to use the `~f` modifier for the path to become resolved; note that `for` does not access the file system to check whether the path truly exists, unless wild-cards are included... – aschipfl Sep 22 '17 at 10:32
0

you are almost there, just use %~dp0..

or if you want it fully resolved, use this trick

@echo off
call :resolve "%~dp0.."
goto :eof

:resolve
echo %~f1
goto :eof

for an explanation, see this SO answer https://stackoverflow.com/a/15568171/30447

PA.
  • 28,486
  • 9
  • 71
  • 95