Найти: как не иметь ошибок (stderr), когда нет файлов

У меня есть собственный скрипт, который gzip файлы журнала, когда им один день. В моем скрипте все ошибки (stderr) записываются в файл, и в конце скрипта я использую этот файл, чтобы узнать, было ли его выполнение хорошим или нет.

Эта часть моего кода выглядит

# 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

Моя проблема: этот код прекрасно работает, если есть хотя бы один файл для gzip, но если нет, то возникает ошибка, когда я этого не хочу.

Я пробовал разные решения, чтобы решить эту проблему без успеха.

кто-нибудь знает, как решить эту проблему?

2 ответа

Решение

Попробуй это

#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`

Если вы используете GNU-версию xargs, вы можете использовать -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.

Код:

# 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
Другие вопросы по тегам