0

I would like to run a CRONTAB job to delete files older than 5 days in a folder AND pipe the command output to a file in case of errors.

This command deletes the files when run from a command line:

/usr/bin/find /mnt/SQL_Backups/* -mtime +5 -exec rm {} \;

but, when I add this to it to get the the stdout and stderr pipe, it fails.

/usr/bin/find /mnt/SQL_Backups/* -mtime +5 -exec rm {} \; > /mnt/output/CRONDeleteFiles.txt 2>$1

From the command line, error is

-bash: $1: ambiguous redirect

while from CRONTAB email error message, I get this error

/bin/sh: 1: cannot create : Directory nonexistent

I suspect it has something to do with my piping code?

What is the right way to do this?

2
  • that is 2>&1 not 2>$1. Also you can change \; to + to speed up deleting by the find command Oct 28, 2022 at 13:23
  • Not sure how many times I looked at that line. I must need glasses. And thanks for the speed improvement hint...
    – RDK
    Oct 28, 2022 at 14:47

2 Answers 2

0

stderr to stdout is redirected with 2>&1, not 2>$1 as in your example.

0

You could write to the logger,

find /mnt/SQL_Backups/* -mtime +5 -print -delete 2>&1 | logger -t rmsqlbackups

Since I've not provided a priority or facility (e.g. -p user.info) on my systems this gets written to /var/log/messages amongst others. The 2>&1 captures stderr as well as stdout.

Alternatively use your own method and write to a file, although I suspect you may want append (>>) rather than output (>), and here I've prepended all output with the current date/time so that you can see what was deleted when:

( date; find /mnt/SQL_Backups/* -mtime +5 -print -delete; echo ) >> /mnt/output/CRONDeleteFiles.txt 2>&1

Not the answer you're looking for? Browse other questions tagged .