Search code examples
loggingcmdcopybatch-processing

Batch file to loop through a copy command


I have quite a few batch files that create and backup log files. I have them working but would like to make them more stream line. Here is the commands I am using:

copy Send-bak29.log Send-bak30.log
copy Send-bak28.log Send-bak29.log
copy Send-bak27.log Send-bak28.log
copy Send-bak26.log Send-bak27.log
copy Send-bak25.log Send-bak26.log
copy Send-bak24.log Send-bak25.log
copy Send-bak23.log Send-bak24.log
copy Send-bak22.log Send-bak23.log
copy Send-bak21.log Send-bak22.log
copy Send-bak20.log Send-bak21.log
copy Send-bak19.log Send-bak20.log
copy Send-bak18.log Send-bak19.log
copy Send-bak17.log Send-bak18.log
copy Send-bak16.log Send-bak17.log
copy Send-bak15.log Send-bak16.log
copy Send-bak14.log Send-bak15.log
copy Send-bak13.log Send-bak14.log
copy Send-bak12.log Send-bak13.log
copy Send-bak11.log Send-bak12.log
copy Send-bak10.log Send-bak11.log
copy Send-bak9.log Send-bak10.log
copy Send-bak8.log Send-bak9.log
copy Send-bak7.log Send-bak8.log
copy Send-bak6.log Send-bak7.log
copy Send-bak5.log Send-bak6.log
copy Send-bak4.log Send-bak5.log
copy Send-bak3.log Send-bak4.log
copy Send-bak2.log Send-bak3.log
copy Send-bak1.log Send-bak2.log
copy Send-bak.log Send-bak1.log
copy Send.log Send-bak.log

Basically it keeps a 30 day running log of the "Send.log" file. Is there a way I can use a loop command instead of multiple copy commands? Any help is greatly appreciated


Solution

  • Here's a loop. When you've run it and you're sure it's going to do the right thing, change all occurrences of echo copy to just copy.

    @echo off
    setlocal enabledelayedexpansion
    for /l %%i in (30 -1 2) do (
        set /a j = %%i - 1
        echo copy Send-bak!j!.log Send-bak%%i.log
    )
    echo copy Send-bak.log Send-bak1.log
    echo copy Send.log Send-bak.log
    

    However, note that copying the files is going to take a long time. It would be better to rename them, which is much faster. Instead of copy, use move /y. (The /y option tells the move command that it's ok to overwrite an existing file.)