Touch a file in Linux

chraebsli@programming.dev to Programmer Humor@programming.dev – 1166 points –
94

You are viewing a single comment

The intended use of touch is to update the timestamp right?

Yeah. It could just as well have issued a file not found error when you try to touch a nonexistent file. And we would be none the wiser about what we're missing in the world.

“Do one thing and do it very well” is the UNIX philosophy after all; if you’re 99% likely to just create that missing file after you get a file not found error, why should touch waste your time?

Because now touch does two things.

Without touch, we could "just" use the shell to create files.

: > foo.txt

Touch does one thing from a “contract” perspective:

Ensure the timestamp of is

with this logic, any command that moves, copies or opens a file should just create a new file if it doesn't exist

and now you're just creating new files without realising just because of a typo

But this directly goes against that philosophy, since now instead of changing timestamps it's also creating files

You can pass -c to not create a file, but it does go against the philosophy that it creates them by default instead of that being an option

EDIT: Looking closer into the code, it would appear to maybe be an efficiency thing based on underlying system calls

Without that check, touch just opens a file for writing, with no other filesystem check, and closes it

With that check, touch first checks if the file exists, and then if so opens the file for writing