How to keep files safe from accidental overwriting with noclobber under BASH shell
This happens many times. You accidentally use redirecting output using > operator.
For example you type a command:
$ ls -l *.c > output.txt
If file output.txt exists and is a regular file it will be overwritten. Just imagine as root user, typing somecommand > /etc/passwd instead of somecommand < /etc/passwd.
Or you used > when they meant to use >> (append).
So how do you tell shell not to delete file data / contents by mistake?
You need to set noclobber variable. It can keep you from accidentally destroying your existing files by redirecting input over an already-existing file.
Task: Set noclobber i.e. prevent overwriting
Type the command:
$ set -o noclobber
Now try to write to a file called output.txt
$ cat > output.txt
OR
ls -l > output.txt
Output:
bash: output.txt: cannot overwrite existing file
Add set -o noclobber to your ~.bashrc file:
$ echo ‘set -o noclobber’ >> ~.bashrc
Task: Turn off noclobber
Type the following command:
$ set +o noclobber
Using + rather than - causes these flags to be turned off.
Task: Temporary turn off noclobber
Sometime you just need to turn off noclobber for single operation. Use >| operator to force the file to be overwritten:
$ ls /etc >| output.txt
$ less output.txt
Read bash man page for more information:
$ man bash
$ help set
Want to stay up to date with the latest Linux tips, news and announcements? Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
You may also be interested in other helpful articles:
- Linux : How to delete file securely
- How Install and setup a honeypot
- Git revision control software howto
- Howto: Verify Downloaded Linux / BSD DVD or CD ISO images for integrity
- Happy Diwali
Discussion on This Article:
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!



There is also chattr utility that is very useful to prevent files being overwritten and/or modified even under root. In order to protect critically important file just execute chattr +i /path/to/file. To disable protection execute chattr -i /path/to/file.