Run crontab non-interactively from script

6,517

Solution 1

From StackOverflow: Linux - How do I create a crontab thru a script

Cron jobs usually are stored in a per-user file under /var/spool/cron

The simplest thing for you to do is probably just create a text file with the job configured, then copy it to the cron spool folder and make sure it has the right permissions.

Solution 2

I am fairly new to linux shell scripting and I found the answers in the SO post Brian mentioned to be incomplete. They were a great help and had most of the information I needed but I ran into a couple issues wit permissions and executing commands over ssh. My final solution is:

cd ~/
echo "" > x
sudo cp ~/x /var/spool/cron/crontabs/myuser
sudo chown myuser:crontab /var/spool/cron/crontabs/myuser
echo "*/20 * * * * /path/to/myscript" > c
cat ~/c | crontab -

First I create an empty crontab file, then correct the permissions to what crontab needs, then put the cron command in a file and finally tell crontab to schedule the script.

Adding the cron command to a file instead of using echo was necessary because I was having issues with quoting over ssh.

Solution 3

You can edit the entries of the crontab without using the -e option as follows.

#write out current crontab
crontab -l > mycron
#echo new cron into cron file
echo "<new crontab entry>" >> mycron
#install new cron file
crontab mycron
rm mycron

This works really well for creating/editing (use sed) crontab entries via scripts.

Source: StackOverflow

Share:
6,517

Related videos on Youtube

Nash0
Author by

Nash0

Updated on September 18, 2022

Comments

  • Nash0
    Nash0 almost 2 years

    I would like to schedule some tasks on remote servers by script but am having an issue with crontab expecting to be run interactively the first time. As far as I understand crontab needs to be initialized by first running crontab -e. Which causes it to prompt which editor to use and launch that editor.

    I need initialize crontab and schedule a task on too many servers to log into each individually. Is there a way I can avoid the interactive part or script it?

    The servers and my client are running Ubuntu 13.04.

  • Rahul Kadukar
    Rahul Kadukar almost 3 years
    What happens if there is no existing crontab, in that case crontab -l will not work