Andy Lester

Technology, careers, life and being happy

The touch command does more than just create empty files

| 6 Comments

Beginners to Unix/Linux learn about the touch command as a way to create an empty file.

$ ls -l /tmp/foo
ls: /tmp/foo: No such file or directory

$ touch /tmp/foo
$ ls -l /tmp/foo
-rw-r--r--  1 andy  wheel  0 Jul 10 11:56 /tmp/foo

But there’s more to it than that.  The main job of touch is to modify the timestamps on a file.  Creation of a file is almost a side effect.

The -t argument to touch lets me specify a date and time to set on the file.

$ ls -l /tmp/foo
ls: /tmp/foo: No such file or directory

$ touch -t 201107010930 /tmp/foo
$ ls -l /tmp/foo
-rw-r--r--  1 andy  wheel  0 Jul  1 09:30 /tmp/foo

If I don’t specify a date and time, then the current date and time are used.

$ ls -l /tmp/foo
-rw-r--r--  1 andy  wheel  0 Jul  1 09:30 /tmp/foo

$ touch /tmp/foo
$ ls -l /tmp/foo
-rw-r--r--  1 andy  wheel  0 Jul 10 11:58 /tmp/foo

You can also use the timestamp from another file and apply it to another file by using the -r switch.

$ ls -l /tmp/someotherfile
-rw-r--r--  1 andy  wheel  0 Aug 12  2005 /tmp/someotherfile

$ touch -r /tmp/someotherfile /tmp/foo /tmp/foo2 /tmp/foo3
$ ls -al /tmp/
-rw-r--r--  1 andy  wheel  0 Aug 12  2005 /tmp/foo
-rw-r--r--  1 andy  wheel  0 Aug 12  2005 /tmp/foo2
-rw-r--r--  1 andy  wheel  0 Aug 12  2005 /tmp/foo3
-rw-r--r--  1 andy  wheel  0 Aug 12  2005 /tmp/someotherfile

man touch will give you all the details.

6 Comments

  1. Great post, I don’t often have to play with timestamps but it’s nice to know that it’s easy to do.

    /Stu

  2. Pingback: touch 命令 | 笨兔兔

  3. Same as Stu.

    It makes sense. Like “last time I touched this file was…”

  4. Pingback: Links 19/7/2011: Why GNU/Linux Feels Better Than Mac OS X, Howard County Library Uses Ubuntu | Techrights

  5. A million thanks for posting this infotramion.

Leave a Reply

Required fields are marked *.