How to Run a Script/Command on Startup on Linux/Ubuntu

How to Run a Script/Command on Startup or Login on Linux/Ubuntu

Want to run a program, command, or script when you start or log into your Linux OS? This article will show you how.

Running Scripts on Startup with Crontab

The best way to run a command whenever your system starts is using crontab.

cron is the job scheduler used by Linux to schedule the execution of tasks.

The crontab is the text file where those tasks are defined.

There is a system-wide crontab file, and each user also has their own individual crontab file for scheduling their own tasks.

Adding a System-Wide Startup Task

The system-wide crontab is located at:

/etc/crontab

It can be edited using the nano text editor by running:

sudo nano /etc/crontab

Note the use of sudo – the system crontab must be edited as root.

Each line in a crontab file defines a task. Each line starts with a schedule for the task to be run at, followed by a tab or space, followed by the command to run.

Linux has a special schedule command @reboot which will run the specified command every time the computer starts.

So, to define a system-wide task to ruin a shell script each time the system boots, the following line should be added:

@reboot  /var/scripts/my-startup-script.sh

As you can see, the @reboot schedule is followed by the command to run (in this case, it’s the path to a shell script to be executed).

Tasks defined in the system crontab will be run as root.

Adding a Startup Task for a User

Regular users can’t edit the system crontab.

It is also recommended not to run non-administrative tasks as the root user unless necessary (it’s usually a good idea to have a user for each task which is restricted to using the resources only required for that task, as a security measure).

To run your startup task as a regular user, you will need to add it to that user’s individual crontab.

If you are logged in as the user in question, you can run:

crontab -e

To edit the crontab for that user.

Then, add your command to the file as we did for the system-wide crontab above:

@reboot  /var/scripts/my-startup-script.sh

To edit the crontab for another user, you will need to switch to that user’s account temporarily:

sudo -u otheruser crontab -e

Note the user of the sudo command with the -u argument to execute the command as another user.

All commands added to a user’s crontab will be run as that user – and will only have access to the system resources that the user has permission to access.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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