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 typoYou 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 huponexitEdit: I forgot to add, thanks for the detailed answer!
It won't save you from clobbering from another machine when using scp, though, so watch out.
cat paper.* > paper.all
This has the potential to use up the whole disk. The fix here is easy: do globbing before redirection. But this does not solve the other problem:
cat a b > a
This has a simple workaround which is even easier to type: cat a >> b. But the trap remains. How could the shell fix it? By pretending the user wrote this instead:
cat a b > temp; mv temp a
Let's look at the trade offs. We do a bit of extra work: one rename operation. This should be pretty cheap, and solves this problem as well as paper.all.
The real trouble I think is coming up with a good name and location for tmpfile that is guaranteed not to mess up the operation of the command we're running. If we put it in the current directory, we get the wrong answer from ls. If we put it in /tmp, it will mess things up when we're working in /tmp. However, after doing a few minutes of research, it appears that this problem is already solvable on Linux: by using the O_TMPFILE flag, there is no need to give the file a name at all, until after the command finishes running.
The result of cat a b > a is precisely the result that the user intends, provided that the user has actually read the documentation.