0

In a backup-restore scenario, I'm trying to generate a helper from within a batch.

The helper just combines restore.bat and an argument of the form state-%today%.zip to allow a specific restore without opening a command prompt or drag and drop:

call restore.bat state-YYYYMMDD.zip

This way it can be easily generated by backup.bat. But the helper fails if it was run as administrator (which is the actual goal of the coupling) because due to the context switch the current work directory changes to C:\Windows\system32 and that's why the helper's sibling file is not found.

This can be fixed by using %~dp0 that returns the path of the helper batch dynamically. My hand-made solution works as expected:

pushd %~dp0
call restore.bat %~dp0state-YYYYMMDD.zip
popd

Since YYYYMMDD is determined at backup time. I now need to generate the helper dynamically from within backup.bat, the first approach is

backup.bat

set HELPER=restore-%today%.bat
echo pushd %~dp0 > %HELPER%
echo restore.bat %~dp0state-%today% >> %HELPER%
echo popd >> %HELPER%

but the result

helper-20210630.bat

pushd c:\users\me\test\
call restore.bat c:\users\me\test\state-20210630.zip
popd

...is not portable to other folders. How do I pipe %~dp0 verbatim to the helper batch?

I found nothing in

And the advice to escape % via ^ that I found in batch-file - Echo output to file | batch-file Tutorial didn't work.

Wolf
  • 9,679
  • 7
  • 62
  • 108
  • I'm not sure this question has the potential to actually be reopened at some point. At least the title was too specific to attract readers (or search engines) so I changed it to better reflect my actual goal. – Wolf Jul 01 '21 at 08:39

1 Answers1

0

As I found out by trial and error is that the percent sign (%) has to be escaped by doubling (%%).

test-path.bat

@echo off
echo %%cd%% : %cd%
echo %%~dp0 : %~dp0

set TEST_OUT=%~dp0test-out.bat

echo echo %%%%cd%%%% : %%cd%% >%TEST_OUT%
echo echo %%%%~dp0 : %%~dp0 >>%TEST_OUT%

call %TEST_OUT%
pause

BTW: above script can also be used to show the divergence of the current work directors between a normal start as you by double clicking or pressing enter on it, or via context menuRun as administrator


The whole case now turns out to be just another variation of Escape percent in bat file. But we all know that once you've worked out a solution, you suddenly find it everywhere.

Wolf
  • 9,679
  • 7
  • 62
  • 108