-3

I have question why is my cmd for "removing all files in directory except last 20" not working within cron but in command prompt yes.

* * * * *  ls -1tr /home/testusr/test | head -n -20 | xargs -d '\n' rm -f  > /var/opt/check.log 2>&1

Directory contains let say 100x files which are named DATA-20140605xxxx generated minute by minute.

Thank advance for any answer.

2 Answers2

2

The problem you are having is caused because the output of your ls command doesn't contain the path to the file it only contains the filename. When a cron job runs, it runs in the users home directory so when your rm is run, it is looking for files in /home/testuser not /home/testuser/test.

You could fix this with a simple cd command

cd /home/testuser/test && ls -1tr /home/testusr/test ...

This however isn't great as you are parsing the output of ls which is a Bad IdeaTM see the link for extensive discussion.

user9517
  • 117,122
0

If you run that ls from your root directory, you'll get a file list, but NOT a path. So in effect, you're trying to delete DATAblah from whatever the cwd of cron is.

The solution is either:

  • embed a chdir into cron (or wrap your commands in a script).
  • use something other than 'ls.echo /home/testuser/test/*` will give you path names, for example. (But obviously - no defined sort order).
  • find a way to prefix that path to rm.

Wrapper scripts are generally a good bet for this sort of thing though. Could you instead to a time based deletion? IF they're timestamped minute by minute, could you instead delete all files older than say, 10m old?

In which case: find /home/testuser/test/ -mmin +10 -exec rm {} \; might do the trick.

Sobrique
  • 3,817