Running Commands at Startup

If you find that you need to run a particular command whenever the server boots up, there are a number of ways to do this.

rc.local

One of the traditional and most popular ways is to use the rc.local file. Ubuntu will look to this file when booting up, and execute any commands in it as root. This means you don’t need to add ‘sudo’ at the start of the command. This file is located in your /etc directory. If you find that /etc/rc.local does not exist, you can create it using nano. Just add the following lines to the file:

Then make it executable by entering

Any commands you need run at startup must be entered before the ‘exit 0’.

Crontab

Cron is the service in linux which allows you to schedule commands or jobs to be run. You can schedule a script to be run every 30 minutes, or at a set time repeatedly. You can also use cron to run a command when the server boots up.

First open crontab in edit mode:

scroll to the bottom and then use the @reboot suffix, followed by your command or the script you want to run:

Each use on the server will have a crontab for themselves, and any command/script they run under their crontab will be run using their own permissions. If there are any sudo commands, you will need to ensure the user has been included in the /etc/sudoers file with NOPASSWD privileges.

Leave a comment