Skip to content

Instantly share code, notes, and snippets.

@Foadsf
Created October 30, 2024 06:19
Show Gist options
  • Save Foadsf/4af33964da484715b217461173e4ba50 to your computer and use it in GitHub Desktop.
Save Foadsf/4af33964da484715b217461173e4ba50 to your computer and use it in GitHub Desktop.
Windows batch implementation of Unix touch with recursive directory support
@echo off
setlocal enabledelayedexpansion
:: touch.bat - Windows implementation of Unix touch command
:: Usage: touch filename [filename2 filename3 ...]
:: Creates empty files if they don't exist or updates their timestamps if they do
:: Supports full paths and can create directories if needed
if "%~1"=="" (
echo Usage: touch filepath [filepath2 filepath3 ...]
echo Creates new empty files or updates timestamps of existing files
echo Supports full paths and can create necessary directories
exit /b 1
)
:process_args
if "%~1"=="" goto :eof
set "filepath=%~1"
set "directory=%~dp1"
:: Remove trailing backslash for root directories
if "%directory:~-2%"==":\" set "directory=%directory:~0,-1%"
:: Check if directory exists
if not exist "%directory%\" (
echo Directory does not exist: %directory%
set /p "create=Would you like to create the directory path? (Y/N) "
if /i "!create!"=="Y" (
mkdir "%directory%" 2>nul
if errorlevel 1 (
echo Error: Failed to create directory path: %directory%
exit /b 1
)
echo Created directory path: %directory%
) else (
echo Operation cancelled for: %filepath%
goto :next_arg
)
)
:: Process the file
if exist "%filepath%" (
:: File exists - update timestamp using copy trick
copy /b "%filepath%"+,, "%filepath%" >nul 2>&1
if errorlevel 1 (
echo Error: Failed to update timestamp for "%filepath%"
exit /b 1
)
echo Updated: %filepath%
) else (
:: File doesn't exist - create it
type nul > "%filepath%" 2>nul
if errorlevel 1 (
echo Error: Failed to create "%filepath%"
exit /b 1
)
echo Created: %filepath%
)
:next_arg
:: Process next argument
shift
goto process_args
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment