84

What's the point of the touch command? I know I can create empty files with it, but so is also the case with echo -n.

Otherwise, why would someone need to change the timestamps of a file? Unless to create the false impression about the age of a file, I don't see any other use, and this one is not a legitimate one (from my point of view).

17
  • 18
    instead of echo -n > filename, you can run the following: >filename Commented Jan 12, 2014 at 20:12
  • 78
    What are the illegitimate uses?
    – bmargulies
    Commented Jan 12, 2014 at 23:54
  • 11
    Unless to create the false impression about the age of a file. Not necessary false impression. What if you want to change the modification time? It can be useful in scripts. This script heavily depends on the touch command and it is very convenient and simple to have it like that.
    – VL-80
    Commented Jan 13, 2014 at 2:01
  • 7
    Consider what tar (or other de-archivers) do when they extract an archive. Generally they set the modification time of the file to the time from the archive, not the time the archive was extracted, and this is a desirable feature. Since it's legitimate for a user-mode program to create false timestamps there's not much argument why touch (or some other command-line program) shouldn't allow it based on a command-line argument. Learning C doesn't make you more legitimate than someone writing a sh script ;-) Commented Jan 13, 2014 at 2:14
  • 5
    In unix, there is no timestamp that describes the age of a file. That would be a creation timestamp and there is no such timestamp for files in unix. Commented Jan 13, 2014 at 2:21

15 Answers 15

98

One advantage of touch is that it can specify arbitrary timestamps, while echo -n will always result in the current time.

An example of a legitimate use is to update a timestamp of a source code file so a program like make will consider the source file newer than its compiled object and rebuild it.

Other uses are to create files that function solely based on their existence e.g. /etc/nologin, which disallows logins if it exists. I'd also argue that touch myfile is a simpler construct than echo -n >> myfile, as well as being shorter to type.

4
  • 19
    another common use: touch a file to a specific date, then "find / -newer /the/file" to find all files changed/created after it Commented Jan 13, 2014 at 9:47
  • @casey When I checked the documentation of echo -n I see that it says "do not output the trailing newline". So I do not see how can this create an empty file. Can you clarify please?
    – Geek
    Commented Jan 13, 2014 at 16:03
  • 4
    @Geek echo -n will output an empty string, and by itself does nothing. Redirecting its output via >> causes the empty output to be appended to a file. The redirection will cause the file to be created if the file does not exist.
    – casey
    Commented Jan 13, 2014 at 16:07
  • 6
    That doesn't work: opening an existing file for output, but not writing to it, does not change the mtime (on my system, anyway). Even if it did, you don't need and shouldn't use echo -n for a command that does nothing. echo -n may output the string "-n" under some shells. If you really need a command that does nothing, : or true are a better option, but >> myfile by itself is also a perfectly valid way of creating the file if it doesn't exist. All this, of course, supports your answer that you should just use "touch".
    – hvd
    Commented Jan 13, 2014 at 17:56
39

The underlying system call (utime) is important for various utilities like tar to be able to set the timestamps of a newly copied (un-tarred) file. Some backup utilities can also be optioned to reset the last-accesstime of files that they have copied.

One legitimate use of touch is to create a file with a particular timestamp. Such a "reference" file can then be used by commands like find. For example, to find all files more recently modified than Nov 1, 2013 (ie 2013/11/01)"

touch -amt 201311010000 myref
find . -type f -newer myref -exec ls -ld {} +
3
  • How to calculate that 201311010000 means Nov1,2013? Is there a utility which will tell me this? In other words how do I determine the input to touch?
    – Geek
    Commented Jan 13, 2014 at 16:26
  • 4
    @Geek By looking at the number and noting that the first part, 20131101, can be broken down into 2013-11-01, or November 1, 2013. You can then assume that the 0000 part indicates a specific time of day, in this case 00 hours, 00 minutes. Or you could just look at the man page for touch, which tells you exactly what the format is (see -t).
    – JAB
    Commented Jan 13, 2014 at 16:32
  • @Geek The manpages are your friend :-)
    – JRFerguson
    Commented Jan 13, 2014 at 16:34
38

The touch command's primary purpose is manipulating the timestamps of files, and for creating files.

Examples

1. creating files

$ ls -l
total 0

$ touch file{1..3}

$ ls -l
total 0
-rw-rw-r--. 1 saml saml 0 Jan 12 13:33 file1
-rw-rw-r--. 1 saml saml 0 Jan 12 13:33 file2
-rw-rw-r--. 1 saml saml 0 Jan 12 13:33 file3

NOTE: The total 0 output from ls -l is correct. This implementation of ls shows the number of blocks being used by the files when they're listed. You can assure yourself of this fact by adding the -s switch to ls. This will list the blocks in use by each file. Here I've added 2 characters to file1 & file2.

Example

$ ls -ls
total 8
4 -rw-rw-r--. 1 saml saml 3 Jan 13 12:07 file1
4 -rw-rw-r--. 1 saml saml 3 Jan 13 12:09 file2
0 -rw-rw-r--. 1 saml saml 0 Jan 13 12:05 file3

