touch with DOS commands

by Brett on March 20, 2007

I often use Cygwin to get access to a few linux style commands that I need. The command touch is one of those commands. In case your not familiar with it it will create/update the creation and modification times of a file to the current time. If the file specified does not exist it will also create an empty file.

The problem I recently encountered though was I needed the touch functionality but on a computer that did not have Cygwin installed. Of course I could have just put together a quick little C# or Java program to do the trick but I still would have to install the app onto this other computer.

The solution to this delimia was to use the following dos command which will create an empty file:
copy /y nul file.txt

  • errr

    That seems to clear(!!) the file, rather than touching it

  • You are right! I have only used that command to quickly create an empty file. I have never used it for updating the modification time of an existing file.

    I do not know of a way to modify the date modified of a file in dos without using a third party program. Although, if you want the date modified to be updated to the current time you could use one of the follow commands:

    1. This copies the file to a temp File and then copies the temp File back over the original. Then deletes the temp File.
    type file.txt > tmpFile.txt | type tmpFile.txt > file.txt | del tmpFile.txt

    2. Type: edit file.txt, then hit: alt, f, s, alt, f, x

    I really think both solutions are hacks at best. I also wonder what would happen to unicode files or files that have unix style line endings.

  • @copy nul: /b +%1 tmp.$$$
    @move tmp.$$$ %1

    doesn’t change anything in, only time and date

  • @copy %1 + nul %1 /by

    also works, provided copy is new enough to test that it shouldn’t overwrite the original file

  • dolphin

    @COPY /B %1 +,,

    I found that command on the following page:

  • Simone

    type nul >> “c:\file.txt”

  • There are two parts to the behavior of ‘touch’:

    1) if the file doesn’t exist, create it (which also sets the current date/time)
    2) if the file does exist, update the date and time

    In both cases, nothing is added or removed from the contents of the file (the first case starts with an empty file).

    The use of copy will fail for the first case, and the use of just ‘type nul >> foo’ will not work for the second case. You will have to combine both of these approaches:

    @echo off
    type nul >> %1
    copy /b %1 +,,

  • nitin

    Perfect Simone & dangerOp. Exactly what I was looking for. My copy /Y nul test.txt was creating the file the first time but I didn’t want it to overwrite the file the next time without popping the confirmation message. type nul >> test.txt worked just fine for me. I was not concerned about the timestamp part anyway.
    Thanks guys.

Previous post:

Next post: