I have created a script to install two scripts on to the crontab.


 sudo crontab -l > mycron
 #echo new cron into cron file

 echo "*/05 * * * * bash /mnt/md0/capture/delete_old_pcap.sh" >> mycron #schedule the delete script
 echo "*/12 * * * * bash  /mnt/md0/capture/merge_pcap.sh" >> mycron     #schedule the merge script

#install new cron file
 crontab mycron
rm mycron

The script runs, and add the two lines to the crontab. But if I run the script again, it adds those lines again , thus I will have four lines saying the same stuff. I want the install script to run such that, the lines inserted to the crontab do not repeat. How can I do that


I would recommend using /etc/cron.d over crontab.

You can place files in /etc/cron.d which behave like crontab entries. Though the format is slightly different.

For example

*/05 * * * * root bash /mnt/md0/capture/delete_old_pcap.sh
*/12 * * * * root bash  /mnt/md0/capture/merge_pcap.sh

The difference in the format is adding the user to run the job as after the time specification.

Now you can simply check if the file exists, and if you overwrite it, it doesn't matter.


Note that it's possible your cron daemon might not have /etc/cron.d. I do not know which cron daemons have it, but vixie cron is the the standard cron daemon on linux, and it does.


You could instead declare a function:

add() {
  grep -Fq "$1" mycron || echo "$1" >> mycron

and invoke it by saying:

add "*/05 * * * * bash /mnt/md0/capture/delete_old_pcap.sh"

This would append the line only if doesn't exist in the file.

  • can you please tell what grep -Fq "$1" does? – Jishnu U Nair Feb 27 '14 at 12:35
  • And the script give error grep: input file `mycron' is also the output – Jishnu U Nair Feb 27 '14 at 12:43
  • @JishnuUNair -F would make grep interpret the pattern as fixed string. – devnull Feb 27 '14 at 12:50
  • @JishnuUNair Are you sure that you copied the above text correctly? – devnull Feb 27 '14 at 12:50
  • yes, I have copied it correctly. – Jishnu U Nair Feb 27 '14 at 12:59

from bash I use

    crontab -l | { cat; echo "*/10 * * * * /script/script.sh > /dev/null 2>&1"; } | crontab -

Also use this script to add cron entries on remote servers

    cronok+=`ssh $host 'crontab -l'`;

    if [[ "$cronok" == *${pattern}* ]]; then
         echo "found cron  at [$host]"
        echo "Cron at [$host] not found adding now"
       `ssh $host 'crontab -l | { cat; echo "*/10 * * * * /root/reboot.sh > /dev/null 2>&1"; } | crontab -'`
       echo "finished cron"

You can write a script and add it to crontab to stop it:

####You should calculate tiem you want kill your script.
#######code of calculating........
pid=`ps ax |egrep myscript |awk {'print $1'}`
kill -9 $pid
kill $pid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.