Updating Modification Times with touch
We have used the touch command a few times to create empty files. For a previously nonexistent file, here are equivalent ways of doing the same thing:
cat /dev/null > some-file Copy empty file to some-file printf "" > some-file Print empty string to some-file cat /dev/null >> some-file Append empty file to some-file printf "" >> some-file Append empty string to some-file touch some-file Update timestamp of some-file
However, if the file exists already, the first two truncate the
file to a zero size, whereas the last three effectively do nothing more
than update its last-modification time. Clearly, the safe way to do that
job is with touch, because typing
>
when you meant >>
would inadvertently destroy the file
contents.
touch is sometimes used in shell scripts to create empty files: their existence and possibly their timestamps, but not their contents, are significant. A common example is a lock file to indicate that a program is already running, and that a second instance should not be started. Another use is to record a file timestamp for later comparison with other files.
By default, or with the -m
option, touch changes a file's last-modification time,
but you can use the -a
option to change the last-access
time instead. The time used defaults to the current time, but you can
override that with the -t
option, which takes a
following argument of the form [[CC]YY]MMDDhhmm[.SS]
, where the century, year within the century, and seconds are optional, ...
Get Classic Shell Scripting now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.