Changing a batch file when its running

后端 未结 6 689
北荒
北荒 2020-12-01 05:22

I am running a long running batch file. I now realize that I have to add some more commands at the end of the batch file (no changes to exisiting content, just some extra co

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 06:09

    Nearly like rein said, cmd.exe remember the file position (not only the line position) it's currently is, and also for each call it push the file position on an invisble stack.

    That means, you can edit your file while it's running behind and before the actual file position, you only need to know what you do ...

    A small sample of an self modifying batch
    It changes the line set value=1000 continuously

    @echo off
    setlocal DisableDelayedExpansion
    :loop
    REM **** the next line will be changed
    set value=1000
    rem ***
    echo ----------------------
    echo The current value=%value%
     nul
    echo(
    (
    call :changeBatch
    rem This should be here and it should be long
    )
    rem ** It is neccessary, that this is also here!
    goto :loop
    rem ...
    :changeBatch
    set /a n=0
    set /a newValue=value+1
    set /a toggle=value %% 2
    set "theNewLine=set value=%newValue%"
    if %toggle%==0 (
       set "theNewLine=%theNewLine% & rem This adds 50 byte to the filesize.........."
    )
    del "%~f0.tmp" 2> nul
    for /F "usebackq delims=" %%a in ("%~f0") DO (
       set /a n+=1
       set "line=%%a"
       setlocal EnableDelayedExpansion
       if !n!==5 (
           (echo !theNewLine!)
       ) ELSE (
           (echo !line!)
       )
       endlocal
    ) >> "%~f0.tmp"
    (
      rem the copy should be done in a parenthesis block
      copy "%~f0.tmp" "%~f0" > nul
      if Armageddon==TheEndOfDays (
       echo This can't never be true, or is it?
      )
    )
    echo The first line after the replace action....
    echo The second line comes always after the first line?
    echo The current filesize is now %~z0
    goto :eof 
    

提交回复
热议问题