How to prevent accidental file overwrites from output redirection How to prevent accidental file overwrites from output redirection, redirecting output, prevent accidental overwrites of files
It is possible (and very easy) to delete a file's content just by a simple output redirection to that file.
# echo "Some output" > output.o
If output.o is a regular file and it contained some information before this, you can say "Good bye" to it, unless you have another copy stored somewhere on the filesystems/backup media.
Let's say that output.o already contains some information and we do the redirection:
# cat output.o something # echo "another text" >| output.o # cat output.o another text
I've just overwritten the file. The information stored is gone.
To prevent accidental file overwrites from output redirection, use the noclobber variable (type: set -o noclobber in your shell). It will keep you from accidentally overwrite files.
# set -o noclobber # cat output.o another text # echo "something back" > output.o output.o: cannot overwrite existing file
... and there you have it.. :)
Appending output to an existing file
Same as redirecting, only that instead of ">" we use ">>"
# echo "something back" >> output.o && cat output.o another text something back
Overwrite a file's content even if noclobber variable is set
(instead of command > file , use command >| file )
To have noclobber variable set all the time add the line set -o noclobber line to your shell's profile or /etc/profile so that all users will have it (of course they can overwrite it by deactivating noclobber: set +o noclobber).
Pay great attention. NOCLOBBER variable can save you from accidental file overwrites from output redirection, but not from forced redirection (>|)
Designed and developed by Andrei Manescu. Optimized for Mozilla Firefox.
Copyright 2007 Andrei Manescu
All trademarks and copyrights on this page are owned by their respective owners. Comments are owned by those who posted them.