2. time/date info of a file - stat command

$ stat file1
  File: ‘file1’
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: fd02h/64770d    Inode: 11403667    Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/    saml)   Gid: ( 1000/    saml)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2014-01-12 13:33:38.279456149 -0500
Modify: 2014-01-12 13:33:38.279456149 -0500
Change: 2014-01-12 13:33:38.279456149 -0500
 Birth: -

We can use touch to manipulate the various timestamps on a given file.

3. excerpt from touch man page

   -a     change only the access time
   -m     change only the modification time
   -t STAMP
          use [[CC]YY]MMDDhhmm[.ss] instead of current time

4. manipulating access time

$ touch -a -t200001010000 file1

$ stat file1
  File: ‘file1’
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: fd02h/64770d    Inode: 11403667    Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/    saml)   Gid: ( 1000/    saml)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2000-01-01 00:00:00.000000000 -0500
Modify: 2014-01-12 13:33:38.279456149 -0500
Change: 2014-01-12 13:38:52.023434696 -0500
 Birth: -

5. manipulate modify time

$ touch -m -t200001010000 file1

$ stat file1
  File: ‘file1’
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: fd02h/64770d    Inode: 11403667    Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/    saml)   Gid: ( 1000/    saml)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2000-01-01 00:00:00.000000000 -0500
Modify: 2000-01-01 00:00:00.000000000 -0500
Change: 2014-01-12 13:39:31.060432026 -0500
 Birth: -

You might be wondering about the change time (ctime). That cannot be manipulated using touch. That tracks the time any of the meta data was touched on the file. See this U&L Q&A for more details, titled: What can you do to a file without triggering the "Change" Timestamp?.

6
  • 1
    @sim: my question implies that I know that touch is for changing timestamps. I just wanted to know why would an honest user want that. If it were not for the ctime part of your answer, I'd had given you a -1. Commented Jan 12, 2014 at 19:46
  • 16
    @QuoraFea - my answer is for your benefit and ever user that ever comes across it in the future. Please don't assume that an answer is purely for your sake and I'm sorry if I offended you in any way, it was not my intent, I was merely attempting to explain the underpinnings of how time works.
    – slm
    Commented Jan 12, 2014 at 20:00
  • @sim: I'm not offended, just thought the answer was not going in the right direction. Anyway, thanks for this answer. Commented Jan 12, 2014 at 20:36
  • @QuoraFea - you're quite welcome, and thank you for your Q. They're appreciated!
    – slm
    Commented Jan 12, 2014 at 20:36
  • 1
    @Geek - try the commands. That is correct output from ls -l in a directory where the files have 0 size, and nothing else exists yet. As soon as you give one of the files size then the total will show up w/ the amount of blocks in use by the files. See my updates if you're unsure, I've added an example.
    – slm
    Commented Jan 13, 2014 at 17:12
20

Apart from the other two very good answers you got, yet another use is, in your words, to

create the false impression about the age of a file

for example for use in backup schemes. You might want to not update a backup with a newer one since they're identical, or since the changes are irrelevant compared to the expense of updating a backup on, say, a slow line to a remote host. To achieve this, you have the simple option of marking the backup file with a newer timestamp, not faking but declaring that the validity timestamp of that file is now a different one.

The impression about the age of the file is now indeed false, but its meaning is real and legitimate.

20

One of the most common uses of touch is -- or at least used to be -- to trigger a rebuild of code.

The usual build tools -- make and its derivitives -- try to save work by not recompiling/rebuilding files unless one of the files which went into creating them has changed -- for example, if a .o file is more recent than the .c source, it's usually safe to presume that the C source hasn't been changed since being compiled to produce that object file.

But there are times when you want to force something to be rebuilt. You could make a needless modification to one of its source files, but that risks accidentally damaging something. Instead, you could simply touch the file, making it look new without any risk of altering its content -- and that would be enough to convince make that it was time to rebuild everything that depends on that file.

There are other uses, but historically that was the big one.

3
  • While it seams a good idea to change a file to cause a rebuild I would argue against it. Some source code revision systems can get confused about a changed file. So touch is as bad as a manual change. To cause a rebuild I suggest deleting the output files .o of the source in question.
    – harper
    Commented Jan 13, 2014 at 6:46
  • 1
    Manual changes and removal of the .o files both require more time and typing, and a manual change is much more error-prone. And we're only talking about modifying the timestamp on a working copy -- if edits are made afterward, the file will correctly reflect the change timestamp. And not all version control systems are confused by a timestamp.
    – David
    Commented Jan 13, 2014 at 14:18
  • 1
    As David said. This really was standard Unix practice not that long ago, and still remains standard practice for developers working outside IDEs.
    – keshlam
    Commented Jan 13, 2014 at 15:24
12

I've worked with at least one web framework (can't remember which) that in development mode watched the source code files for changes and reloaded the application when that happened.

Of course sometimes you wanted it to reload after changing something it wasn't watching, in which case touching its main configuration file did the trick.

So, in the general case, whenever you want to start a process triggered by changes to a file, without actually changing the file.

