How do I prevent a file from accidentally being overwritten from redirection?



  • For some background, also see: https://en.wikipedia.org/wiki/Clobbering

    For additional protection from accidentally overwriting files. In your bashrc or equivalent. This can also be useful in some bash shell scripts, even if the setting is not permanently enabled.

    The short option for setting noclobber is -C

                  -C      If set, bash does not overwrite an existing file  with
                          the  >, >&, and <> redirection operators.  This may be
                          overridden when creating output files by using the re‐
                          direction operator >| instead of >.
    

    Turn on option for noclobber.

    set -o noclobber
    

    Any attempt to overwrite a file using redirection will be denied.

    $ ls > /tmp/myfile1
    -bash: /tmp/myfile1: cannot overwrite existing file
    

    To override a redirection write use >|

    $ ls >| /tmp/myfile1
    


© Lightnetics 2024