Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash command with pipe not working in crontab

Tags:

linux

bash

cron

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?

like image 273
llmelmo Avatar asked May 26 '19 06:05

llmelmo


1 Answers

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 --'
like image 96
UtLox Avatar answered Oct 07 '22 19:10

UtLox