Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script runs from shell but not from cron job

Tags:

linux

bash

cron

Cron installation is vixie-cron

/etc/cron.daily/rmspam.cron

#!/bin/bash
/usr/bin/rm /home/user/Maildir/.SPAM/cur/*;

I Have this simple bash script that I want to add to a cron job (also includes spam learning commands before) but this part always fails with "File or directory not found" From what I figure is the metachar isn't being interperted correctly when run as a cron job. If I execute the script from the commandline it works fine.

I'd like a why for this not working and of course a working solution :)

Thanks

edit #1 came back to this question when I got popular question badge for it. I first did this,

#!/bin/bash
find  /home/user/Maildir/.SPAM/cur/ -t file | xargs rm

and just recently was reading through the xargs man page and changed it to this

#!/bin/bash
find  /home/user/Maildir/.SPAM/cur/ -t file | xargs --no-run-if-empty rm

short xargs option is -r

like image 595
Tanj Avatar asked Oct 01 '08 12:10

Tanj


People also ask

Why does my cron job not run?

Crontab might fail for a variety of reasons: The first reason is that your cron daemon might not be working for any reason, resulting in your crontab failing. There also exists a possibility that your system's environment variables are not settled correctly.

Does cron use bash or sh?

Cron Uses /bin/sh By Default, Not Bash Bash ( /bin/bash ) is a common shell on most distros, and is an implementation of sh. The /bin/sh file is a symlink to an sh implementation, but it isn't always bash. On Debian based systems like Ubuntu, and on macOS, /bin/sh links to dash by default.


1 Answers

If there are no files in the directory, then the wildcard will not be expanded and will be passed to the command directly. There is no file called "*", and then the command fails with "File or directory not found." Try this instead:

if [ -f /home/user/Maildir/.SPAM/cur/* ]; then
    rm /home/user/Maildir/.SPAM/cur/*
fi

Or just use the "-f" flag to rm. The other problem with this command is what happens when there is too much spam for the maximum length of the command line. Something like this is probably better overall:

find /home/user/Maildir/.SPAM/cur -type f -exec rm '{}' +

If you have an old find that only execs rm one file at a time:

find /home/user/Maildir/.SPAM/cur -type f | xargs rm

That handles too many files as well as no files. Thanks to Charles Duffy for pointing out the + option to -exec in find.

like image 157
janm Avatar answered Oct 16 '22 18:10

janm