Working with files

Linux commands: touch

Learn how the Linux touch command creates a new empty file, and how running it on a file that already exists just updates that file's modification timestamp.

You can create an empty file using the touch command:

touch apple.txt

Check it with ls -l:

-rw-r--r--  1 flavio  staff  0 Sep  8 18:22 apple.txt

The 0 is the size in bytes. The file exists, and it’s empty.

That’s how most people use touch, but creating files is a side effect. The real job of touch is to update a file’s timestamps: the time it was last modified and the time it was last accessed. When the file doesn’t exist, there’s nothing to update, so touch creates it first.

Let’s see the real job. Put some text in the file, wait a minute, then touch it again:

echo "hello" > apple.txt
ls -l apple.txt
touch apple.txt
ls -l apple.txt
-rw-r--r--  1 flavio  staff  6 Sep  8 18:22 apple.txt
-rw-r--r--  1 flavio  staff  6 Sep  8 18:23 apple.txt

The time moved forward. The size is still 6, and cat apple.txt still prints hello. touch never opens the file for writing, so it never erases anything. That’s what makes it safe to run on files you care about.

Why would you want to bump a timestamp? Build tools like make compare modification times to decide what needs rebuilding. Touching a file tells them “this changed, rebuild it”, without editing anything.

If you want to update a file only when it already exists, add -c:

touch -c optional.txt

With -c, a missing file is not created. The command finishes silently and nothing appears on disk. Without -c, you’d get a new empty optional.txt.

You can also copy the timestamps from another file with -r:

touch -r source.txt destination.txt

Now destination.txt has the same times as source.txt. There’s also a -t option to type a date by hand, but the format is easy to get wrong, so I reach for -r when I can.

One thing touch does not do is control permissions or content. The new file gets the default permissions of your session (we’ll see umask later in the course). If you need content in the file, use redirection instead:

echo "hello" > greeting.txt

The most common failure is a folder that doesn’t exist:

touch drafts/apple.txt
touch: drafts/apple.txt: No such file or directory

touch creates files, not folders. Run mkdir drafts first, then touch the file.

Try this on your own project: pick a file, note its time in ls -l, run touch on it, and confirm the content is untouched while the time changed.

Lesson completed