Site icon DesignLinux

Touch Command in Linux

Linux Touch Command

The touch command is used to create a new empty files and update the timestamps of existing files and directories. In this tutorial, we will cover how to use the touch command with examples.

Linux Files Timestamps

At first, we will see the file timestamps in Linux. There are three timestamps of a Linux file:

Use the stat command to show the file status with timestamps:

stat file_name

Make sure at the time of creating a new file requires write permission on the parent directory.

How to Use Touch Command

When you run the touch command without any options and if the given file name does not exist then it will create a new file. If the file already exists touch will change the file last access and modification times to the current time.

For example, if the file filename doesn’t exist the following command will create it otherwise, it will change its timestamps:

touch filename

You can create or modify multiple files in a single touch command. Just specify the file names as arguments:

touch filename1 filename2 filename3

To prevent from creating a new file use the -c (--no-create) option with touch command.

For instance, if the filename is exists then it will change the file timestamps otherwise it will not do anything:

touch -c filename

Changing only access or modification times

If there is no option is passed with the touch command, it will update the file last access and modification time with the current time. To change only any one of them you can use -a and -m option with touch command:

Change only the access time

Use the -a option to change only the file’s access time:

touch -a filename

Change only the modify time

Use the -m option to change the file’s modify time:

touch -m filename

When changing the modify time, the change time will be also updated.

Setting specific timestamps

Using the touch command you can update or create a file with a specific time instead of the current time. Use the -d (--date=) option to specify a date string.

For example, to change the last access and modification time of filename1 to 18 October 2020 11:02 you would use the following command:

touch -d '18 October 2020 11:02' filename1

You should enclosed the date string with single quotes. You can also provide only the date and it will automatically changes the year to the current one:

touch -d '12 October' filename1

To specify the timestamp to use it instead of the current time. The timestamp argument needs to be in the following format:

use [[CC]YY]MMDDhhmm[.ss]

For example, using below command you can set the last access and modification time for filename1 to 1 October 10:02 of the current year.

touch -t 10011002 filename1

Conclusion

You learned how to use the touch command to creating a new file or update timestamp of existing files.

If you have any questions or feedback, feel free leave a comment below.

Exit mobile version