svn | awk | mail works in bash, but not in cron job
I have the following command to show changes to a subversion repository
svn log -v -r{$(date +%Y-%m-%d)}:HEAD http://therepository | awk '/^r[0-9]+ / {user=$3} {if (user=="username")开发者_开发知识库 {print $1 $2 $3}}' | mail -ne -s'Users SVN commits' email@email.com
It works fine in the command line.
When I paste it into a crontab, I get the following error message:
/bin/sh: -c: line 0: unexpected EOF while looking for matching `)'
/bin/sh: -c: line 1: syntax error: unexpected end of file
How does this need to be quoted to work?
When using cron, avoid the hassle of such issues by putting everything into a shell script, then call the shell script from cron.
This approach is commonly used and a good idea because:
- It makes your command easily testable (you don't have to do stupid things like schedule an execution in one minute's time)
- Easy to manually invoke if you have to, eg in case the job failed, ops can re-run without touching crontab - also jobs can be invoked from other jobs, eg a final job that checks if all jobs ran OK and re-runs those that didn't
- It separates what is executed from when it's executed - leaving cron to do (only) what it does best: scheduling
- It gives you full access to shell script features, or using different shells like perl
- It keeps crontab clean and easy to read
- Anyone developing/maintaining cron tasks knows where to look if you use a consistent directory for cron tasks (eg /opt/cron or whatever)
- You can put your cron tasks under source control - too often shell scripts are overlooked for source control, but they are code and therefore benefit from source control
For example:
dosomething.sh:
svn log -v -r{$(date +%Y-%m-%d)}:HEAD http://therepository | awk '/^r[0-9]+ / {user=$3} {if (user=="username") {print $1 $2 $3}}' | mail -ne -s'Users SVN commits' email@email.com
plus
cron 0 22 * * * /opt/cron/dosomething.sh
The easiest thing to do would be to save that as a bash script, and then run the script from cron.
(I would have made this a comment rather than an answer, but SO won't let me comment)
joe
精彩评论