Shell – When creating an empty file, why might one prefer ‘touch file’ over ‘: >> file’

filesshelltouch

Never realized that you could do this until just now:

: >> file

It seems to be functionally similar to:

touch file

Is there a reason why most resources seem to prefer touch over this shell builtin?

Best Answer

You don't even need to use :; you can just > file (at least in bash; other shells may behave differently).

In practical terms, there is no real difference here (though the minuscule overhead of calling out to /bin/touch is a thing).

touch, however, can also be used to modify the timestamps on a file that already exists without changing or erasing the contents; further, > file will blow out any file that already exists. This can be worked around by instead using >> file.

One other difference with touch is that you can have it create (or update the timestamp on) multiple files at once (e.g. touch foo bar baz quux) with a more succinct syntax than with redirection, where each file needs its own redirection (e.g. >foo >bar >baz >quux).

Using touch:

$ touch foo; stat -x foo; sleep 2; touch foo; stat -x foo
  File: "foo"
  Size: 0            FileType: Regular File
  Mode: (0644/-rw-r--r--)         Uid: (991148597/redacted)  Gid: (1640268302/redacted)
Device: 1,5   Inode: 8597208698    Links: 1
Access: Fri May 25 10:55:19 2018
Modify: Fri May 25 10:55:19 2018
Change: Fri May 25 10:55:19 2018
  File: "foo"
  Size: 0            FileType: Regular File
  Mode: (0644/-rw-r--r--)         Uid: (991148597/redacted)  Gid: (1640268302/redacted)
Device: 1,5   Inode: 8597208698    Links: 1
Access: Fri May 25 10:55:21 2018
Modify: Fri May 25 10:55:21 2018
Change: Fri May 25 10:55:21 2018

Using redirection:

$ > foo; stat -x foo; sleep 2; >> foo; stat -x foo
  File: "foo"
  Size: 0            FileType: Regular File
  Mode: (0644/-rw-r--r--)         Uid: (991148597/redacted)  Gid: (1640268302/redacted)
Device: 1,5   Inode: 8597208698    Links: 1
Access: Fri May 25 10:55:21 2018
Modify: Fri May 25 10:56:25 2018
Change: Fri May 25 10:56:25 2018
  File: "foo"
  Size: 0            FileType: Regular File
  Mode: (0644/-rw-r--r--)         Uid: (991148597/redacted)  Gid: (1640268302/redacted)
Device: 1,5   Inode: 8597208698    Links: 1
Access: Fri May 25 10:55:21 2018
Modify: Fri May 25 10:56:25 2018
Change: Fri May 25 10:56:25 2018
Related Question