How to empty (“truncate”) a file on linux that alr

2019-01-21 00:56发布

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?

8条回答
2楼-- · 2019-01-21 01:07

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.

查看更多
甜甜的少女心
3楼-- · 2019-01-21 01:07

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

echo "" | sudo tee fileName
查看更多
▲ chillily
4楼-- · 2019-01-21 01:09

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

> error.log
查看更多
迷人小祖宗
5楼-- · 2019-01-21 01:10

false|tee fileToTruncate

may work as well

查看更多
等我变得足够好
6楼-- · 2019-01-21 01:12

You can try also:

echo -n > /my/file

查看更多
Juvenile、少年°
7楼-- · 2019-01-21 01:21

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

查看更多
登录 后发表回答