Keeping Files Safe from Accidental Overwriting
Problem
You don’t want to delete the contents of a file by mistake. It can be too easy to mistype a filename and find that you’ve redirected output into a file that you meant to save.
Solution
Tell the shell to be more careful, as follows:
$ set -o noclobber $
If you decide you don’t want to be so careful after all, then turn the option off:
$ set +o noclobber $
Discussion
The noclobber option tells bash not to overwrite any
existing files when you redirect output. If the file to which you
redirect output doesn’t (yet) exist, everything works as normal, with
bash creating the file as it opens it for output.
If the file already exists, however, you will get an error
message.
Here it is in action. We begin by turning the option off, just so that your shell is in a known state, regardless of how your particular system may be configured.
$ set +o noclobber $ echo something > my.file $ echo some more > my.file $ set -o noclobber $ echo something > my.file bash: my.file: cannot overwrite existing file $ echo some more >> my.file $
The first time we redirect output to my.file
the shell will create it for us. The second time we redirect,
bash overwrites the file (it truncates the file to
0 bytes and starts writing from there). Then we set the noclobber option and we get an error message
when we try to write to that file. As we show in the last part of this
example, we can append to the file (using >>) just fine.
Warning
Beware! The noclobber option only ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access