flouts
flouts

Reputation: 21

Bash script run from cron

I have the following bash script:

#!/bin/bash
src="/home/user/testingscript"
for dir in $(ls "$src")
do
find ${src}/${dir}/ -type f -mtime +31 delete
done

It runs fine if i execute it from the terminal, but once i put it in the crontab like that:

* * * * * /bin/bash /home/user/script/mailboxclean.sh >> /home/user/mailboxcleanup.log 2>&1

or as:

* * * * * /home/user/script/mailboxclean.sh

it doesnt run.

I see no feedback in the syslog, apart that the script has been executed and in the mailboxcleanup.log where i am redirecting I see the followinh which doesnt really help:

/home/user/mailboxcleanup.log: 1: /home/user/mailboxcleanup.log: /bin/sh:: not found

Any ideas?

Thanks

Upvotes: 2

Views: 2775

Answers (1)

Olivier Dulac
Olivier Dulac

Reputation: 3791

It depends where you put the script.

If you want it to be run via /etc/crontab: you need a 6th parameter before the command, specifying the user!

 * * * * * theuser /home/user/script/mailboxclean.sh

If you place it in someone's (root, or a user) crontab using crontab -e

 * * * * * /home/user/script/mailboxclean.sh

(ie, no 6th parameter, as the user is known)

Be careful that if you want to have it run daily/weekly/monthly by placing it under /etc/cron.*/, you need to REMOVE the extension (ie, call it mailboxclean) as otherwise it will simply be ignored

The most common cause of difference is that the script lack some environment variable when run via cron (or when placed underneath a /etc/cron.* directory)... Check for this (you could add a : echo "=== set: ============ " ; set ; echo "=== env: ============ " ; env at the beginning of your script while debugging, for example. Or just ensure you set everything you need correctly)


And not related to the question, but you should change the

for dir in $(ls "$src"); do find ${src}/${dir}/ -type f ....

to

for dir in "${src}"/*/ ; do find "${dir}" -type f ....

(see http://mywiki.wooledge.org/BashPitfalls for infos on this, and many other (the rest of their site is great too, when you learn bash scripting))

Upvotes: 1

Related Questions