0

I'd like to write a batch file, which reads its own code inside a string, then creates a new batch file with the string as content and execute it.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • And where do you want to get with this? No memory? – Radu Gheorghiu Nov 07 '13 at 09:58
  • are you looking for something like `%0 | %0` – JDong Nov 07 '13 at 10:05
  • @radugheorghiu i want to create a selfe replicating batch with an mutation algorithm ofcourse it should have also an algorithm wich prevents a to high number of files and lets it die after a certain number of replications – Raymond Osterbrink Nov 07 '13 at 10:05
  • @RaymondOsterbrink Then it might work. Just try what Nemesis said. – Radu Gheorghiu Nov 07 '13 at 10:21
  • Quines are related to your question, try a look at [Quines on Dostips](https://www.dostips.com/DtTipsQuine.php) and [the forum thread](https://www.dostips.com/forum/viewtopic.php?t=5728) – jeb Feb 05 '21 at 06:01

2 Answers2

2

You can read the content of the started batch file with

    type "%~f0"

Therefore, try something like

    echo off
    type "%~f0" > Test\file.bat
    Test\file.bat

However, this script would repeat itself continously (or aborts if the directory Test does not exist). So you need to think about this approach (i.e. using conditional statements).

Nemesis
  • 2,324
  • 13
  • 23
  • this is great, but is there a way to store the code inside a variable before creating the new batch, so i can modify it before? – Raymond Osterbrink Nov 07 '13 at 10:19
  • Just have a look at: http://stackoverflow.com/questions/2323292/windows-batch-assign-output-of-a-program-to-a-variable – Nemesis Nov 07 '13 at 10:30
0
@echo off
setlocal DisableDelayedExpansion

if not exist newBatchFile.bat (

   echo First execution!

   set "batchFile="
   for /F "usebackq delims=" %%a in ("%~F0") do (
      set "line=%%a"
      setlocal EnableDelayedExpansion
      if "!line:~0,1!" equ ")" set "batchFile=!batchFile:~0,-1!"
      set "batchFile=!batchFile!!line!"
      if "!line:~-1!" neq "(" set "batchFile=!batchFile!&"
      for /F "delims=" %%b in ("!batchFile!") do endlocal & set "batchFile=%%b"
)
   setlocal EnableDelayedExpansion
   echo !batchFile:~0,-1! > newBatchFile.bat
   newBatchFile.bat

) else (

   echo Second execution!

)
Aacini
  • 65,180
  • 12
  • 72
  • 108