Adding Job to Crontab Using BASH

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.
  • 9644 Kunder som kunne bruge dette svar
Hjalp dette svar dig?

Relaterede artikler

Setting time with NTP in LINUX

NTP (Network Time Protocol) could be used to set time synced with ntp clocks, to do this use the...

Linux version & Operating System info

LINUX Version Info To learn the architecture and kernel version info use the shell command...

Compile and build Apache + MySQL + PHP from the source [cite]

This is a complete working solution to build Apache (httpd-2.2.25), MySQL (MySQL-5.6.14) and PHP...

Using vi Editor

Vi is the one of the mostly used editor in Linux via terminal. In most cases where Linux is used...

Build PHP5.5 on CentOS 6.4 with MSSQL Support [cite]

Most of the yum repos doesn’t include PHP5.5.X on current releases for the time being. So...