Redirecting output of a program to a rotating file Redirecting output of a program to a rotating file linux linux

Redirecting output of a program to a rotating file


If I understood your problem, one solution (without modify myprogram.sh) could be:

$ myprogram.sh | while true; do head -10 >> /var/log/httpd/error_log; done

Explaining:

  • myprogram.sh writes to stdout
  • We redirect this output to while bash sentence through a pipe |.
  • while true is an infinite loop that will never end, nor even when myprogram.sh ends which should break the pipe.
  • In each loop head command is called to append the first 10 lines read from the pipe to the end of current /var/log/httpd/error_log file (that may be different from the last loop because of logrotate).

(You can change the number of lines being written in each loop)

And another way is:

$ myprogram.sh | while read line; do echo "$line" >> /var/log/httpd/error_log; done
  • That's very similar to the first one, but this ends the loop when myprogram.sh ends or closes it's stdout.
  • It works line by line instead in groups of lines.