How to Execute a Command or a Script on system Startup or Reboot

Rispondi
Avatar utente
openresource
Administrator
Administrator
Messaggi: 382
Iscritto il: mar gen 28, 2020 9:52 pm
Reactions score: 4
Località: varese
Contatta:
giu 2020 06 07:14

How to Execute a Command or a Script on system Startup or Reboot

Messaggio da openresource

Immagine

Being a Linux system admin or even a general Linux user, you might be required to run some commands or scripts at a regular interval or at a needed time. We use crontab to accomplish these tasks & we have already discussed Crontab in our tutorial. But how can we execute a command or script on system startup or after a reboot?
Well, there are two ways we can execute a command or script on system startup or after a reboot,

1- using ‘/etc/rc.local’ file
2- using Crontab

Recommended Read:  Beginner’s guide to Backup Postgres Database
Also Read: Scheduling CRON Jobs with Crontab for Beginners
Let’s discuss both these methods one by one.

1- Using ‘/etc/rc.local’ file

This is my go-to method when I need to execute a command or script on system startup. To execute a command on startup, open the file 

‘/etc/rc.local’,

NOTE:- In the latest CentOS version, we might find this file in ‘/etc/rc.d/rc.local’.

$ sudo vi /etc/rc.local
& add it into the file with full command path, like,
/bin/date

Save file & exit. To get the full path of the command, you can run the ‘which’ command,

$ which date

Now the command will execute on each startup or after a reboot as well. To add a script to the file, first make sure that the script is executable,

$ chmod +x /home/linuxtechlab/test.sh
& then edit the rc.local file,
$ sudo vi /etc/rc.local
/bin/sh /home/linuxtechlab/test.sh

Save the file & exit, we are done. Now let’s see the second method as well.

2- Using Crontab

For this method, we only need to create a new crontab job in our system. So to create a new crontab job, run the following command,

$ crontab -e

Then add the following job to crontab,

@reboot (sleep 120; /bin/sh /home/linuxtechlab/test.sh)

So we added the job to run on every reboot with a sleep period of 120 seconds because we want our system to be fully up before our script is executed, otherwise, our script might fail to run. We now end this tutorial on how to execute command or script on system startup or after a reboot.

Immagine
Rispondi