nixCraft Poll

Topics

How to keep files safe from accidental overwriting with noclobber under BASH shell

Posted by Vivek Gite [Last updated: February 23, 2007]

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:

Discussion on This Article:

  1. Artem Nosulchik Says:

    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.

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!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.