Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix shell script to truncate a large file

I am trying to write a Unix script which will truncate/empty a file which is continuously being written/open by an application when it reaches say 3GB of space. I know that the below command would do it :

cp /dev/null [filename] 

But I am going to run this in an production environment automatically as a cron job - just posting here to see if you guys faced any issues while doing something similar to this.

like image 427
peedee Avatar asked Nov 27 '12 00:11

peedee


People also ask

How do I trim a file in bash?

Another different way to remove the contents of a file is using the “truncate” command. The file “empty.sh” has been used here again with the same text script. By running the bash command, the output will be as same as in the image. After that, we will use the “truncate” command followed by the “-s” keyword.


2 Answers

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.

like image 55
chepner Avatar answered Oct 12 '22 13:10

chepner


I've used the following command on debian

truncate -s 0 filename 
like image 27
Ricardo Marimon Avatar answered Oct 12 '22 12:10

Ricardo Marimon