I have a text file in my home directory which receives data regularly through a cron job. Because the cron job provides dynamic data, I would also want to set a cron job to empty the file contents (the file must still exist). I don't need help with cron, just the command which can help with emptying the file.
The simplest way:
This is a less obvious way and probably less readable in a shell script by others, but it's all you need.
when you don't have permissions on that file. But you can use:
|show 1 more comment|
To automate this you can use logrotate. Just create a configuration file for the file you want to be emptied, add other settings and you can have it empty every day automatically based on criteria you choose f.e everyday, or when file is bigger than etc.
Take a look here on how to configure logrotate: http://linuxcommand.org/man_pages/logrotate8.html
There is a tool created for that purpose:
This will clear the contents but it will still be the same file.
An arguably easy to remember way is this:
For POSIX compliance use
Yet another way, more obscure and probably not shell agnostic:
If the file to truncate needs root privileges to write then the following lines will not work as probably expected:
This is because the redirection is done by the shell even before sudo is executed. That means that the write access to the file is done using the privileges of the user who runs the shell, not the privileges which will be granted by sudo.
A workaround is to defer the redirection to a shell executed using sudo privileges like this:
You can also use