In the context of a command line interpreter, clobbering means overwriting the contents of a file using shell redirection (using the > and >> operators). This is sometimes useful, sometimes catastrophic.

By default, the clobbering is enabled in both zsh and bash, or the be technically correct, the noclobber option is disabled (enabling the noclobber option prevents overwriting of files by redirection). To check this option (works in zsh and bash):

$ set -o | grep noclobber

If the output is:

noclobber       off

then the option is disabled and you can overwrite a file by redirection.

I use mostly zsh with the prezto configuration framework on top, which enables the noclobber option, which is great for preventing you from accidentally overwriting a file.

To enable the noclobber option (just like other shell options):

$ set -o noclobber

or using the shorthand:

$ set -C

To permanently enable the option you may put one of the lines below in the config file of you shell ($HOME/.bashrc for bash, $HOME/.zshrc for zsh)

To disable the noclobber option:

$ set +o noclobber

or using the shorthand:

$ set +C

However, we can overcome the noclobber restriction by:

  • Using the >| redirection operator instead of > like this:
$ echo "blah blah blah" >| existing_file
  • Using the tee utility from GNU coreutils:
$ echo "blah blah blah" | tee existing_file

I consider the second option a bit better, because it's also useful when you're logged in as a non priviledged user and want to write to a system file.

For example, you want to change to I/O scheduler of the sda disk device to noop. That would be normally done by writing noop to /sys/block/sda/queue/scheduler.

$ echo noop > /sys/block/sda/queue/scheduler
zsh: permission denied: /sys/block/sda/queue/scheduler

Oops! Apparently we don't have enought permissions, let's sudo try again:

$ sudo echo noop > /sys/block/sda/queue/scheduler
zsh: permission denied: /sys/block/sda/queue/scheduler

Wait, what?? It doesn't work with sudo? Why? Because the redirection is done as the user that started the shell, not root. You may sudo su and then repeat the command, but I think it's easier to just:

$ echo noop | sudo tee /sys/block/sda/queue/scheduler