Touch command is commonly used to create an empty file in Linux. It can be also used to change file timestamps.
In this tutorial, we learn about touch command in Linux with useful examples.
Linux Touch command
The touch command is used to update the access and modification time of a file.
touch [OPTION] FILE
Without any option, it creates an empty file assuming the file doesn’t exist. If the file exists it change the timestamp. Touch cant open, save or close a file. You can use any text editor such as vi, vim, nano, or cat command to open the file created by the touch command.
Let’s go through how to use the touch command in Linux with examples.
1. Create an empty file
The following command creates a file named ‘example1.txt’.
This file example1.txt won’t have any contents. To confirm you can open with cat command (ie cat example1.txt).
To create multiple empty files, type,
touch example2.txt example3.txt
Remember If the file or directory already exists touch will update its access and modification time to the current time.
2. Change file access and modification time
To change the file access and modification time on an existing file to current time run the following command:
From the output, you can see that both access and modification time changed for the file.
To change only the access time of an existing file, use the -a option:
touch -a example2.txt
Similarly to change only the modification time of an existing file, type:
touch -m example3.txt
3. Set Specific Access and modification time
To set a specific date/time for the access and modification timestamps use -t option.
touch -t YYYYDDHHMM.SS filename
For example to change access and modification date/time of file named jmeter.log to 3rd Jan 2020, 3 PM, type:
touch -t 202001011500 jmeter.log
Alternatively, you can also use
-d option to change access/modification timestamps of a file to a specific date:
touch -d ‘01-October-2021’ example3.txt
-d options you can create a file with a specified time.
4. Use the timestamp of another file
You can reference a file and use the same timestamp
touch -r example2.txt example3.txt
Here example3.txt will get the same timestamp as of example2.txt.
5. Force not to create any files
Touch creates a new file if it doesn’t exist. To force touch not to create a file use the -c option.
touch -c fileName
In this tutorial, we learned about touch command in Linux with useful examples. You can get more information from touch man pages.