How to create a cron job using Bash automatically without the interactive editor?
You can add to the crontab as follows:
#write out current crontabcrontab -l > mycron#echo new cron into cron fileecho "00 09 * * 1-5 echo hello" >> mycron#install new cron filecrontab mycronrm mycron
Cron line explaination
* * * * * "command to be executed"- - - - -| | | | || | | | ----- Day of week (0 - 7) (Sunday=0 or 7)| | | ------- Month (1 - 12)| | --------- Day of month (1 - 31)| ----------- Hour (0 - 23)------------- Minute (0 - 59)
Source nixCraft.
You may be able to do it on-the-fly
crontab -l | { cat; echo "0 0 0 0 0 some entry"; } | crontab -
crontab -l
lists the current crontab jobs, cat
prints it, echo
prints the new command and crontab -
adds all the printed stuff into the crontab file. You can see the effect by doing a new crontab -l
.
This shorter one requires no temporary file, it is immune to multiple insertions, and it lets you change the schedule of an existing entry.
Say you have these:
croncmd="/home/me/myfunction myargs > /home/me/myfunction.log 2>&1"cronjob="0 */15 * * * $croncmd"
To add it to the crontab, with no duplication:
( crontab -l | grep -v -F "$croncmd" ; echo "$cronjob" ) | crontab -
To remove it from the crontab whatever its current schedule:
( crontab -l | grep -v -F "$croncmd" ) | crontab -
Notes:
- grep -F matches the string literally, as we do not want to interpret it as a regular expression
- We also ignore the time scheduling and only look for the command. This way; the schedule can be changed without the risk of adding a new line to the crontab