Skip to content

touch Command in Linux

Summary

The touch command in Linux is used to create new, empty files or update the access and modification times of existing files and directories.

Introduction

The touch command is a fundamental utility in Linux systems. While its primary function is to create empty files, it's more commonly used to quickly update the timestamps (access and modification times) of existing files without altering their content. This can be useful for various tasks like managing build processes, triggering events based on file modification, or simply marking files as recently accessed. It's a simple yet powerful command for managing file metadata.

Use case and Examples

Creating a new empty file

touch new_file.txt
This command creates an empty file named new_file.txt in the current directory. If the file already exists, its timestamp is updated.

Updating the timestamp of an existing file

touch existing_file.txt
This command updates the access and modification times of existing_file.txt to the current time. The file's content remains unchanged.

Creating multiple files at once

touch file1.txt file2.txt file3.txt
This command creates three new, empty files: file1.txt, file2.txt, and file3.txt.

Changing access time only

touch -a my_file.txt
This command updates only the access time of my_file.txt, leaving the modification time unchanged.

Changing modification time only

touch -m my_file.txt
This command updates only the modification time of my_file.txt, leaving the access time unchanged.

Setting specific timestamps using a reference file

touch -r reference_file.txt target_file.txt
This command sets the access and modification times of target_file.txt to the same values as reference_file.txt.

Setting a specific date and time

touch -t 202401011200 target_file.txt
This command sets the access and modification times of target_file.txt to January 1st, 2024, at 12:00 PM. The format for -t is [[CC]YY]MMDDhhmm[.ss].

Commonly used flags

Flag Description Example
-a Change only the access time. touch -a my_file.txt
-m Change only the modification time. touch -m my_file.txt
-r Use the times of a reference file. touch -r reference.txt target.txt
-t Use the specified time instead of the current time. The argument should be in the format [[CC]YY]MMDDhhmm[.ss]. touch -t 202312312359 file.txt
-c or --no-create Do not create any files. If the file does not exist, do nothing. touch -c non_existent_file.txt


Share on Share on

Comments