How to add a crontab entry from a shell script on Linux?

crontab -e will start an editor to edit the crontab entries. But how to add a crontab entry from a shell script on Linux without interaction from users?

You can try this piece of script:

(crontab -l; echo "@reboot echo "rebooted"";) | crontab -

Note that the update by this line of script is not atomic. If some other programs edit the crontab files between the first and second invokes of crontab, the edits will be lost. Hence, make sure there is not other programs/admins editing the crontab when you use this piece of script.

Answered by Vivian.

One comment:

  1. Fantastic solution, thank you!

    I’ve implemented this into a BASH function:

    add_cron() {
    # save the entire line in one variable

    # check if line already exists in crontab
    crontab -l | grep “$line” > /dev/null

    if [ $status -ne 0 ]
    echo “adding line …”
    (crontab -l; echo “$line”;) | crontab –

    This avoids duplicate adding. You can then add a line like so:
    add_cron “* * * * * /path/to/executable argument_1 argument_2 >/dev/null 2>&1”

    Kind regards,

Leave a Reply

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