Creating files with "touch"

Ben Sinclair - Nov 11 '19 - - Dev Community

The act of creation

touch is often put forward as the command to create a file. What's wrong with that? Let's start with the manual page1.

touch -- change file access and modification times
Enter fullscreen mode Exit fullscreen mode

It's a command that lets you update a file's timestamps without loading the file. So it's quick - you don't need to open and save a document manually. And it's useful in a few cases that new users probably don't care about. If your system is set to delete logs over a certain age, you can touch one you want to keep.

touch has the side-effect of creating an empty file if it doesn't already exist; that's not its purpose. It's one way of doing it, but you can accomplish the same thing many other ways. You can redirect nothing to a file, for example:

touch this
> that # then hit ctrl-c if you're using zsh
echo > the-other
cp /dev/null yet-another
Enter fullscreen mode Exit fullscreen mode

And these will all do mostly the same thing2

But you have to figure touch is more straight-forward, right? It's one command, with no redirection or funny special characters to remember!

Sure. The problem with touch being taught as a way to create files isn't because it's a bad way of doing it, it's because you don't need to create files.

Say what?

When was the last time you were using a text editor and said to yourself, "Damn it, I forgot to create this file first, how can I save my work?" That's right, never.

There are a very, very limited number of times you - as a learning user - might want to create an empty file. Maybe you use .gitkeep to save empty directories to git. You should probably stop doing that. Maybe you want to add a .hushlogin to your home directory? You probably didn't know that was an option. Maybe you want to check whether you really have write-permission to this mounted directory? Ok, sure.

But no, people rarely create empty files. If anything, you'll be creating files from templates, which is probably handled by your editor or IDE anyway.

Why am I bringing this up? Because touch appears near the top of lists of commands suggested to command-line newbies all the time.

Here's the lesson: you don't need to waste time learning something that seems so oddly-named. YAGNI.

Spare your brain for something else.

--
If you have any practical use cases for creating empty files, or another reason you can think of for this to be a useful command for beginners, let me know in the comments!


  1. There's even a tl;dr

  2. echo > the-other will result in a file containing a newline, whereas the others will result in an empty (0-byte) file. 

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player