17

I need to delete files under directory except latest 2.

I have prepared command to list according to date and delete files. It work when I run manually from command line , however it does not work in crontab.

In crontab,

* * * * * /bin/ls -t /mytest | /usr/bin/tail -n +2 | /usr/bin/xargs rm --

This command works when I run this command from commandline.

Also tried to add command in bash script then called that script from crontab but it did not work again.

How can I run that command via crontab?

5
  • Hi, welcome to stack overflow. Explain what does not work; did you see any errors? May 26, 2019 at 6:17
  • Hi, no any errors - but can see it ran according to cron logs
    – llmelmo
    May 26, 2019 at 6:20
  • what if you try bash -c "/bin/ls -t /mytest | /usr/bin/tail -n +2 | /usr/bin/xargs rm --" as the command to your cron job?
    – GMc
    May 26, 2019 at 7:31
  • no luck , its working from command line again but no in cron job
    – llmelmo
    May 26, 2019 at 9:17
  • Enable crons error logging, e.g. by setting MAILTO=.
    – Wiimm
    May 26, 2019 at 10:02

1 Answer 1

28

crontab only expects one command. If multiple commands are to be executed, they can be bundled using bash -c

* * * * * bash -c 'ls -t /mytest | tail -n +2 | xargs rm --'
2
  • Probably remove the explicit paths while you're at it.
    – tripleee
    May 26, 2019 at 8:17
  • is PATH at the beginning of crontab defined?
    – UtLox
    May 26, 2019 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.