Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need help to write a script to copy log files.

There are two format of logs:

  • System_<date_timestamp>.log
  • trace_<date_timestamp>.log

New files are generated when trace log reaches 20 MB and sytem log reaches 10MB.

Only 5 of these logs (5 for each kind) are allowed to be saved, once there is more than 5 of them, the old files get deleted and replaced by new ones.

Therefore, before they get deleted I need to copy them to a different location so that I can view them later when needed to debug.

Basically, it will look like the following (showing just trace log format, similar with System log):

share|improve this question

Also you can use log-rotate for the same, see following example

# Logrotate file for trace

/source/path/trace_*.log {
    rotate 1
        # After compressing logs, move to other location 
        Log_dir="/target/dir/old_log_$(date +%F)/$(date +%H_%S)/"
        [[ ! -d "${Log_dir}" ]] && /bin/mkdir -p "${Log_dir}"
        /bin/mv /source/path/*.gz "${Log_dir}"

save above file, let say /etc/logrotate_trace.conf then simply set cron job for every hour

00 * * * * /usr/sbin/logrotate  -f /etc/logrotate_trace.conf

for testing you can run it from command line as

/usr/sbin/logrotate  -f /etc/logrotate_trace.conf
share|improve this answer

With GNU cp (as found on most non-embedded Linux distributions and a few other Unices):

cp -p --update /source/path/trace_*.log /target/dir
share|improve this answer

The most straightforward tool is rsync, which copies new files, updates changed files, and leaves existing unchanged files alone.

rsync -a /path/to/source/*.log /path/to/backup/directory/
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.