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?

αғsнιη
  • 40,939
  • 15
  • 71
  • 114
RDK
  • 23
  • 3
  • that is `2>&1` not `2>$1`. Also you can change `\;` to `+` to [speed up deleting by the find command](https://unix.stackexchange.com/a/194348/72456) – αғsнιη Oct 28 '22 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 '22 at 14:47

2 Answers2

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
roaima
  • 107,089
  • 14
  • 139
  • 261
0

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

White Owl
  • 4,511
  • 1
  • 4
  • 15