Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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`
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

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.