Running Command at Startup on Crontab

Running Command at Startup on Crontab

I wanted to run a command on our linux after its done rebooting, I saw that it can be done using crontab. I wanted to run this command

sudo ifdown eth0 && sudo ifup -v eth0

on the crontab can i just do:

@reboot sudo ifdown eth0 && sudo ifup -v eth0

or do i need to store that in a script?

thank you

3

2 Answers

A few notes here before this would work:

  1. Don't use sudo in a cron job. Instead edit root's crontab instead of your own, e.g. sudo crontab -e and then enter commands without sudo.
  2. As @mikewhatever mentioned, this is an odd use for cron, and would likely be better placed in /etc/rc.local before the exit 0 line.
  3. If you tell us exactly what you're looking for, we might be able to direct you to a log or config option (restarting your network services at startup feels a little hackish).
  4. On most systems @reboot should also run after a hard shutdown or crash, but there are different cron implementations so YMMV. I've seen comments in different places asserting both.

EDIT (2016/02/17): Removed incorrect blurb on absolute paths; kudos @muru
EDIT (2016/10/17): Added shutdown note
EDIT (2017/09/11): Revised shutdown note. Not really sure on that one.

9

You can use crontab for this, but if you use sudo, then you will need a NOPASSWD rule in sudoers to do so. (See How to run a cron job using the sudo command.)

It would be simpler to edit /etc/rc.local and add these commands before the exit 0 line.

2

Your Answer

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

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.