如何清空(“截断”)Linux 上已经存在并以某种方式受到保护的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2423281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to empty ("truncate") a file on linux that already exists and is protected in someway?
提问by Sumeet Pareek
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
我的服务器上有一个名为 error.log 的文件,我需要经常截断它。我对该文件有 rw 权限。在vi中打开文件>删除所有内容>保存作品(显然)。但是当我尝试下面的
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?
显然,在服务器上进行了某种配置以防止意外覆盖文件。谁能告诉我如何在单个命令中“截断”文件?
采纳答案by R Samuel Klatchko
You have the noclobber
option set. The error looks like it's from csh, so you would do:
您已设置noclobber
选项。错误看起来像是来自 csh,所以你会这样做:
cat /dev/null >! file
If I'm wrong and you are using bash, you should do:
如果我错了并且您正在使用 bash,则应该执行以下操作:
cat /dev/null >| file
in bash, you can also shorten that to:
在 bash 中,您还可以将其缩短为:
>| file
回答by Dodger Web
false|tee fileToTruncate
false|tee fileToTruncate
may work as well
也可以工作
回答by SIFE
This will be enough to set the file size to 0:
这足以将文件大小设置为 0:
> error.log
回答by Oden
You can try also:
你也可以试试:
echo -n > /my/file
echo -n > /my/file
回答by risnandar
You can also use function truncate
您还可以使用函数截断
$truncate -s0 yourfile
if permission denied, use sudo
如果权限被拒绝,请使用 sudo
$sudo truncate -s0 yourfile
Help/Manual: man truncate
帮助/手册:man truncate
tested on ubuntu Linux
在 ubuntu Linux 上测试
回答by sakhunzai
Since sudo will not work with redirection>
, I like the tee
command for this purpose
由于 sudo 不适用于重定向>
,因此我喜欢tee
用于此目的的命令
echo "" | sudo tee fileName
回答by petermolnar
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.
这不会破坏日志文件,因此您甚至可以在 syslog 上使用它,例如。
回答by user3301460
Any one can try this command to truncate any file in linux system
任何人都可以尝试使用此命令截断linux 系统中的任何文件
This will surely work in any format :
这肯定适用于任何格式:
truncate -s 0 file.txt
回答by Den129
I do like this:
cp /dev/null file
我喜欢这样:
cp /dev/null file