Simple Touch Implementation in Windows Batch Programming


The touch command is a frequently-used utility on Linux, that allows you to create an empty file if it does not exist, or update the file time stamp to now.

touch Simple Touch Implementation in Windows Batch Programming windows batch

touch

The windows, by default, does not ship with this useful command line utility although you can get such tool from e.g. git, cygwin etc. You can, however, write a small batch file that implements the basic features of touch (except that you can’t specify the time stamp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@echo off
:: simple touch replacement by batch
:: https://helloacm.com
 
setlocal
set CreateFiles=True
 
:start
    if %1.==. goto :end
    if "%1"=="-c" (
        set CreateFiles=False
        shift
        goto :start
    )
    if exist "%1" (
        copy /b "%1" +,, > nul
    ) else (
        if "%CreateFiles%"=="True" (
            type nul > "%1" 
        )       
    )
    shift
    goto start
 
:end
endlocal
@echo off
:: simple touch replacement by batch
:: https://helloacm.com

setlocal
set CreateFiles=True

:start
	if %1.==. goto :end
	if "%1"=="-c" (
		set CreateFiles=False
		shift
		goto :start
	)
	if exist "%1" (
		copy /b "%1" +,, > nul
	) else (
		if "%CreateFiles%"=="True" (
			type nul > "%1"	
		)		
	)
	shift
	goto start

:end
endlocal
You can touch more than 1 files... Share on X
touch 1 2 3 4

If you don’t want to create files if they are non-existent, give it a -c switch.

touch -c sample

The copy /b “%1” +,, > nul will modify the time stamp without touch the file content.
The type nul > “%1” will empty a file whether they are existent or not.
The shift will shift all parameters to the left so “%1” becomes “%2”, “%2” becomes “%3” and so on (maximum %9).
The setlocal and endlocal defines a region for local variables (set) to live.

github source

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
340 words
Last Post: Use Dual Dedicated Graphic Cards on HPZ800 Server: Nvidia Quadro 2000D and ATI Radeon HD 6700
Next Post: How to avoid WordPress Emails going to Spam Folder?

The Permanent URL is: Simple Touch Implementation in Windows Batch Programming

2 Comments

  1. movsb

Leave a Reply