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

Posted on In QA

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
    line=$*

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

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

    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,
    Martin.

Leave a Reply

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