Linux Shell: Protecting against accidental output redirection and file overwrite
Redirecting standard output/error in a Linux/BSD shell can very easy overwrite a file, removing it's content, making it impossible to recover (unless there's a backup).
To prevent this
sh,
bash and
ksh shells implement an evironment variable called
noclobber.
Code:
# cat tmp.file
If you use a lot of file redirection in your scripts it's quite easy to overwrite existing files accidentaly.
To prevent this, most shells implement the noclobber environment variable.
# echo "Overwritten content">tmp.file
# cat tmp.file
Overwritten content
Checking if noclobber is activated in current shell:Code:
# set -o
allexport off
braceexpand on
emacs on
errexit off
errtrace off
functrace off
hashall on
histexpand on
history on
ignoreeof off
interactive-comments on
keyword off
monitor on
noclobber off
noexec off
noglob off
nolog off
notify off
nounset off
onecmd off
physical off
pipefail off
posix off
privileged off
verbose off
vi off
xtrace off
Activating shell noclobber environment variable:Code:
# set -o noclobber; set -o | grep noclobber
noclobber on
At this point, accidental output redirections cannot harm. An error will occur when this will happen:
Code:
# echo "2nd Overwritten content">tmp.file
bash: tmp.file: cannot overwrite existing file