How to empty ("truncate") a file on linux that already exists and is protected in someway?

LinuxFileCommand Line

Linux Problem Overview


I have a file called error.log on my server that I need to frequently truncate. I have rw permissions for the file. Opening the file in vi > deleting all content > saving works (obviously). But when I try the below

cat /dev/null > error.log

I get the message

File already exists.

Obviously there is some kind of configuration done on the server to prevent accidental overriding of files. Can anybody tell how do I "truncate" the file in a single command?

Linux Solutions


Solution 1 - Linux

You have the noclobber option set. The error looks like it's from csh, so you would do:

cat /dev/null >! file

If I'm wrong and you are using bash, you should do:

cat /dev/null >| file

in bash, you can also shorten that to:

>| file

Solution 2 - Linux

You can also use function truncate

$truncate -s0 yourfile

if permission denied, use sudo

$sudo truncate -s0 yourfile

Help/Manual: man truncate

tested on ubuntu Linux

Solution 3 - Linux

This will be enough to set the file size to 0:

> error.log

Solution 4 - Linux

the credit goes for my senior colleague for this:

:> filename

This will not break log files, so you can even use it on syslog, for example.

Solution 5 - Linux

> false|tee fileToTruncate

may work as well

Solution 6 - Linux

Since sudo will not work with redirection >, I like the tee command for this purpose

echo "" | sudo tee fileName

Solution 7 - Linux

I do like this: cp /dev/null file

Solution 8 - Linux

Any one can try this command to truncate any file in linux system

This will surely work in any format :

truncate -s 0 file.txt

Solution 9 - Linux

You can try also:

echo -n > /my/file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSumeet PareekView Question on Stackoverflow
Solution 1 - LinuxR Samuel KlatchkoView Answer on Stackoverflow
Solution 2 - LinuxrisnandarView Answer on Stackoverflow
Solution 3 - LinuxSIFEView Answer on Stackoverflow
Solution 4 - LinuxpetermolnarView Answer on Stackoverflow
Solution 5 - LinuxDodger WebView Answer on Stackoverflow
Solution 6 - LinuxsakhunzaiView Answer on Stackoverflow
Solution 7 - LinuxDen129View Answer on Stackoverflow
Solution 8 - Linuxuser3301460View Answer on Stackoverflow
Solution 9 - LinuxOdenView Answer on Stackoverflow