Home > File & Directory Management > touch

touch: Change file access and modification times or create a file

The touch command is used to update the access and modification times of a file to the current time, or to create a new empty file if the file does not exist. The -c option, in particular, is useful for preventing the creation of new files when they don't exist, allowing you to manipulate only the timestamps of existing files.

Overview

The touch command updates file timestamps or creates an empty file if it doesn't exist. The -c or --no-create option prevents file creation when a file is absent, primarily used when you only want to modify the timestamps of existing files.

Key Features

  • Update file access and modification times
  • Create a new empty file if the file does not exist (default behavior)
  • Prevent creation if the file does not exist (-c option)

Key Options

Controlling Default Behavior

Specifying Time

Generated command:

Try combining the commands.

Description:

`touch` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Explore various scenarios using the touch command and the -c option.

Do not create if file does not exist, update timestamp if it does

touch -c test_file.txt

If test_file.txt does not exist, no action is taken. If it exists, its access and modification times are updated to the current time.

Update only the access time of an existing file (prevent creation)

touch -ac existing_file.log

If existing_file.log exists, only its access time is updated to the current time. If it does not exist, it is not created.

Set timestamp to a specific time (prevent creation)

touch -c -t 202312311030.00 report.txt

If report.txt exists, its timestamp will be set to December 31, 2023, 10:30 AM. If the file does not exist, it will not be created.

Set timestamp using the time of a reference file (prevent creation)

touch -c -r source.txt target.txt

The timestamp of target.txt will be set by referencing the timestamp of source.txt. If target.txt does not exist, it will not be created.

Tips & Precautions

The touch command can be useful in scripts for checking file existence or for triggering build systems by manipulating specific file timestamps.

Key Usage Tips

  • Use -c to perform specific actions after checking file existence in scripts.
  • Manage file dependencies in build systems like Makefiles (update target files when source files change).
  • Resetting log file timestamps to analyze logs for specific periods.
  • The -c option is essential when you need to change only the timestamp of an existing file without creating a new one.

Precautions

The touch command modifies only the metadata (timestamps) of a file, not its content. Executing touch on a non-existent file without the -c option will create an empty file. Therefore, it is advisable to always consider the -c option to prevent unintended file creation.


Same category commands