Touch Command in Linux with Examples

Touch Command in Linux with Examples

The touch command is used to change the timestamp of a file. If the file is not available at the location, it creates an empty file with zero byte size.

In this article, we will explore some examples of touch commands in Linux. All the commands have been executed in RHEL 9.

Syntax

The syntax of the command is as follows:

touch <options> <file or directory name>

Examples of Touch Command in Linux

Create an empty file

As we have said in the intro, if a file is not located in the directory it creates an empty file. Let’s say, our file is sample.txt. Execute the following command on the terminal.

touch sample.txt

Create multiple files

You can create multiple text files with the touch command. The command is as follows:

touch <file 1> <file 2> <file 3>

Suppose, we want to create files sample1.txt, sample2.txt, and sample3.txt. The command should look like this.

touch sample1.txt sample2.txt sample3.txt

We can create such multiple files with the help of the following command.

touch <filename{<start>..<finish>}>

Suppose we want to create ten files sample1.txt, sample2.txt, sample3.txt, sample4.txt … . sample10.txt. Run the command as follows:

touch sample{1..10}.txt

Change the timestamp of a file

We have already created the empty file. Let’s change its time stamp. Execute the following command on the terminal.

touch sample.txt

As you can see from the below screenshot, the time stamp has been changed from 11:10 to 11:14.

Set specific timestamp

If you want to set a specific time stamp of a file, the command has the following syntax.

touch -t <timestamp> <filename>

The timestamp has the following pattern.

[[CC]YY]MMDDhhmm[.ss]

Where

  • CC denotes the first two digits of the year
  • YY denotes the last two digits of the year
  • MM denotes month
  • DD denotes day
  • Hh denotes hour
  • Mm denotes minute
  • Ss denotes second

The parameters in square brackets are optional.

Suppose to change the timestamp of a file sample1.txt to Ist January 1999 midnight, the command is as follows.

touch -t 199901010000 sample1.txt

Set timestamp using date string

You can set the timestamp of a file using the date string as follows.

touch -d <string> <filename>

Suppose you want to set the time stamp of a file sample1.txt as March 04, 2001, the command shall be written as follows:

touch -d '4 Mar 2001 00:00' sample1.txt

Change access time

You can change the access with the help of -a option. Suppose you want to change the access time of sample1.txt, execute the below command.

touch -a sample1.txt

Change modification time

You can change the modification time of a file using -m option. Suppose you want to change the modification time of sample1.txt, the command should be executed as follows.

touch -m sample1.txt

Conclusion

Thank you for reading my article. Have a good day!