I am aware that the touch
command is used to update the date of last modification on a file. It is also used to create a new file if requested file does not exist on file system.
Since touch (as it's name implies), should just update last mod date, why does it also try to create a new file?
Is it just a check written in the touch's code, or is it something else that causes a file to be created?
Best Answer
touch
creates a new, empty file if the file doesn't exist because that's what it was designed to do. The utility has to contain code to handle that case specifically. The utility appeared in Unix V7; its manual described it thus:(I don't know what
touch
did if the file was empty. The underlying system call came later.)I don't know for sure why
touch
was designed to make the file exist, but I suspect it's because ofmake
. Why would you want to set a file's modification time to the current time? There are cases where it could be useful to set the modification time to a particular time, but that ability came later, the originaltouch
could only set the modification time to the current time. A reason to do that is to re-run amake
rule that depends on the file.That is, suppose you have a file
foo
, and a makefile that declares a command to generatebar
fromfoo
. When you typemake bar
, the command is executed andbar
is created. Ifbar
exists and is newer thanfoo
,make bar
does nothing, becausemake
assumes thatbar
has already been generated. However, ifbar
is older thanfoo
, make thinks thatbar
is not up-to-date and needs to be regenerated.But what if the rules to generate
bar
have changed? Then you have two options:rm bar; make bar
touch foo; make bar
You would need
foo
to exist in order to generatebar
, otherwise the command would typically not work.The “touch” terminology was also present in the
make
utility:make -t bar
would only pretend to run the commands, that is, it would set the modification time ofbar
to the current time without actually running the command to generatebar
(you would do this if you thought that the changes tofoo
shouldn't affectbar
). Thetouch
utility was therefore a standalone version of themake -t
feature.