This tip is for people who have ever hosed important files by using > when they meant to use >>. Add the following line to .bashrc:
set -o noclobber
The noclobber option prevents you from overwriting existing files with the > operator.
If the redirection operator is ‘>’, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is ‘>|’, or the redirection operator is ‘>’ and the noclobber option is not enabled, the redirection is attempted even if the file named by word exists.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$ echo "Hello, world" >file.txt $ cat file.txt Hello, world $ echo "This will overwrite the first greeting." >file.txt $ cat file.txt This will overwrite the first greeting. $ set -o noclobber $ echo "Can we overwrite it again?" >file.txt -bash: file.txt: cannot overwrite existing file $ echo "But we can use the >| operator to ignore the noclobber." >|file.txt $ cat file.txt # Successfully overwrote the contents of file.txt using the >| operator But we can use the >| operator to ignore the noclobber. $ set +o noclobber # Changes setting back |
Run: