No Clobber
Never overwrite files by accident
Posted: June 16, 2023
Ever unintentionally clobbered a file when redirecting some output to it?
$ cat some_file
foo bar
# Unintentionally overwrite 'some_file'
$ echo "potato" > some_file
$ cat some_file
potato
This can happen whenever the output file already exists. Or when you accidentally write to the file with >
instead of appending to it using >>
.
Most Linux shells actually have an option to prevent you from unintentionally overwriting files. It is generally called “no clobber” and you can enable it as follows:
# On Bash ~/.bashrc
set -o noclobber
# On Zsh ~/.zshrc
setopt NO_CLOBBER
This will make sure that the filename does not exist before trying to redirect data into it:
$ cat some_file
foo bar
# Unintentionally overwrite 'some_file'
$ echo "potato" > some_file
zsh: file exists: some_file
# 'some_file' remains untouched
$ cat some_file
foo bar
But what if we intentionally want to overwrite a file? In that case, we can tell bash to ignore the clobber by using >|
instead:
$ echo "potato" >| some_file
$ cat some_file
potato