How to Execute Commands or Scripts at Reboot or Startup in Linux?

In the world of Linux, mastering the skill of executing commands or scripts during system reboot or startup is like possessing a magical key that opens the door to automated operations🔑. Whether it’s for system initialization settings, starting specific services, or performing data backups, this method allows for efficient automation. This article will take you on a deep dive into various methods for executing commands or scripts during Linux reboot or startup, providing powerful support for your Linux operations journey💪.

How to Execute Commands or Scripts at Reboot or Startup in Linux?

1. The rc.local Method

In early Linux systems, rc.local was a well-known and commonly used method to execute custom commands or scripts at startup. It acts like a “universal pocket” in the system startup process, where you can place any tasks you want to execute immediately after the system startup is complete.

To use rc.local, you first need to edit the /etc/rc.local file. This file is typically an executable script that is called towards the end of the system startup process. For example, suppose we have a simple script that prints a welcome message and starts a custom service at system startup. We can do the following:

Open the /etc/rc.local file with your preferred text editor (like vi or nano):

sudo vi /etc/rc.local

Add the following content to the file:

#!/bin/bash
# Print welcome message
echo "Welcome back to the Linux world!"
# Start custom service
/home/user/myservice start
exit 0
How to Execute Commands or Scripts at Reboot or Startup in Linux?

It is important to note that the commands or scripts added to the rc.local file must be executable, and the paths must be correct. Additionally, the exit 0 statement indicates that the script exits normally; if an error occurs during execution, you can return the corresponding error code based on the actual situation.

However, with the development of modern Linux systems, the usage of rc.local may have some changes. In some systems, it may be disabled by default, requiring you to enable it manually. For example, in some systemd-based systems, you may need to execute the following command to enable the rc-local service:

sudo systemctl enable rc-local

Then edit the /etc/rc.local file and add your commands or scripts. This method, while traditional, is still very effective for some simple startup tasks, especially in scenarios where using other complex system service management tools is not suitable or convenient.

2. systemd Service Unit

In modern Linux systems, systemd has become the mainstream initialization system and service manager. It provides a highly flexible and powerful way to manage system services, including executing commands or scripts at startup.

Creating a service unit with systemd to execute at startup is like crafting a little automation assistant that can accurately execute tasks at specific stages of system startup according to your requirements.

First, we need to create a service unit file. Suppose we want to create a service unit named mybootscript.service to execute a script located at /home/user/bootscript.sh at startup. You can follow these steps:

Create the service unit file:

sudo vi /etc/systemd/system/mybootscript.service

Add the following content to the file:

[Unit]
Description=My Boot Script Service
After=network.target

[Service]
Type=oneshot
ExecStart=/home/user/bootscript.sh

[Install]
WantedBy=multi-user.target
How to Execute Commands or Scripts at Reboot or Startup in Linux?

In this service unit file, the [Unit] section describes the basic information of the service, and After=network.target indicates that this service will execute after the network service starts. The [Service] section defines the service type as oneshot, meaning it executes only once, and ExecStart specifies the path of the script to be executed. The [Install] section indicates that this service should be started in multi-user mode.

After creating the service unit file, you need to reload the systemd configuration:

sudo systemctl daemon-reload

Then enable this service:

sudo systemctl enable mybootscript.service

Thus, the /home/user/bootscript.sh script will be automatically executed at the next system startup. If you want to test this service immediately, you can use the following command:

sudo systemctl start mybootscript.service

The advantage of using systemd service units is that they integrate well with other system services and resources, allowing you to finely control the startup order, dependencies, and more. Additionally, systemd provides rich logging and monitoring features, making it easy to view the execution status of the service and troubleshoot issues. For example, if your script encounters an error during execution, you can check the service logs with the following command:

sudo journalctl -u mybootscript.service

3. init.d Scripts

For some Linux distributions based on SysVinit or in scenarios compatible with SysVinit scripts, init.d scripts are still a viable way to execute commands or scripts at startup. init.d scripts act like a group of diligent little craftsmen during the system startup process, with each script responsible for starting, stopping, or managing a specific service or task.

To create an init.d script, you first need to create a script file in the /etc/init.d directory. For example, we create a script named myinitdscript:

sudo vi /etc/init.d/myinitdscript

Add the following basic structure to the script:

#!/bin/bash
# Description
### BEGIN INIT INFO
# Provides: myinitdscript
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: My Init.d Script
# Description: This script is used to perform custom tasks during system startup and shutdown.
### END INIT INFO

case "$1" in
    start)
        # Commands or scripts to execute at startup
        echo "Starting myinitdscript"
        /home/user/myscript.sh start
        ;;
    stop)
        # Commands or scripts to execute at shutdown
        echo "Stopping myinitdscript"
        /home/user/myscript.sh stop
        ;;
    *)
        echo "Usage: $0 {start|stop}"
        exit 1
        ;;
esac

exit 0
How to Execute Commands or Scripts at Reboot or Startup in Linux?

In this script, the part between ### BEGIN INIT INFO and ### END INIT INFO provides some metadata about the script, such as the service name it provides, the dependencies for starting and stopping, etc. The case statement determines the corresponding startup or shutdown operation based on the passed parameters (start or stop).

After creating the script, you need to grant it executable permissions:

sudo chmod +x /etc/init.d/myinitdscript

Then, you can use the following command to add the script to the system’s startup and shutdown sequence:

sudo update-rc.d myinitdscript defaults

Thus, during system startup and shutdown, myinitdscript will execute the startup or shutdown operations in the /home/user/myscript.sh script based on the corresponding parameters. It is important to note that writing init.d scripts must follow certain specifications and conventions, and there may be slight differences across different Linux distributions. However, overall, it provides an effective solution for compatibility with traditional SysVinit systems.

4. cron Tasks

Although cron tasks are primarily used for scheduling tasks, we can cleverly utilize them to execute commands or scripts at system startup. cron acts like a precise clock manager, capable of executing tasks at specific times or intervals you set, and system startup can also be seen as a special time point.

To use cron to execute tasks at startup, you need to edit the /etc/crontab file. For example, if we want to execute a data cleanup script /home/user/cleanup.sh at system startup, we can add the following content to the /etc/crontab file:

@reboot root /home/user/cleanup.sh
How to Execute Commands or Scripts at Reboot or Startup in Linux?

Here, @reboot indicates that the script should be executed at system reboot or startup, root indicates that the script is executed as the root user, followed by the script’s path.

It is important to note that the execution of cron tasks depends on the normal operation of the cron service. In some systems, the cron service may be enabled by default, but if you find that cron tasks are not executing as expected, you can check the status of the cron service to ensure it is running properly:

sudo service cron status

If the cron service is not running, you can start it with the following command:

sudo service cron start

The advantage of using cron to execute tasks at startup is that its setup is relatively simple, and it can be conveniently managed alongside other scheduled tasks. However, it should be noted that the execution timing of cron tasks may be affected by system load and other factors, so for some startup tasks that require very precise timing, it may not be the best choice.

How to Execute Commands or Scripts at Reboot or Startup in Linux?

Important! Operations and Maintenance Discussion Group is Open to the Public!Scan the code to add the editor’s WeChat, apply to jointhe groupHow to Execute Commands or Scripts at Reboot or Startup in Linux?▲ Long press to join the group

Leave a Comment