用于截断大文件的 Unix shell 脚本

我正在尝试编写一个 Unix 脚本,它将截断/清空一个应用程序不断写入/打开的文件,当它达到大约3GB 的空间时。我知道下面的命令可以做到这一点:

cp /dev/null [filename]

但是我将在一个生产环境中作为 cron 作业自动运行它-只是在这里发布,看看你们在做类似的事情时是否遇到了任何问题。

59345 次浏览

That seems reasonable to me. Unix, of course, would let you do this about 50 different ways. Here are two examples:

echo -n "" >filename
cat /dev/null >filename

Just to add another answer,

: > filename

: is a no-op in bash (POSIX-compliant), so this essentially just opens the file for writing (which of course truncates the file) and then immediately closes it.

EDIT: as shellter commented, you don't actually need a command to go along with the redirection:

$ echo foo > foo.txt
$ cat foo.txt
foo
$ > foo.txt
$ cat foo.txt
$

A simple redirection all by itself will clear the file.

I've used the following command on debian

truncate -s 0 filename

trunc filename

works on AIX flavor of UNIX