3 ms·
In modern bash, this case is already protected with the "noclobber" option (enabled with "set -C" or "set -o noclobber"). It is described in the "REDIRECTION" s
by pdkl95 12y ago
In modern bash, this case is already protected with the "noclobber" option (enabled with "set -C" or "set -o noclobber"). It is described in the "REDIRECTION" section of bash(1), subsection "Redirecting Output".
It fails ">" redirections with an error message when it would clobber an existing file (you probably wanted to append to the file wiht ">>"). If you really intended this behavior, the new redirection operator '>|' has the old behavior.
$ set -o noclobber
$ echo foo > bar
$ cat bar
foo
$ cat bar > bar
bash: bar: cannot overwrite existing file
$ echo baz > bar
bash: bar: cannot overwrite existing file
$ echo baz >| bar
$ cat bar
baz
edit: fixed typo
- girvo 12y agoThat's a nice feature, but it should definitely be turned on as a default rather than hidden behind an option.
- pdkl95 12y agoThat would break a very large number of existing scripts that depend on being able to replace a file with a traditional ">" redirection. You can set it as the default for your own interactive shell if you want by adding set -o noclobber to your ~/.bashrc file. It is probably a good idea to add it after the line that check if it is being used non-interactively, which probably looks something like this if [[ $- != *i* ]] ; then # Shell is non-interactive return fi # add interactive-shell-only settings here While you're editing .bashrc, you may want to also add these options that are available in modern bash that I find make the experience a lot nicer. # support new glob patterns like !(foo|bar|...) # for example, this move everything EXCPET the .h files # mv !(*.h) /some/dir/ shopt -s extglob # support ** in globs to match zero-or-more-recursive-directories shopt -s globstar # if you're annoyed at having to type "nohup" to prevent # programs from closing when you close the shell window shopt -u huponexit
- girvo 12y agoRight, it definitely would break a lot of existing scripts, so I understand why its not a default. The thing is though, that really proves the argument that some parts of Unix have a bad out of the box user experience! I personally love Unix and find it amazingly powerful, but I've made the same mistakes as everyone and killed entire boxes, and really with some simple UX changes that could be fixed in the bulk of cases. Edit: I forgot to add, thanks for the detailed answer!
- sapsan 12y agoNice feature, never heard of that before. Thanks!
- SiVal 12y agonoclobber is also an option setting in zsh, and I always have it set. The little extra confirmation it requires before clobbering is actually a nice confirmation that you are doing what you intended when you did intend it, and a nice rescue in case you didn't. It won't save you from clobbering from another machine when using scp, though, so watch out.