touch ‐ #files - five4nets/Linux-Knowledgebase GitHub Wiki

Linux touch Command Tutorial

The touch command in Linux is a simple yet powerful utility used primarily to create empty files or update the timestamps of existing files. This tutorial covers the basics of the touch command, its syntax, options, and practical examples.

Table of Contents

Introduction

The touch command is commonly used to:

  • Create empty files.
  • Update the access and modification timestamps of existing files.
  • Set specific timestamps for files.

It is a standard command available in most Linux distributions and Unix-like systems.

Syntax

touch [options] file...
  • file: The name of the file(s) to create or update.
  • options: Flags that modify the command's behavior.

Common Options

Option Description
-a Update only the access time.
-m Update only the modification time.
-c Do not create a file if it does not exist.
-d Set a specific timestamp using a date string.
-t Set a specific timestamp using a formatted time (e.g., YYYYMMDDhhmm).
-r Use the timestamp of a reference file.
--help Display the help manual for touch.

Examples

Creating a Single File

To create an empty file named example.txt:

touch example.txt

This creates example.txt if it doesn't exist. If it already exists, it updates the file's access and modification timestamps to the current time.

Creating Multiple Files

To create multiple files at once:

touch file1.txt file2.txt file3.txt

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

Updating File Timestamps

To update the timestamps of an existing file to the current time:

touch existing_file.txt

This updates both the access and modification times of existing_file.txt.

Setting Specific Timestamps

To set a specific timestamp for a file using the -t option:

touch -t 202306151230 file.txt

This sets the timestamp of file.txt to June 15, 2023, 12:30 PM.

Alternatively, use the -d option with a date string:

touch -d "2023-06-15 12:30" file.txt

This achieves the same result as the previous example.

Using a Reference File

To set the timestamp of one file to match another file's timestamp:

touch -r reference_file.txt target_file.txt

This updates target_file.txt to have the same timestamps as reference_file.txt.

Creating a File Without Changing Timestamps

To update a file's timestamp only if it exists, without creating it if it doesn't:

touch -c nonexistent_file.txt

No file is created if nonexistent_file.txt does not exist.

References