2015년 9월 13일 일요일

Truncating a file when the noclobber option is set

On a recent service call, a client asked me if there was a way to get rid of an enormous log file (> 10 gigabytes) without using rm which would cause high I/O load on a production system. I told the client to use the redirect operator to truncate the file to an empty file.

In normal cases, simply doing

> fileName

which is equivalent to

cat /dev/null > fileName

will do the trick.

When the client tried this, however, he got the following error message:

File exists

A quick google search revealed that this error is returned when the noclobber option is set in .bashrc or the configuration file for your shell of choice (ksh, csh, etc).

To override noclobber just once, you would use the >| operator in bash:

>| fileName

The server in question happened to be using C-shell, however, so the noclobber redirect override should be >!

>! fileName


References:

http://www.linuxhowtos.org/Tips%20and%20Tricks/Protecting%20files%20with%20noclobber.htm

http://stackoverflow.com/questions/2423281/how-to-empty-truncate-a-file-on-linux-that-already-exists-and-is-protected-i