In this post we focus on How to use touch command in Linux?
touch command is used to update the timestamp of a file or directory. Timestamp means that it will update the access and modification times of the file or directory specified.
Example of How to use touch command in Linux?
Suppose an existing file “xyz.txt”. If we do the long list of this file using ls -l it will show the last access time. Next, we use touch command and long list it again. Now the access time gets updated.
Note: If the specified file does not exist then a new file with that name is created. Thus, we can also touch command to create new files.
touch can also be used to update the timestamp of directories. But it will not create a new directory if it does not already exist.
Options used with touch command
1. To Update only the ACCESS time
-a: option updates only the access time and not the modification time
2. Do not create a new file
-c: if you do not want touch to create a new file if it does not already exist then use this option. For example:
Here we use -c option. Thus the non-existing file f3 is not created.
3. Specify time of your own choice
-d: if you want to assign a timestamp of your own choice then use this option. By default, touch assign current time. But what if you want a time of your own choice. For example:
Now we use -d option to assign a date and time of our own choice.
Note: -d option allows different formats to specify the new date and time.
4. To Update only the Modification time
-m: option updates only the modification time and not the access time
5. Assign time of another file
-r: if you want to assign the timestamp of another file to any other file then use this option. By default touch assign current time. But what if you want the time stamp of two files to be same. For example:
There are two files f1 and f2 having different timestamp. Next, the timestamp of f2 is made similar to f1 by using the -r option. After -r specify the file whose timestamp is to be assigned and then the file to whom it is to be assigned.
6. Specify time of your own choice
-t: if you want to assign a timestamp of your own choice then use this option. By default touch assign current time. But what if you want a time of your own choice. The format of using this option is:
Everything within [ ] brackets is optional.
Note: The format of -t option is fixed which must be followed.
Some Useful Questions
Q1. Write the command to modify the access time of a directory without actually accessing it.
Q2. Update the timestamp of a file F1 by next 7 days
Q3. Assign the following timestamp to a file
18 Jan, 23:11