1

I have a custom script which gzip log files when they are one day old. In my script all errors (stderr) are logged to a file and at the end of the script I use this file to know if its execution was good or not.

This part of my code looks like

# redirection of stderr to file
exec 2> /tmp/errors.txt

# gzip old log files
find *.log -mtime +1|xargs gzip -f

# test if error log file is empty
if [ -s /tmp/errors.txt ]; then
    .....
fi

My problem is: this code works great if there is at least one file to gzip, but if not it raises an error when I don't want to.

I've tried different solutions to solve this problem with no success.

Does anyone know how to solve this problem?

slm
  • 7,615
  • 16
  • 56
  • 76
daks
  • 673
  • 7
  • 25

2 Answers2

1

Try this

#redirect stderr to null
exec 2> /dev/null
FILECOUNT = `find *.log -mtime +1|wc -l`

#redirection of stderr to file
exec 2> /tmp/errors.txt

# gzip old log files    
if [ $FILECOUNT != '0' ]; then
   find *.log -mtime +1|xargs gzip -f
fi

# test if error log file is empty
if [ -s /tmp/errors.txt ]; then
    .....
fi`
Pablo
  • 330
  • 1
  • 6
1

If you are using a GNU version of xargs you can use -r:

   --no-run-if-empty
   -r     If the standard input does not contain any nonblanks, do not run
          the command.  Normally, the command is run once even if there is
          no input.  This option is a GNU extension.

Code:

# redirection of stderr to file
exec 2> /tmp/errors.txt

# gzip old log files
find *.log -mtime +1|xargs -r gzip -f

# test if error log file is empty
if [ -s /tmp/errors.txt ]; then
    .....
fi
Lesmana
  • 2,304
  • 2
  • 17
  • 12