Sumeet Pareek
Sumeet Pareek

Reputation: 2819

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

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?

Upvotes: 118

Views: 120495

Answers (9)

Den129
Den129

Reputation: 11

I do like this: cp /dev/null file

Upvotes: 1

user3301460
user3301460

Reputation: 21

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

Upvotes: 2

petermolnar
petermolnar

Reputation: 1626

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.

Upvotes: 13

sakhunzai
sakhunzai

Reputation: 14470

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

echo "" | sudo tee fileName

Upvotes: 4

risnandar
risnandar

Reputation: 5563

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

Upvotes: 77

Oden
Oden

Reputation: 754

You can try also:

echo -n > /my/file

Upvotes: -4

SIFE
SIFE

Reputation: 5695

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

> error.log

Upvotes: 49

Dodger Web
Dodger Web

Reputation: 114

false|tee fileToTruncate

may work as well

Upvotes: 4

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

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

Upvotes: 164

Related Questions