37

How can I override the file exists: warning from zsh?

> echo > newfile.txt
> echo > newfile.txt  
zsh: file exists: newfile.txt  

In these cases I prefer my shell to not complain and simply overwrite the file, like bash.

Likewise, how to override the following:

$ ls >> /tmp/testfile.txt                                                                                                                                                   
zsh: no such file or directory: /tmp/testfile.txt
1
  • 2
    set +C should be longer for a comment. But maybe that's because i failed to mention >| for a single-use case.
    – mikeserv
    Jun 25, 2015 at 14:38

3 Answers 3

58

You can force the ZSH to clobber on redirect with:

>!

Same as >, except that the file is truncated to zero length if it exists, even if CLOBBER is unset.

or

>>!

Same as >>, except that the file is created if it does not exist, even if CLOBBER is unset.

31

Does your setopt output mention noclobber? If so, that's it, just setopt clobber

The documentation for the option is at http://zsh.sourceforge.net/Doc/Release/Options.html#index-file-clobbering_002c-allowing

24

Others have recommended using >! or >>! but these are not POSIX standard. The POSIx compliant way to overwrite files without prompting is to use >| or >>| and this will work in any shell.

For information see here: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_02

1
  • Note that the noclobber feature comes from csh, long before it was added to the Bourne shell or POSIX. And the syntax there was and still is with >!. In the fish shell, neither >! nor >| are supported. The former will redirect stdout to a ! file, and >| will give you a syntax error. Same in rc and derivatives. Jun 15, 2020 at 8:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.