Pages

Friday, June 2, 2017

How to Auto Execute Commands/Scripts During Reboot or Startup

I am always fascinated by the things going on behind the scenes when I boot a Linux system and log on. By pressing the power button on a bare metal or starting a virtual machine, you put in motion a series of events that lead to a fully-functional system – sometimes in less than a minute. The same is true when you log off and / or shutdown the system.
What makes this more interesting and fun is the fact that you can have the operating system execute certain actions when it boots and when you logon or logout.

In this distro-agnostic article we will discuss the traditional methods for accomplishing these goals in Linux.
Note: We will assume the use of Bash as main shell for logon and logout events. If you happen to use a different one, some of these methods may or may not work. If in doubt, refer to the documentation of your shell.

Executing Linux Scripts During Reboot or Startup

There are two traditional methods to execute a command or run scripts during startup:

Method #1 – Use a cron Job

Besides the usual format (minute / hour / day of month / month / day of week) that is widely used to indicate a schedule, cron scheduler also allows the use of @reboot. This directive, followed by the absolute path to the script, will cause it to run when the machine boots.
However, there are two caveats to this approach:
  1. a) the cron daemon must be running (which is the case under normal circumstances), and
  2. b) the script or the crontab file must include the environment variables (if any) that will be needed (refer to this StackOverflow thread for more details).

Method #2 – Use /etc/rc.d/rc.local

This method is valid even for systemd-based distributions. In order for this method to work, you must grant execute permissions to /etc/rc.d/rc.local as follows:
# chmod +x /etc/rc.d/rc.local
and add your script at the bottom of the file.
The following image shows how to run two sample scripts (/home/gacanepa/script1.sh and /home/gacanepa/script2.sh) using a cron job and rc.local, respectively, and their respective results.

      ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
                                                    ► Read more: http://adf.ly/1n5ZAN
      ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

No comments:

Post a Comment