Search code examples
batch-file

How can I make a batch file copy itself?


Isn't it supposed to be just a simple command? COPY 0%.BAT FOLDER? I have a batch file inside a folder which is inside another folder that is on the desktop (Desktop > Temp > activity > test.bat). In the batch file at the end I added this:

COPY %0.BAT Temp

so basically I want to copy it to copy itself to the parent folder without it running. and one more thing, how can I redirect the output of my batch file commands to a nul device?


Solution

  • You want to copy the batch file up 2 folders, right? How about this?

    @echo off
    copy %0 ..\..\temp >nul
    

    If you want to redirect the standard output of a command to nowhere, use >nul. Use @echo off to turn off all output.

    Update to explain what %0 is:

    When running a batch file, values like "%0" or "%1" refer to the arguments passed into the batch file. The value %0 is the batch file itself, the value %1 is the first argument passed to the batch file, %2 is the second argument, etc.. So for example if you had a file FOO.BAT which contained:

    echo 1st arg: '%0'
    echo 2nd arg: '%1'
    echo 3rd arg: '%2'
    

    If you ran:

    C:\foo.bat hello world
    

    The output would be:

    1st arg: 'foo.bat'
    2nd arg: 'hello'
    3rd arg: 'world'