Home » BASH » How to executing your script on startup

How to executing your script on startup

Last updated May 15, 2021

This script is not limited to running only applications or services at startup, but to also start scripts on bootup (power on) of a system. For example, if your system boots up and you would like to apply several tweaks to the OS such as performance enhancements or battery tweaks, you can do this on startup via the systemd or init.d script. Another example could be to run a never ending script that creates logging events, like an electronic version of a pulse monitor.

In short, Linux or most *NIX systems use either the venerable rc.d system or the newer and more controversial systemd system to manage the starting and stopping of system resources. Without diving into the entire boot sequence of Linux, here is how it works:

The Linux kernel is loaded and mounts the root filesystem.

The rootfile system contains a shell at a particular path (the init level).

Then, the systemd works its way through a series of services to start (the run level).

If a service or script is added, it will likely be added at the run level. It can also be started, stopped, reloaded, and restarted from the command line at any time as well. When the system is booting, it merely uses the start functionality provided by the init.d or system.d script. However, even though the semantics of either the rc.d or systemd system differ, they still require the following:

  • Scripts or services need to be enabled for specific system startup levels.
  • Scripts to be started and/or stopped can be configured to be started in a specific order.
  • Directives for starting (at a minimum), stopping, restarting and/or reloading are executed based on a parameter when executing one of these actions (or blocks). Any number of commands can also be executed when calling start, for example.

Prerequisites

In Ubuntu 16.04 LTS (and other distributions), use systemd. Knowledge of both the init.d and systemd service control systems is certainly worth having as many embedded systems use Busybox. BusyBox uses the init.d system instead of systemd.

Before diving into the “how to do it” section, we are going to create a template init script for posterity and awareness should you run into them. It will be called myscript and it will run myscript.sh. At a minimum, a system.d compatible script looks like the following:

myscript.sh

#!/bin/sh 
### BEGIN INIT INFO 
# Provides: myscript 
# Required-Start: $local_fs 
# Required-Stop: $local_fs 
# Default-Start: 2 3 4 5 
# Default-Stop: 0 1 6 
# Short-Description: Start script or daemons example 
### END INIT INFO 

PATH=/sbin:/bin:/usr/sbin:/usr/bin 
DAEMON_NAME=myscript.sh 
DESC=myscript 

DAEMON=/usr/sbin/$DAEMON_NAME 
case $1 in 
	start) 
	log_daemon_msg "Starting $DESC" 
	$DAEMON_NAME 
	log_end_msg 0 
	;; 
	stop) 
	log_daemon_msg "Stopping $DESC" 
	killall $DAEMON_NAME 
	log_end_msg 0 
	;; 
	restart|force-reload) 
	$0 stop 
	sleep 1 
	$0 start 
	;; 
	status) 
	status_of_proc "$DAEMON" "$DESC" && exit 0 || exit $? 
	;; 
	*) 
	N=/etc/init.d/$DESC 
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2 
	exit 1 
	;; 
esac 
exit 0 
# vim:noet

The content should be fairly easy to read if you have worked through the cookbook until this point. It relies on the comments in the header to determine the name, run levels, orders, and dependencies. Below that, it uses a switch statement while looking for several predetermined/standardized parameters: start, stop, restart, force-reload, and status. Inside of the start case, we start the binary, and in the stop case, we use the killall function to stop the binary.

It is important to know that the mere installation of an init script does not guarantee execution on startup. There is a process to enable the service or script. In the older system (SysV), you may have heard/seen of the command chkconfig being used. In systemd, you may use the systemctl command to enable/disable a service. In this section, we are only going to focus on systemd.

Note:

SysV executes the scripts in sequential order based on their number in the filename (for example, S99-myinit). Systemd does not because it also reviews dependencies and waits for their completion.

Write script:

Let’s start our activity as follows:

Create a script called myscript.sh with the following contents:

myscript.sh

#!/bin/bash 
for (( ; ; )) 
do 
	sleep 1 
done

Next, let’s add the correct permissions to the script so that we can create a systemd service using it. Notice the use of the sudo command—enter your password where appropriate:

$ sudo cp myscript.sh /usr/bin 
$ sudo chmod a+x /usr/bin/myscript.sh

Now that we have something to execute on start, we need to create a service configuration file to describe our service; we used vi in this example and sudo (note down its location):

myscript.service

$ sudo vi /etc/systemd/system/myscript.service 
[Unit] 
Description=myscript 

[Service] 
ExecStart=/usr/bin/myscript.sh 
ExecStop=killall myscript.sh 

[Install] 
WantedBy=multi-user.target

To enable the myscript service, run the following command:

$ sudo systemctl enable myscript # disable instead of enable will disable the service

To start and verify the presence of the process, run the following command:

$ sudo systemctl start myscript 
$ sudo systemctl status myscript

You may reboot the system to see our service in action on startup.

How this script works:

Let’s understand our script in detail:

In step 1, we create a trivial looping program to be ran at system startup called myscript.sh.

In step 2, we copy the script to the /usr/bin directory and add permissions using the chmod command for everyone to be able to execute the script (chmod a+x myscript.sh). Notice the use of sudo permissions to create a file in this directory and to apply permissions.

In the third step, we create the service configuration file, which describes a service unit for systemd. It goes by the name of myscript and within the [Service] directive, the two most important parameters are present: ExecStart and ExecStop. Notice that the start and stop sections look similar to the SysV/init.d approach.

Next, we use the systemctl command to enable myscript. Conversely, it can be used in the following way to disable myscript: $systemctl disable myscript.

Then, we use systemctl to start myscript and verify the status of our script. You should get a similar output to the following (notice that we double checked the presence using ps):

$ sudo systemctl status myscript 
myscript.service - myscript 
	Loaded: loaded (/etc/systemd/system/myscript.service; enabled; vendor preset: 
	Active: active (running) since Tue 2017-12-26 14:28:51 EST; 6min ago  
 Main PID: 17966 (myscript.sh) 
	CGroup: /system.slice/myscript.service 
		├─17966 /bin/bash /usr/bin/myscript.sh 
		└─18600 sleep 1 

Dec 26 14:28:51 moon systemd[1]: Started myscript. 
$ ps aux | grep myscript 
root 17966 0.0 0.0 20992 3324 ? Ss 14:28 0:00 /bin/bash /usr/bin/myscript.sh 
rbrash 18608 0.0 0.0 14228 1016 pts/20 S+ 14:35 0:00 grep --color=auto myscript

On reboot, if enable was set, our script will be running as expected.

Related Posts

Creating a config file and using it in tandem with your scripts

In this article, we are going to create a config file and use it in our shell script.PrerequisitesBesides having a terminal open, you need basic knowledge of creating scripts and config files.Write scriptNow, we are going to create a script and config file. The...

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

Using Bash to monitor battery life and optimize it

In this article, we will learn about the TLP Linux tool. TLP is a command-line tool; it is used for power management and will optimize the battery life.PrerequisitesBesides having a Terminal open, you need to ensure that you have TLP installed on your system.How to do...

Creating a simple NAT and DMZ firewall using bash script

In this article, we will create a simple NAT firewall with DMZ using iptables.PrerequisitesBesides having a Terminal open, you need to ensure that iptables is installed in your machine.Write scriptWe will write a script to set up a DMZ using iptables. Create...

Follow Us

Our Communities

More on BASH

The Ultimate Managed Hosting Platform
Load WordPress Sites in as fast as 37ms!

0 Comments

0 Comments

Submit a Comment

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

seven + fourteen =

Shares