Protecting File Content During I/O Redirection with noclobber in Bash shell
How to use noclobber during redirection to avoid overwriting files
Redirecting standard output to an existing file overwrites the previous file content, which results in data loss. This process of overwriting existing data is known as clobbering. To prevent an overwrite from occurring, the shell supports a noclobber option.
When the noclobber option is set, the shell refuses to redirect the standard output to the existing file and displays an error message to the screen. The noclobber option is activated in the shell using the set command. For example:
$ set -o noclobber
$ set -o | grep noclobber
noclobber on
$ ps -ef > file_new
$ cat /etc/passwd > file_new
bash: file_new: cannot overwrite existing file
$
Deactivating the noclobber Option
Tempororily disable noclobber
To temporarily deactivate the noclobber option, use the >| deactivation syntax on the command line. The noclobber option is ignored for this command line only, and the contents of the file are overwritten.
$ ls -l >| file_new
Disable noclobber on a Bash shell
To deactivate the noclobber option, perform the following commands:
$ set +o noclobber
$ set -o | grep noclobber
noclobber off
$ ls -l > file_new
$