Clobbering a File on Purpose

Problem

You like to have noclobber set, but every once in a while you do want to clobber a file when you redirect output. Can you override bash’s good intentions, just once?

Solution

Use >| to redirect your output. Even if noclobber is set, bash ignores its setting and overwrites the file.

Consider this example:

$ echo something > my.file
$ set -o noclobber
$ echo some more >| my.file
$ cat my.file
some more
$ echo once again > my.file
bash: my.file: cannot overwrite existing file
$

Notice that no error message occurs on the second echo, but on the third echo, when we are no longer using the vertical bar but just the plain > character by itself, the shell warns us and does not clobber the existing file.

Discussion

Using noclobber does not take the place of file permissions. If you don’t have write permission in the directory, you won’t be able to create the file, whether or not you use the >| construct. Similarly, you must have write permission on the file itself to overwrite that existing file, whether or not you use the >|.

So why the vertical bar? Perhaps because the exclamation point was already used by bash for other things, and the vertical bar is close, visually, to the exclamation point. But why would ! be the appropriate symbol? Well, for emphasis of course. Its use in English (with the imperative mood) fits that sense of “do it anyway!” when telling bash to overwrite the file if need be. Secondly, the vi (and ex) editors use the ! in that same meaning ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.