Adding a task into crontab is relatively easy. You just enter the crontab with “$ crontab -e” and add the necessary job, save and exit.

But adding a job in your bash script is not that simple, because what you have to do is, to get the entire list of the jobs, append your new job and save them as a whole.

Here’s a snippet of how to do that. Here, we assume that we want to run a script called “myscript.sh” every 5 minutes and the full path of the script is “$my_path/myscript.sh”. Don’t forget that in everycase, adding a job to crontab you have to specify the full path!

So basically, add these lines to your script.

command="$my_path/myscript.sh" > /dev/null 2>&1"
job="* /5 * * * * $command"
cat <(grep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -

Note that this is for BASH, not SH, since the syntax with the brackets is only available in BASH.

As you can see, the last line is the critical one. In the first brackets using the grep tool, we catch everything currently in the crontab “except our command”, so this will prevent from adding the $command even if it is already in crontab. After that, we echo our job to the end of the current jobs, and redirect it to cat as a standart input. Since the standart output of cat will be the whole crontab list “with our new job”, we can use crontab with its “-” option to get the arguments from the stadart output.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: