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

by on February 23, 2007 · 2 comments· 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



You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 2 comments… read them below or add one }

1 Artem Nosulchik September 11, 2007 at 8:34 am

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.

Reply

2 V.Balaviswanathan May 12, 2009 at 8:47 am

@Artem

The utiltiy chattr is not only used to prevent overwritten but also can make a file undeletable

To view a file which has this attribute set we use the command

lsattr

I hope you know this command but to refresh i gave this command

Thanks and Regards

V.Balaviswanathan

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 8 + 11 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.



Previous post:

Next post: