Remove old files rolling by date, keeping certain number of files in Cronjob not working

349 views Asked by At

I need some help with a bash script. The script "backup.sh" looks like this:

  rm -f $(ls -t /backups/mongo/ | awk 'NR>14')
  rsync -pvztr  --progress /backups/*...........

I want to remove old files in /backups/mongo/ folder, keeping no more than 15 files. The script works fine if I run ./backup.sh, but if I make it run as a cronjob, the remove part (rm) does not work, the rests work.

Can someone help me spot the problem?

2

There are 2 answers

0
Murad Tagirov On

Looks like you have to load bash profile. Its not loading by default when you call bash script from crontab. Just add

source /etc/profile

to the beginning of you script

0
AnFi On

1 Make ls produce full paths of files to be removed. Otherwise rm may fail or remove files in wrong directory if current directory is not /backups/mongo/.
2 You use bash specific syntax. Use sheebang to make you script use bash.

#!/bin/bash
rm -f $(ls -t /backups/mongo/* | awk 'NR>14')
....