Creating Loop Touching Files with Increasing Time Stamps: A Tech Support Guide

Abstract: Create 50 files with incrementing timestamps on Linux, macOS, and Windows using touch or PowerShell.

Created: 2026-10-04 by

To create 50 files with increasing timestamps, use the touch command in Linux or macOS by iterating through a loop and setting the modification time using -d or -t flags. On Windows, utilize PowerShell’s New-Item cmdlet combined with Set-ItemProperty to manipulate the LastWriteTime attribute for each generated file sequentially.

Understanding File Timestamps and System Differences

File systems store metadata about every file, including creation, modification, and access times. These timestamps are crucial for version control, backup synchronization, and forensic analysis. However, the way different operating systems handle these attributes varies significantly. In Unix-like systems, such as Linux and macOS, the touch utility is the standard tool for changing file timestamps. It can update the access and modification times of a file to the current system time or set them to a specific date and time provided by the user.

Windows operates differently. While it also tracks creation, last write, and last access times, the native command-line interface (CMD) lacks a direct equivalent to touch that easily handles arbitrary timestamp manipulation without third-party tools. PowerShell, however, provides robust object-oriented commands that allow precise control over file properties. This distinction means that a solution suitable for one platform may not work on another without adaptation. Understanding these underlying mechanisms is essential before attempting to automate the creation of multiple files with specific temporal sequences.

The Linux Approach: Using Touch with Loops

In Linux environments, creating a sequence of files with incrementing timestamps is straightforward using Bash scripting. The core command is touch, which accepts various options to modify time attributes. To create 50 files where each subsequent file has a timestamp one minute later than the previous one, you can employ a for loop.

#!/bin/bash
start_time=$(date -d "2023-01-01 00:00:00" +%s)
for i in {1..50}; do
    # Calculate the new timestamp by adding i minutes
    new_time=$((start_time + i * 60))
    # Convert seconds back to a readable format for touch
    formatted_time=$(date -d @$new_time "+%Y%m%d%H%M.%S")
    # Create the file and set its timestamp
    touch -t $formatted_time "file_$(printf '%03d' $i).txt"
done

This script initializes a starting epoch time, then iterates 50 times. In each iteration, it calculates the new timestamp by adding multiples of 60 seconds (one minute) to the start time. The date command converts this epoch value into a format compatible with touch's -t flag, which expects a string like YYYYMMDDhhmm.ss. The resulting files are named sequentially, ensuring clarity when reviewing the output. This method is efficient and relies entirely on standard POSIX utilities available in most Linux distributions.

The macOS Variation

macOS inherits much of its command-line heritage from BSD Unix, making the touch command largely similar to its Linux counterpart. However, there are subtle differences in how the date command parses strings. On macOS, the -d flag used in GNU coreutils (Linux) is not supported. Instead, you must use -j (no input file) and -f (input format) to parse dates, or rely on epoch calculations which are more portable across both platforms.

#!/bin/bash
start_epoch=$(date -j -f "%Y-%m-%d %H:%M:%S" "2023-01-01 00:00:00" +%s)
for i in {1..50}; do
    new_epoch=$((start_epoch + i * 60))
    formatted_time=$(date -r $new_epoch "+%Y%m%d%H%M.%S")
    touch -t $formatted_time "file_$(printf '%03d' $i).txt"
done

This script uses -j -f to interpret the initial date string and -r to convert the calculated epoch back to a displayable format. The rest of the logic remains identical to the Linux example. Users should note that if they are using Homebrew-installed GNU coreutils, the Linux syntax might work, but relying on native BSD utilities ensures compatibility without additional dependencies.

Implementing the Solution in Windows PowerShell

On Windows, the process requires PowerShell because the traditional Command Prompt does not expose file timestamp properties directly. PowerShell treats files as objects with accessible properties. You can create a file using New-Item and then immediately modify its LastWriteTime property using Set-ItemProperty.

$startDate = Get-Date "2023-01-01 00:00:00"
for ($i = 1; $i -le 50; $i++) {
    $fileName = "file_{0:D3}.txt" -f $i
    $filePath = Join-Path -Path "." -ChildPath $fileName
    
    # Create the empty file
    New-Item -ItemType File -Path $filePath -Force | Out-Null
    
    # Calculate the new timestamp
    $newTime = $startDate.AddMinutes($i)
    
    # Set the LastWriteTime property
    Set-ItemProperty -Path $filePath -Name LastWriteTime -Value $newTime
}

This script defines a start date and loops 50 times. Inside the loop, it constructs the filename using string formatting to ensure zero-padded numbers. After creating the file with New-Item, it calculates the new time by adding $i minutes to the start date. Finally, Set-ItemProperty updates the LastWriteTime attribute. Note that while this sets the modification time, Windows also tracks a creation time which may not be updated by this specific command unless additional API calls are made. For most testing purposes, manipulating the last write time is sufficient to simulate sequential file generation.

Verifying and Managing Generated Files

Once the scripts have executed, it is important to verify that the timestamps were applied correctly. In Linux and macOS, running ls -l will display the modification time next to each filename. In PowerShell, you can inspect the results by piping the file list to Select-Object and displaying the LastWriteTime property. If the timestamps appear incorrect, check the timezone settings of your system, as scripts often assume UTC or local time depending on the configuration.

These generated files are frequently used for testing backup software, monitoring log rotation, or simulating data ingestion pipelines. If you need to clean up these test artifacts, you can delete them individually or remove the entire directory. For those looking to manage cache intervals regularly, see Way to Clear Cache Regular Intervals without Application. Additionally, if you encounter unexpected output files during development, refer to Deleting Unexpected Output: How to Delete a Single File for best practices on cleanup.

Frequently Asked Questions

Can I create files with decreasing timestamps?

Yes, simply subtract the interval instead of adding it in your loop calculation. In Linux, change + i * 60 to - i * 60, and in PowerShell, use $startDate.AddMinutes(-$i). This allows you to simulate files being created in reverse chronological order.

Does this method update the creation time on Windows?

No, Set-ItemProperty only modifies the LastWriteTime and CreationTime properties that are exposed via .NET. Typically, the CreationTime is set when the file is first instantiated by New-Item. To strictly control creation time, you would need to use Win32 API calls via C# or specialized third-party tools, as PowerShell's native cmdlets do not fully support overriding the birth time attribute.

What happens if I run the script twice?

If you run the script again without deleting the existing files, the script will likely overwrite them due to the fixed naming convention. In Linux, touch updates the timestamp of an existing file rather than creating a new one. In PowerShell, New-Item -Force will replace the existing file. Always clear the target directory before re-running to ensure accurate testing results.

Is it possible to do this without a loop?

For small numbers of files, you can manually invoke the touch or New-Item commands for each file. However, for 50 or more files, a loop is the only practical approach. Manual entry is prone to errors and extremely time-consuming. Automation ensures consistency and speed, which is critical for generating large datasets for testing.

How do I handle timezones in these scripts?

Timestamps are generally interpreted in the system's local timezone unless specified otherwise. To force UTC, you can export the TZ=UTC environment variable before running the script in Linux/macOS. In PowerShell, you can specify [System.DateTimeKind]::Utc when creating the initial date object. Consistency between the script's timezone assumption and the system clock is vital for accurate timestamp placement.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More