Overwrite file every day

Hi Friends,

I have written a script to capture system performance every hour and redirected to output file. How to overwrite the file every next day?

Thanks
Suresh

Hi,

You can schedule cron job to remove file every day like below.

0 0 * * * rm -f namefFile

Thanks
Pravin

There's a few ways:

  • remove or rename the old file.
  • unset noclobber (and set it back after).
  • force redirection using script >| file .
2 Likes

In CarloM's very good answer - the >| is a POSIX required shell redirection operator - it overrides the noclobber option. You seldom see it in posts on this forum.

Shorthand for truncating a file (make a file zero length):

 >| myfile  (works regardless of noclobber option)
 > myfile   (works when noclobber is not set, which is usually the default setting)

You control noclobber this way

set +o noclobber     # turn off   default for most users on most systems, except for "read-only" users.
set -o noclobber      # turn on   Note: a priori the -/+ signs appear to be backwards but this is correct

So you could add this to your crontab:

1 0 * * * >| /path/to/file/to/overwrite

This runs at one minute after midnight every day. The file is empty after this code runs, regardless of shell options.

4 Likes

What if the file is held open by an application running? Will that application write to file offset 0, or will the file continue to exist on disk, but lose its directory entry?