Add Timestamp Prefix to Filename while Creating File in Bash

Abstract: Prevents file overwrites by adding a timestamp prefix to filenames during creation in Bash.

Created: 2026-09-04 by
To add a timestamp prefix to a filename in Bash, use the date command with a specific format string and combine it with your desired filename using shell expansion or a function. This approach ensures unique file names that reflect creation time, preventing overwrites and aiding in chronological organization of logs, backups, or temporary data files.

Using Shell Expansion for Quick Creation

The most immediate way to create a file with a timestamped name is directly within the command line using parameter expansion. This method relies on the $(...) syntax, which executes the enclosed command and substitutes its output into the current string. For example, if you want to create a log file named with the current date and time, you can type:
touch $(date +%Y%m%d_%H%M%S)_log.txt
In this command, date +%Y%m%d_%H%M%S generates a string like 20231027_143022. The touch command then creates an empty file named 20231027_143022_log.txt. This technique works for any command that accepts a filename argument, such as cp, mv, or text editors like vim or nano. It is particularly useful for one-off tasks where you do not want to define persistent scripts or aliases. When dealing with filenames that might contain spaces or special characters, ensure you quote the entire expanded string to prevent word splitting. For instance, echo "data" > "$(date +%F)_report.csv" safely creates a file named 2023-10-27_report.csv. If you are interested in customizing how Bash displays these prompts or abbreviations during interaction, you might find Understanding Bash Prompt Abbreviations: An Overview helpful for broader context on shell customization.

Creating a Reusable Bash Function

For frequent use, defining a Bash function is more efficient than typing the full command repeatedly. A function allows you to encapsulate the logic and provide a simple interface. Add the following snippet to your ~/.bashrc or ~/.bash_profile file:
mktime() {
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local filename="${1:-file.txt}"
    local new_name="${timestamp}_${filename}"
    
    # Check if the file already exists to avoid accidental overwrites
    if [[ -e "$new_name" ]]; then
        echo "Error: File '$new_name' already exists."
        return 1
    fi
    
    touch "$new_name"
    echo "Created file: $new_name"
}
This function, named mktime, takes an optional argument for the base filename. If no argument is provided, it defaults to file.txt. It generates the timestamp, constructs the new name, checks for existence to prevent data loss, and then creates the file. After adding this to your configuration file, run source ~/.bashrc to load the changes into your current session. You can then simply call mktime mydata.csv to create 20231027_143022_mydata.csv. Functions offer greater flexibility than aliases because they support variables, conditional logic, and error handling. Aliases are essentially simple text substitutions and cannot handle complex logic or arguments dynamically. If you are experiencing issues with special characters or quoting in your scripts, reviewing best practices for handling spaces and dashes can be beneficial, as discussed in Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting.

Customizing Date Formats

The appearance of the timestamp depends entirely on the format string passed to the date command. Common formats include:
  • %Y-%m-%d: ISO 8601 standard (e.g., 2023-10-27). This is highly recommended for sorting.
  • %d/%m/%Y: European date format (e.g., 27/10/2023).
  • %s: Unix epoch time (seconds since Jan 1, 1970). Useful for precise ordering but less human-readable.
  • %H:%M: Time only (e.g., 14:30).
You can mix these components with separators like underscores, hyphens, or dots. Avoid using forward slashes (/) or colons (:) in filenames on most operating systems, as they are reserved for directory separation or time notation in some contexts. Always test your format string by running date +your_format in the terminal before embedding it in a script.

Handling Timestamps in Existing Files

Sometimes you may need to rename existing files rather than create new ones. You can achieve this by combining find with exec or a loop. However, caution is advised when renaming large numbers of files. Before performing bulk operations, always back up your data. If you are managing synchronization between directories where timestamps matter, understanding how tools like rsync handle sub-directories and modification times is crucial, as detailed in rsync: Not Iterating Sub-Directories - Modify Timestamp?.

Frequently Asked Questions

How do I prevent overwriting existing files with the same timestamp?

Always check if the target filename exists before creating it using the -e test operator in Bash. In the function example above, we included a conditional check that returns an error if the file already exists, ensuring data integrity.

Can I use milliseconds in the timestamp?

Yes, use %N in the date format string to get nanoseconds. Since millisecond precision is often sufficient, you can truncate it using ${var:0:3} in Bash parameter expansion to get just the first three digits of the nanosecond field.

Why are my filenames appearing in wrong order when sorted?

Sorting issues usually arise from non-standardized date formats. Using the ISO 8601 format (%Y-%m-%d) ensures that lexicographical sorting matches chronological sorting, which is critical for automated backup systems and log analysis.

Does this work in Windows Command Prompt or PowerShell?

No, the date command syntax and Bash functions are specific to Unix-like environments. On Windows, you would use PowerShell cmdlets like Get-Date or CMD variable expansions with different syntaxes to achieve similar results.

How do I remove the timestamp prefix later?

You can use the sed command or Bash parameter expansion to strip the prefix. For example, mv "${file}" "${file#*_}" removes everything up to the first underscore, effectively deleting the timestamp part if it ends with one.

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