Linux – Copy the contents of a file into a new file in Linux

Copy the contents of a file into a new file in Linux… here is a solution to the problem.

Copy the contents of a file into a new file in Linux

I would like to know how to copy all the contents of a file (server.log) to a new file using Linux commands and delete the contents from the original file. It’s actually easy to do that. But I actually want to make sure there won’t be a content update in that operation. Follow the Linux commands to do what I want, but I have to make sure that there is no change in server.log between command1-command2 executions.

command1: #cp server.log serverNew.log 
command2: #truncate -l 0 server.log

Solution

I would use tools built specifically for this purpose, rather than using some temporary solution.

Take a look at logrotate.

It supports compression, running commands after each spin, rotating based on size or time, etc….

Based on your comment below, I assume you are interested in these options:

Post rotation/end script

The line between postrotate and endscript (both of which must appear separately in the line) is executed (using /bin/sh) after log file rotation. These directives may only appear in the log file definition. Typically, the absolute path to the log file is passed to the script as the first parameter. If sharedscripts are specified, the entire schema is passed to the script. See also prerotate. For error handling, see Shared Scripts and NoSharedScripts.

Pre-rotate/end script

The line

between prerotate and endscript (both of which must appear separately on the line) is executed (using /bin/sh) before the log file is rotated, and only if the log is actually rotated. These directives may only appear in the log file definition. Typically, the absolute path to the log file is passed to the script as the first parameter. If sharedscripts are specified, the entire schema is passed to the script. See also postrotate. For error handling, see Shared Scripts and NoSharedScripts.

Related Problems and Solutions