1
  • 4
    This is actually the case with mod_wsgi and apache; you can reload, eg, a django web app just by touching the wsgi file.
    – sapi
    Commented Jan 13, 2014 at 7:59
11

Legitimate use of touch:

  • Update the timestamp of image files (GIF/JPG/etc) to the time they were taken. Not all renderers read or heed the EXIF information.
  • Keep the c/m-time when mass updating a set of files where the timestamp is important for the bundle of files.
  • Set the time of a batch (i.e. CSV) file if you need to do another import after a failure, and the import program depends on the time stamp (leave that discussion to another topic :-) )
  • Archival purposes, i.e. have backups in folders based on year, then setting the time on these folders to Jan 1 YYYY for easy sorting
  • Update a programs lock file to signify that it has been reloaded.
  • Setup a "pollfile" which your application monitors. Perform actions when the pollfile date is changed.
7

One use is to correct the timestamp of a file that was improperly set.

For example, most any way you copy a file (and for some ways that you might move a file) results in the new file having a timestamp of the current time, rather than the timestamp of the original file.

Usually, this is not what is desired. Touch can "fix" that.

Another use is to reflect a file modification that was undone by restoring the file timestamp to what it was before the "edit ... undo-edit" operations.

1
  • 2
    Indeed. Trough time I've found alias cp='cp --preserve=timestamps' is more suited for me in PC land …
    – Runium
    Commented Jan 13, 2014 at 5:24
5

An important difference vs. things like echo (or the even better > file as mentioned by others) is that touch will not smash the contents. > file will empty a file. touch will not. Instead of thinking of tricks to avoid content damage, just use touch! It will do less work in the kernel anyway, because it will work only with the attributes of the file without wasting time actually preparing for an open and then performing a close.

Touch can probably alter the timestamp even if the file is currently under a mandatory or advisory lock, or an exclusive open. Hmmm, have never tested that or read up about it...

2
  • 2
    >> will append instead of overwriting Commented Jan 13, 2014 at 2:12
  • I considered mentioning that, but it's getting even more into side-effect territory. You'd also have to mention the fact that it would throw an error if the file happened to be exclusive-opened already, etc etc etc. A problem that could apply through the use of > too. I guess my secondary point - beyond the primary one that it's marginally quicker to merely touch the file's stats - is that it's a good idea to write code that tells it straight, instead of beating around the bush.
    – user56373
    Commented Jan 20, 2014 at 5:55
4

Here is one - I use a software program called SageTV to record TV shows - these are often recorded in MPEG-2 which isn't a very efficient codec, it also isn't iPad/iPhone friendly. So I convert the files to .mp4 files. But when playing back the files SageTV expects the timestamp of the file to be when the TV show started - if not it screws up the timeline of the show so that it isn't easy to FF or REW. Therefore I use touch to reset the timestamp of the .mp4 file to be the same as the orignal file.
Is that legit?

2

Often you may have a process that changes from userid, like from root -> something else. Touch can give you the chance to create a file in a place that only root can touch before the application starts logging to it as the other user.

2
  • That is not a use of touch that is unachievable by "echo" -- see author's original question Commented Jan 13, 2014 at 1:27
  • Echo involves opening a stream and such. Touch could be hyper optimized by working directly with inodes. PERFORMANCE FTW!
    – user56560
    Commented Feb 17, 2017 at 6:10
2

At work we have an archive of digital maps going back 15+ years. These old maps are saved in a variety of formats such as PostScript, EMF, PRN, hpgl2, pdf, etc. that most programs don't understand. Or you need a dozen different programs to see them all.

To facilitate easy searching and browsing of all these different formats we create jpeg versions of the maps, and then use touch to make the jpeg file match the original source file timestamp -- often years after the original was made.

Now we can use a single program such as Picasa to see the whole library and trivially locate certain date ranges. Without touch we'd have to add date metadata for every single image, probably manually, and then search on those strings when looking for a specific date range.

1

I have not used it for this purpose yet, but I have a script that reads the files and their dates from a directory and reads them for use on a web page. If I have to edit one, it will change its date. I have considered touching them to reset their order.

1

Some init-scripts compare the timestamp of a config-file with their own pid-file. The outcome decides whether to reload the running service or not.

If there is a situation where you do not want to change the config but want to force reloading, touch helps you here.

0

I have a cron job that gets the changes from a database that have occurred between the last run of the job, and the current run. It produces an XML file of the changes which are then processed into a different database. It gets the last run time from the time-stamp on the XML output file.*

If anything goes awry in the processing of the XML file I might want to repeat the run from the original date not from the date referred to on the time-stamp of the new XML file.

The simplest way to do this, rather than editing the scripts that are called etc. is to touch the XML file and force the time-stamp to be the date I require.

Also if I start afresh (with no previous XML output file) I can simply simulate its existence using touch.

[*] Before someone points it out - I realize the time the job starts and the writing of the XML file leaves a time gap of a few minutes where DB changes could occur. The job runs at a time when DB changes are extremely unlikely. That's my excuse and I'm sticking to it :-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .