Recent from talks
Nothing was collected or created yet.
Touch (command)
View on Wikipedia| touch | |
|---|---|
Example of touch usage | |
| Original author | AT&T Bell Laboratories |
| Developers | Paul Rubin, Arnold Robbins, Jim Kingdon, David MacKenzie, Randy Smith, TSC, Microware, Apple, Digital Research, Novell, Kris Heidenstrom |
| Initial release | January 1979 |
| Written in | C |
| Operating system | Unix, Unix-like, Plan 9, Inferno, FLEX, OS-9, Classic Mac OS, Windows, DR DOS, AROS, FreeDOS, ReactOS, KolibriOS, IBM i |
| Platform | Cross-platform |
| Type | Command |
| License | coreutils: GPLv3+ FreeDOS: GPLv2 ReactOS: BSD-4-Clause BusyBox: GPL-2.0-only Toybox: 0BSD Plan 9: MIT License |
touch is a shell command that sets the modification timestamp of an existing file to be current – which on a Unix-based file system includes special files such as directories. If the input path does not specify an existing file, then it creates a new, regular file at the path.
The Single UNIX Specification (SUS) specifies that touch changes the access or modification timestamps, or both. The file is identified by file system path supplied as the sole argument. If the path does not specify a file, the command creates a file with access and modification timestamps as specified or by default to the current time.
By default (no options specified), touching a file is equivalent to creating it with no content or if it exists, opening and saving it without any content changes to update the modification timestamp to be current. This convenience functionality is useful for a variety of scenarios including build and backup. The tools used in such scenarios typically ignore files that are older than a certain point of time. For example, make ignores a source code file that is older than the object file it is used to create.
The command is often used to create a new file, so that can subsequently open it in an editor or to create a file required by an operation that does not require specific content.
A command first appeared in Version 7 AT&T UNIX. Today, the command is available for many operating systems, including many Unix and Unix-like systems, Windows (via UnxUtils[1] and Touch for Windows.[2]), classic Mac OS, DOS, FreeDOS,[3][4] DR DOS 6.0,[5] KolibriOS,[6] FLEX,[7] AROS,[8] OS-9,[9] ReactOS,[10] and IBM i.[11] The version bundled in GNU Core Utilities was written by Paul Rubin, Arnold Robbins, Jim Kingdon, David MacKenzie, and Randy Smith.[12]
See also
[edit]References
[edit]- ^ "Native Win32 ports of some GNU utilities". unxutils.sourceforge.net. Archived from the original on 9 February 2006. Retrieved 11 August 2025.
- ^ "touch for Windows".
- ^ "ibiblio.org FreeDOS Package -- touch (Unix-like)". www.ibiblio.org. Archived from the original on 13 March 2019. Retrieved 13 November 2018.
- ^ "ibiblio.org FreeDOS Group -- Utilities". www.ibiblio.org. Archived from the original on 30 September 2018. Retrieved 13 November 2018.
- ^ "DR DOS 6.0 User Guide Optimisation and Configuration Tips" (PDF). Archived from the original on 30 September 2019. Retrieved 11 August 2019.
- ^ "Shell - KolibriOS wiki". wiki.kolibrios.org. Archived from the original on 11 February 2019. Retrieved 11 August 2019.
- ^ "FLEX 9.0 User's Manual" (PDF). Archived (PDF) from the original on 25 July 2021. Retrieved 10 June 2019.
- ^ "AROS Research Operating System". aros.sourceforge.io. Archived from the original on 2 July 2019. Retrieved 12 September 2020.
- ^ Paul S. Dayan (1992). The OS-9 Guru - 1 : The Facts. Galactic Industrial Limited. ISBN 0-9519228-0-7.
- ^ "reactos/reactos". GitHub. Archived from the original on 11 December 2017. Retrieved 29 July 2019.
- ^ IBM. "IBM System i Version 7.2 Programming Qshell" (PDF). IBM. Archived (PDF) from the original on 18 September 2020. Retrieved 5 September 2020.
- ^ "touch(1): change file timestamps - Linux man page". linux.die.net. Archived from the original on 27 March 2019. Retrieved 27 January 2019.
Further reading
[edit]- McElhearn, Kirk (2006). The Mac OS X Command Line: Unix Under the Hood. John Wiley & Sons. ISBN 978-0470113851.
External links
[edit]- – Shell and Utilities Reference, The Single UNIX Specification, Version 5 from The Open Group
- – Linux User Commands Manual
- – Plan 9 Programmer's Manual, Volume 1
- – Inferno General commands Manual
- examples showing how to use touch
Touch (command)
View on Grokipediatouch command is a standard utility in Unix-like operating systems, defined by the POSIX standard, that updates the last access time and last modification time of specified files to the current system time.[1] If a specified file does not exist, touch creates it as an empty file with default permissions (read/write for owner, group, and others).[1] This dual functionality makes it essential for tasks like preparing placeholder files or refreshing timestamps without altering file contents.[2]
Originally introduced in Version 7 Unix by AT&T Bell Laboratories in 1979, the command's name derives from its mechanism of "touching" a file—reading and rewriting a character to update its modification date—without other changes. In early implementations, such as V7, if the file was empty and non-existent, it would still create it empty, but no action was taken on existing empty files to avoid unnecessary writes.[3] The utility has since evolved to conform to POSIX.1-2017, supporting options like -a to change only access time, -m for modification time only, -c to avoid creating non-existent files, and -t or -d to set custom timestamps.[1] It is implemented in tools like GNU Coreutils for Linux and BSD variants, ensuring portability across systems.
Common use cases include creating multiple empty files with touch file1.txt file2.txt, updating timestamps for build tools like make that rely on file times for dependency checks, or simulating recent activity on files for testing purposes.[2] While simple in syntax—typically touch [options] file—its precise control over timestamps supports advanced scripting and system administration workflows.[1]
Overview
Purpose and Core Functionality
Thetouch command is a standard Unix utility designed to update the access time (atime), which records the last time a file was read or accessed, and the modification time (mtime), which indicates the last time the file's content was altered, to the current system time.[1] By default, it modifies both timestamps simultaneously unless specified otherwise, ensuring that file metadata reflects recent interaction without altering the file's content.[1] This functionality aligns with the POSIX.1-2017 standard and the Single UNIX Specification, which mandate that touch shall change the last data access and modification timestamps using system calls such as utimensat() for existing files.[1]
If the specified file does not exist, touch creates an empty regular file with the given name, setting its initial atime and mtime to the current time, provided the parent directory exists and the -c option is not used to prevent creation.[1] For existing files, including directories and special files such as symbolic links or device files, touch updates the applicable timestamps without changing the file's data or attributes.[1] Notably, Unix file systems also maintain a change time (ctime), which tracks the last modification to the file's inode metadata, such as permissions or ownership; however, touch cannot directly set ctime, as it is automatically updated by the system whenever inode changes occur, including during touch operations.[4]
Originating in Version 7 Unix released by AT&T in 1979, touch has become a foundational tool for precise file timestamp management in Unix-like systems.
Common Applications
Thetouch command plays a key role in software build processes, particularly with tools like make, where updating file timestamps signals that dependencies are current, thereby preventing unnecessary recompilations and optimizing build efficiency. By modifying the modification time of object files or targets to a recent value, developers can mark them as up-to-date relative to source files, which rely on timestamp comparisons to determine rebuild needs. This application is especially valuable in large-scale projects, reducing compilation overhead without altering file contents.[5][6]
In backup and synchronization workflows, touch ensures timestamp consistency across file trees, which is critical for tools like rsync that use modification times to detect changes and propagate updates efficiently. Administrators often employ it to refresh timestamps on synchronized files, avoiding redundant transfers or incomplete backups by aligning access and modification times with source directories. This maintains data integrity in mirrored environments, such as remote servers or archival systems, where mismatched timestamps could lead to overlooked files.[5][6]
For scripting and configuration purposes, touch is frequently used to create placeholder or empty files that serve as inputs for other programs, such as text editors or parsers, without requiring initial content. This initializes structures like log files or temporary inputs in automated pipelines, enabling seamless integration into broader workflows. In testing and debugging scenarios, it simulates file ages by setting specific timestamps, allowing developers to evaluate time-sensitive scripts or commands like find that filter based on modification dates.[7][6]
Within automation tasks, including cron jobs, touch facilitates periodic timestamp refreshes to trigger downstream processes, such as reloading configurations in web applications or marking completion of batch operations. By updating access or modification times at scheduled intervals, it supports monitoring systems that depend on recent file activity to initiate actions, enhancing reliability in long-running automated environments.[5][6]
Syntax and Options
Command Syntax
The basic syntax of thetouch command follows the standard utility format as defined in POSIX, allowing for optional flags followed by one or more file pathnames: touch [options] file...[1]. This structure enables the command to process multiple file operands sequentially, where each pathname specifies a file whose timestamps are to be updated or, if absent, created anew. The command accepts shell-expanded patterns for the file arguments, but operates directly on the resolved pathnames provided.[1]
When invoked on an existing file, touch updates the file's last access and last modification timestamps to the current time, unless alternative times are specified via options.[1] This behavior relies on the utimensat() system call with the file pathname, setting both timestamps equivalently to the specified or current time while preserving other file attributes.[1]
For non-existent files, touch creates empty regular files by invoking the creat() function with a default mode of 0666 (read and write permissions for owner, group, and others), adjusted by the process's umask to determine the final permissions.[1][8] Following creation, the timestamps are set using futimens() on the newly opened file descriptor, again defaulting to the current time. The file is then closed, leaving an empty file with the updated timestamps and no content.[1][9]
The command processes each file argument in sequence, applying the timestamp operations independently and reporting errors—such as permission denials or invalid pathnames—for individual files without halting execution on the first failure.[1] Upon completion, touch returns an exit status of 0 if all operations succeed and all requested changes are made; otherwise, it returns a non-zero value indicating that at least one error occurred during processing.[1]
Key Options and Flags
Thetouch command supports several options to customize the updating of file timestamps, allowing users to target specific times or behaviors without altering the default action of setting both access time (atime) and modification time (mtime) to the current time.[1] These options are standardized in POSIX.1-2017, with additional extensions in implementations like GNU coreutils.[5]
The -a (or --time=atime, --time=access, --time=use) flag changes only the access time of the file, leaving the modification time unchanged.[1] This is useful for simulating recent access without indicating file content changes. Similarly, the -m (or --time=mtime, --time=modify) flag updates only the modification time, preserving the access time.[1]
For precise timestamp control, the -t STAMP flag sets both access and modification times to a user-specified value in the format [[CC]YY]MMDDhhmm[.ss], where CC is the optional century, YY the year (with defaults based on POSIX rules: 69-99 implies 1900s, 00-68 implies 2000s), MM the month (01-12), DD the day (01-31), hh the hour (00-23), mm the minute (00-59), and optional .ss the seconds (00-60).[1] The -r REFERENCE_FILE (or --reference=REFERENCE_FILE) flag instead uses the timestamps from a specified reference file for both access and modification times of the target file(s).[1]
The -d date_time flag sets both access and modification times to a user-specified value in a human-readable format, such as YYYY-MM-DDThh:mm:SS (per POSIX.1-2017).[1] GNU coreutils extends parsing flexibility for -d and provides the equivalent --date=STRING option, supporting various date string formats (e.g., "2025-01-01 12:00:00").[5]
To avoid file creation, the -c (or --no-create) flag prevents the command from creating nonexistent files, applying updates only to existing ones and suppressing related warnings.[1] The --help flag displays usage information and exits, while --version outputs the program's version details and exits.[5]
POSIX requires support for -a, -c, -d, -m, -r, and -t, ensuring portability across conforming systems.[1]
History and Development
Origins in Unix
The touch command first appeared in Version 7 Unix, released by AT&T Bell Laboratories in January 1979, as part of the operating system's standard utility set.[10] This version marked the culmination of early Unix development at Bell Labs, where touch was introduced alongside other essential tools to support file system interactions in a multi-user environment.[11] The command's initial purpose was to simplify file timestamp management for developers and system administrators working in the resource-constrained early Unix environments, enabling quick updates to a file's modification time without substantive changes to its content or the need for complex editing tools.[3] By "touching" an existing file—reading and then rewriting a single character—it updated the last modified date to the current time, while also providing a straightforward way to create empty files if they did not exist, addressing common needs in program development and system maintenance tasks.[3] The core behaviors of touch, including default updates to access and modification timestamps using the current time, were formalized through the underlying system interfaces in the POSIX.1-1988 standard (IEEE Std 1003.1-1988), which specified functions likeutime() to ensure portable timestamp manipulation across conforming Unix-like systems.[12] This standardization built on touch's established role by defining reliable defaults for time updates, promoting consistency in shell scripting and automated processes.
Early documentation for touch appeared in the Unix Programmer's Manuals starting with Version 7, where the man page highlighted its minimalistic design for seamless integration into shell scripts, such as marking files for make-based builds or logging timestamps without altering file contents.[3] These manuals, distributed with the system, underscored touch's utility as a lightweight primitive in the Unix philosophy of small, composable tools.[3]
Implementations and Evolutions
The GNU implementation of thetouch command is part of the coreutils package, maintained by the Free Software Foundation since the early 1990s, with key contributions from developers including David MacKenzie, who announced the initial GNU fileutils in 1990.[13] The latest stable release of GNU coreutils as of November 2025 is version 9.9, which includes ongoing enhancements for timestamp precision, building on support for nanosecond resolution introduced in earlier versions to align with modern filesystems.[14] This nanosecond capability allows touch to set timestamps with sub-second accuracy using options like -t or --date (e.g., specifying fractional seconds), enabling compatibility with filesystems such as ext4 and ZFS that store high-precision metadata.[5]
Variants in BSD-derived systems, such as FreeBSD, and illumos-based distributions like OpenIndiana, exhibit slight differences in option support compared to the GNU version. For instance, in the BSD compatibility mode in illumos, the -f option forces the timestamp update even without read/write permissions, a legacy feature deprecated and ignored in the standard POSIX implementation in favor of options like -c to avoid creating non-existent files.[15] These implementations maintain core POSIX compliance but retain legacy options for backward compatibility with historical BSD behavior.[16]
Key evolutions in the touch command include the addition of the --reference (or -r) option, which allows setting a file's timestamps based on those of a reference file; this feature originated as a GNU extension and was later standardized in POSIX.1-2001.[17] Support for nanosecond timestamps represents another significant advancement, provided through GNU extensions that leverage kernel capabilities in filesystems like ext4 (since Linux kernel 2.6.22) and ZFS, allowing precise time manipulation beyond the traditional one-second granularity.[5][18]
Licensing for touch implementations has shifted from the proprietary AT&T model of early Unix to open-source paradigms. The original AT&T Unix utilities, including touch, were licensed restrictively until the 1980s divestiture enabled broader distribution; subsequent reimplementations in GNU coreutils adopted the GPLv3+ license starting in 2007, while BSD and illumos variants use permissive BSD-style licenses.[19]
As of 2025, recent updates emphasize integration with containerized environments like Docker, where touch is commonly used in Dockerfiles to enforce consistent timestamps across image layers, aiding reproducible builds and avoiding nondeterministic metadata that could affect caching or deployment reliability.[20][21]
Usage Examples
Basic File Creation and Timestamp Updates
Thetouch command in Unix-like systems primarily serves to create empty files or update the access and modification timestamps of existing ones to the current time when invoked without additional options. For instance, executing touch newfile.txt will create a new empty file named newfile.txt with a size of zero bytes if it does not already exist, setting both the access time (atime) and modification time (mtime) to the present moment. This behavior relies on the underlying creat() system call to establish the file with default permissions, typically 0666 modified by the user's umask.[1][2]
When applied to an existing file, such as touch existingfile.log, the command updates only the atime and mtime to the current time without modifying the file's content or size, effectively "touching" the file to indicate recent access or modification for logging or build system purposes. This operation uses utimensat() for existing files to adjust the timestamps precisely. The command can also handle multiple files in a single invocation, for example, touch file1.txt file2.txt dir/file3.txt, which creates any non-existent files among them as empty zero-byte entries and updates timestamps for those that exist, processing each operand sequentially.[1][2]
In cases of errors, such as attempting to create a file in a read-only directory with touch /readonly/dir/newfile.txt, the command outputs a permission denied error for that specific operation but continues processing any subsequent files in the argument list without halting entirely. To verify the effects, one can use ls -l afterward, which displays the file size, atime, and mtime; for a newly created file, this would show a size of 0 and timestamps matching the execution time, while an updated existing file retains its original size but shows refreshed timestamps. The -c option can prevent creation of non-existent files during such operations, producing no output or error if the target does not exist.[1][2]
Advanced Scenarios
In advanced usage, thetouch command enables precise control over file timestamps through options like -t for specifying custom dates and times, which is particularly useful in testing time-sensitive scripts or simulating future file states. For instance, to create or update a file with a timestamp of November 12, 2025, at 12:30:00, the command touch -t 202511121230.00 futurefile.txt sets both access and modification times accordingly, following the POSIX format [[CC]YY]MMDDhhmm[.SS] where the optional .SS denotes seconds.[22] This option leverages system calls like utimensat() to apply the specified timestamp, provided the filesystem supports it.[22]
Another sophisticated application involves synchronizing timestamps between files using the -r option, which copies the access and modification times from a reference file to the target. The command touch -r template.txt copy.txt ensures copy.txt inherits the exact timestamps of template.txt, facilitating consistent versioning in build processes or data replication workflows.[22] This is especially valuable when maintaining temporal dependencies across file sets without altering content.[2]
For scripting scenarios where conditional updates are needed, the -c (no-create) mode prevents file creation if the target does not exist, avoiding unintended artifacts in automated tasks. Executing touch -c outdated.log updates the timestamp only if outdated.log already exists, making it ideal for log rotation scripts or checks that assume file presence.[22] This option suppresses error messages for missing files, promoting silent operation in batch environments.[2]
Batch operations often combine touch with the find utility to refresh timestamps on multiple matching files, such as temporary files in a directory. The command find /dir -name "*.tmp" -exec touch {} + locates all files ending in .tmp and updates their timestamps to the current time in groups for efficiency, commonly used in cleanup or indexing routines. This approach minimizes overhead compared to individual invocations, leveraging find's -exec action to execute touch on discovered paths.
GNU implementations provide nanosecond support via the --date option on compatible filesystems, allowing sub-second granularity beyond POSIX requirements. For example, touch --date='2025-11-12 12:30:00.000123456' file.txt sets the timestamp to November 12, 2025, 12:30:00.000123456, where the fractional part after the decimal represents nanoseconds if the underlying filesystem (e.g., ext4 with nanosecond stat support) permits it.[2] This feature aids high-resolution timing in scientific computing or performance analysis.[5]
Portability and Variations
Cross-Platform Availability
Thetouch command is natively available across various Unix-like operating systems, forming a core part of their standard utilities. In Linux distributions, it is provided by the GNU coreutils package, enabling users to update file timestamps or create empty files directly from the shell.[2] On macOS, which derives from BSD, touch is included as a standard BSD utility, accessible via the Terminal application without additional installation. FreeBSD offers touch as part of its base system, supporting essential file timestamp operations in its POSIX-compliant environment.[16] Similarly, Oracle Solaris includes touch in its user commands, ensuring compatibility for enterprise Unix workloads.[23]
On Windows, there is no built-in touch command in the native Command Prompt or earlier versions of PowerShell, but approximations exist using PowerShell cmdlets such as (Get-Item file).LastWriteTime = Get-Date to update a file's last write time. However, Unix-like environments like Cygwin provide touch through its coreutils package, simulating a POSIX shell on Windows. MSYS2 offers touch via the same coreutils, integrated into its MinGW-w64 toolchain for developers. Git Bash, bundled with Git for Windows, includes touch as part of its MSYS2-derived utilities, allowing seamless use in version control workflows. Direct native access became possible with the introduction of Windows Subsystem for Linux (WSL) in Windows 10 and later, where touch runs within Linux distributions like Ubuntu installed via the Microsoft Store.
In legacy DOS environments, FreeDOS includes an implementation of touch in its standard utilities package, though with limited options compared to Unix variants, primarily for updating file dates and times.[24]
Beyond these, touch appears in specialized systems such as Plan 9 from Bell Labs, where it is implemented in the rc shell for file modification date setting. For embedded systems, BusyBox provides a minimal touch applet as part of its lightweight Unix utility suite, commonly used in resource-constrained devices like routers and IoT hardware.[25]
As of 2025, touch is widely accessible in cloud computing environments, including AWS EC2 instances running Amazon Linux, which includes it in coreutils for scripting and automation tasks.[26] Azure Virtual Machines with Linux distributions, such as Ubuntu or CentOS, natively support touch for file management in virtualized setups.[27] On mobile platforms, Android users can access touch through Termux, a terminal emulator that installs coreutils via its package manager, enabling Unix command execution on non-rooted devices.
Differences Across Systems
The GNU coreutils implementation of thetouch command, commonly used in Linux distributions, extends POSIX standards with options like --date for specifying timestamps in human-readable formats (e.g., ISO 8601) and --reference to copy timestamps from another file, while also supporting nanosecond precision via fractional seconds in timestamp arguments.[28] In comparison, BSD-based systems such as FreeBSD provide similar core functionality through options like -d for date specification and -r for referencing another file's timestamp, but omit --reference and --date equivalents in long form; they include a non-POSIX -A option to adjust timestamps by hours, minutes, or seconds, and lack a -f (force) flag present in some older variants.[29]
Ports to Windows, such as Cygwin's inclusion of GNU coreutils, aim for full POSIX emulation of touch, including advanced options like --date and nanosecond support, but timestamp handling on NTFS can deviate due to the filesystem's native 100-nanosecond resolution; pre-2020 Cygwin releases often rounded sub-second values, though updates since Windows 10 have improved native compatibility for precise Unix-style timestamps.[30]
The BusyBox implementation, designed for resource-constrained environments like embedded systems, offers a stripped-down touch applet supporting basic POSIX options such as -c (no-create), -d (date), -t (timestamp), and -r (reference), but excludes nanosecond precision and advanced adjustments, defaulting to simple file creation or modification time updates without verbose output or symbolic link handling.[31]
Filesystem constraints further influence touch behavior across systems: on FAT32 volumes common in Windows and cross-platform storage, modification timestamps lack Unix-level precision, limited to 2-second granularity, which can cause touch to snap times to even-second boundaries regardless of the underlying command implementation.[32]
As of 2025, macOS (based on Darwin) closely mirrors BSD touch options, including -d, -r, and -A, but integrates with APFS to enable nanosecond-precision timestamps for modification and change times; Apple-specific extensions ensure access times update conditionally based on the volume's APFS_FEATURE_STRICTATIME setting, allowing finer control over timestamp semantics than traditional BSD filesystems.[33]