I need to periodically empty a text file without deleting it (I know how many lines it has).
I tried this:
Created a cron that executes the following script
other lines from the script here
sed '1,14d' file.txt>file.txt
If I run it from a terminal it works fine, but when I run the cron it executes the first part (the "other lines from script here" part) but it doesn't empty the file.
Note: The file has 777 permissions so I don't think it's permissions related.
You can try a simple >file.txt
Maybe the current working directory isn't what you're expecting when cron executes the script. Try specifying the full path to file.txt. Also, this should empty the file as well, just in case there's some issue with the sed command:
You can also use
logrotate
, which gives you the option of not just emptying the file, but archiving (e.g., compressing) the previous contents of the file, and even mail the file to you.The traditional un*x way to "empty" a file:
Moving the file & touching a new file (hence, changing the file descriptor) may prevent existing apps from continuing to write to the file, so that generally is undesirable. If a copy if the existing file is required, you can do something like (although, note it's not atomic, so some date may be duplicated in both files):
And, as mentioned, 'cron' jobs do not usually run in the directory you expect; but you can "cd" to your desired directory in the script to do the work & still use relative paths.
I would do this:
mv file file.bak && touch file && rm file.bak
I move the file first, in case the system happens to have it open.
You can even use truncate(1), if your system has it.