Sunday, May 11, 2025

How to Use Systemd to Run Bash Scripts at Boot in Linux

https://www.tecmint.com/create-new-service-units-in-systemd

How to Use Systemd to Run Bash Scripts at Boot in Linux

A few days ago, I came across a CentOS 8 32-bit distro and decided to test it on an old 32-bit machine. After booting up, I realized there was a bug causing the network connection to drop. Every time I rebooted, I had to manually bring the network back up, which led me to wonder: How can I automate this process with a script that runs every time the system boots?

The solution is straightforward, and today, I’ll show you how to do this using systemd service units, but before we jump into that, let’s first take a quick look at what a service unit is and how it works.

In this article, we’ll cover the basics of systemd service units, their relationship with “targets,” and how to set up a service unit to run a script at boot. I’ll keep things simple, focusing on the practical steps, so you’ll have everything you need to know to tackle this on your own.

What is a Systemd Service Unit?

In simple terms, a service unit in systemd is a configuration file that defines how a service should behave on your system. It could be something like a network service, a program, or even a script that needs to run when your computer boots or at a specific point during the boot process.

These service units are grouped into targets, which can be seen as milestones or stages in the boot process. For example, when your system reaches the multi-user target (runlevel 3), certain services will be started. You can think of these targets as “collections” of services that work together at various stages of the boot sequence.

If you’d like to see the services running in a particular target (for example, graphical.target), you can use the systemctl command:

systemctl --type=service

This will show you all active services in your current target. Some services run continuously, while others start up once and then exit.

List All Active Services
List All Active Services

Checking the Status of a Service

If you’re curious about a particular service, you can use systemctl status to see whether it’s active or inactive:

systemctl status firewalld.service

This command checks the status of the firewalld service. You’ll notice that it’s active, meaning it’s running, and enabled, which means it will start automatically on the next boot.

You can also stop a service temporarily (until the next boot) using:

systemctl stop firewalld.service
systemctl status firewalld.service

This will stop the firewalld service for this session, but won’t prevent it from starting up next time.

Check Status of Service
Check Status of Service

Enabling and Disabling Services

To ensure a service starts automatically on boot, you need to enable it, which will create a symbolic link in the appropriate target’s wants folder:

systemctl enable firewalld.service

To disable it, you would simply run:

systemctl disable firewalld.service
Enabling and Disabling Systemd Services
Enabling and Disabling Systemd Services

Creating a Custom Service Unit

To set up a service that runs a script at boot, we’ll create a new service unit under the /etc/systemd/system directory, here you’ll see existing service unit files and folders for different targets.

cd /etc/systemd/system
ls -l
Existing Service Unit Files
Existing Service Unit Files

Let’s create our own service unit called connection.service using Vim or your preferred text editor to create it:

vim connection.service
Or
vi connection.service

Add the following content to the file.

[Unit]
Description=Bring up network connection
After=network.target

[Service]
ExecStart=/root/scripts/conup.sh

[Install]
WantedBy=multi-user.target

Explanation:

  • [Unit]: The unit’s metadata. We’ve given it a description and told it to run after network.target, meaning it will only execute after the network has been initialized.
  • [Service]: This section defines the command to execute when the service starts. In this case, it runs the script conup.sh.
  • [Install]: This section tells systemd that the service should be loaded at the multi-user target, which is the standard runlevel for most systems.

Now, enable the service so it will start automatically on the next boot:

systemctl enable connection.service

You can confirm that it has been enabled by checking the multi-user.target.wants directory:

ls -l multi-user.target.wants/

The symbolic link to connection.service should now be present. However, we still need to create the script that this service will run.

Verify Service Unit File
Verify Service Unit File

Creating the Script

Let’s now create the conup.sh script that will bring the network connection up.

cd /root
mkdir scripts
cd scripts
vi conup.sh

Add the following line to bring the network up, here the script uses the nmcli command to bring the network connection on the enp0s3 interface up.

#!/bin/bash
nmcli connection up enp0s3

Don’t forget to make the script executable.

chmod +x conup.sh

At this point, the service is ready to go.

SELinux Contexts (For RHEL/CentOS Users)

If you’re using a RHEL-based system (like CentOS or Rocky Linux), don’t forget about SELinux, which can block scripts from running if the correct security context isn’t applied.

To temporarily set the context so the system treats the script as a regular executable, use:

chcon -t bin_t /root/scripts/conup.sh

However, this change won’t survive a reboot or file relabeling.

To make it permanent, use:

semanage fcontext -a -t bin_t "/root/scripts/conup.sh"
restorecon -v /root/scripts/conup.sh

This step ensures the script continues to run properly even after reboots or SELinux policy reloads.

Testing the Service

To test it without rebooting, you can start it manually.

systemctl start connection.service

If everything is set up correctly, the service will execute the script, and your network connection should be restored.

Alternatively, if you wrote a simpler script like touch /tmp/testbootfile, you can check if the file was created in /tmp to confirm the service is running as expected.

Conclusion

By now, you should have a good understanding of systemd service units and how to create and manage them on your system. You’ve also automated a common task – bringing up the network connection on boot using a simple service unit.

Hopefully, this guide helps you get more comfortable with managing services, targets, and scripts in systemd, making your system more automated and efficient.


15 Useful ‘dpkg’ Commands for Debian and Ubuntu Users [With Examples]

https://www.tecmint.com/dpkg-command-examples

15 Useful ‘dpkg’ Commands for Debian and Ubuntu Users [With Examples]

Debian GNU/Linux is the backbone of several popular Linux distributions like Knoppix, Kali, Ubuntu, Mint, and more. One of its strongest features is its robust package management system, which makes installing, removing, and managing software a breeze.

Debian and its derivatives use a variety of package managers such as dpkg, apt, apt-get, aptitude, synaptic, tasksel, dselect, dpkg-deb, and dpkg-split. each serving a different purpose.

Let’s quickly go over the most common ones before diving deeper into the dpkg command.

Common Debian-Based Package Managers

Command Description
apt apt, short for Advanced Package Tool, is used in Debian-based systems to install, remove, and update software packages.
aptitude aptitude is a text-based front-end to apt, great for those who prefer a terminal-based interface with menus.
synaptic synaptic is a graphical package manager that makes it easy to install, upgrade, and uninstall packages even for novices.
tasksel tasksel allows users to install all packages related to a specific task (like a desktop environment or a LAMP server).
dselect dselect is a menu-driven package management tool initially used during the first install, and is now replaced with aptitude.
dpkg-deb Used for working directly with .deb archives – creating, extracting, and inspecting them.
dpkg-split dpkg-split is useful for splitting and merging large files into chunks of smaller files to be stored on media of smaller sizes, such as floppy disks.

dpkg is the main package management program in Debian and Debian-based systems, used to install, build, remove, and manage packages. aptitude is the primary front-end to dpkg.

Some of the most commonly used dpkg commands, along with their usages, are listed here:

1. Install a Package on Ubuntu

To install a package using dpkg, you need to download .deb package file from the following official package repository sites for Debian and Ubuntu-based distributions.

Once downloaded, you can install it using the -i option followed by the name of the .deb package file.

sudo dpkg -i 2048-qt_0.1.6-2+b2_amd64.deb
Install Deb Package
Install the Deb Package

2. List Installed Packages on Ubuntu

To view and list all the installed packages, use the “-l” option along with the command.

dpkg -l
List Installed Deb Packages
List Installed Debian Packages

To view a specific package installed or not, use the option “-l” along with the package name. For example, check whether the apache2 package is installed or not.

dpkg -l apache2
Check Package Installation
Check Package Installation

3. Remove a Package on Ubuntu

To remove the “.deb” package, we must specify the package name “2048-qt” with the “-r” option, which is used to remove/uninstall a package.

sudo dpkg -r 2048-qt
Remove Deb Package
Remove Deb Package

You can also use ‘p‘ option in place of ‘r' which will remove the package along with the configuration file. The ‘r‘ option will only remove the package and not the configuration files.

[root@tecmint~]# dpkg -p flashpluginnonfree

4. View Contents of a .deb Package

To view the content of a particular .deb package, use the “-c” option, which will display the contents of a deb package in long-list format.

dpkg -c 2048-qt_0.1.6-2+b2_amd64.deb
View Contents of Deb Package
View Contents of Deb Package

5. Check Status of Deb Package Installation

Using “-s” option with the package name will display whether a deb package is installed or not.

dpkg -s 2048-qt
Check Deb Package Installation
Check Deb Package Installation

6. List Files Installed by Deb Package

To list the location of all the files installed by a particular package, use the -L option as shown.

dpkg -L 2048-qt
List Files Installed by Deb Package
List Files Installed by Deb Package

7. Install Multiple Debian Packages from a Directory

Recursively install all .deb files found in specified directories and all of their subdirectories, use the '-R' and '--install' options.

For example, to install all '.deb' packages from the directory named ‘debpackages‘.

sudo dpkg -R --install debpackages
Install All Deb Packages
Install All Deb Packages

8. Extract Contents of a Deb Package

To extract the contents of a .deb package but does not configure the package, use the --unpack option.

sudo dpkg --unpack 2048-qt_0.1.6-2+b2_amd64.deb
Extract Contents of Deb Package
Extract Contents of Deb Package

9. Reconfigure a Unpacked Deb Package

To configure a package that has been unpacked but not yet configured, use the “--configure” option as shown.

sudo dpkg --configure flashplugin-nonfree

10. Updating Package Information in System Database

The “–-update-avail” option replaces the old information with the available information for the package file in the package management system’s database.

sudo dpkg --update-avail package_name

11. Delete Information of Package

The action “--clear-avaial” will erase the current information about what packages are available.

sudo dpkg –-clear-avail

12. Forget Uninstalled and Unavailable Packages

The dpkg command with the option “–forget-old-unavail” will automatically forget uninstalled and unavailable packages.

sudo dpkg --forget-old-unavail

13. Display dpkg Licence

dpkg --licence

14. Display dpkg Version

The “--version” argument will display the dpkg version information.

dpkg –version

15. View dpkg Help

The “--help” option will display a list of available options of the dpkg command.

dpkg –help

That’s all for now. I’ll soon be here again with another interesting article. If I’ve missed any commands in the list, do let me know via comments.

Till then, stay tuned and keep connected to Tecmint. Like and share with us and help us spread. Don’t forget to mention your valuable thoughts in a comment.


Wednesday, May 7, 2025

5 Best Tools to Monitor and Debug Disk I/O Performance in Linux

https://www.tecmint.com/monitor-linux-disk-io-performance

5 Best Tools to Monitor and Debug Disk I/O Performance in Linux

Brief: In this guide, we will discuss the best tools for monitoring and debugging disk I/O activity (performance) on Linux servers.

A key performance metric to monitor on a Linux server is disk I/O (input/output) activity, which can significantly impact several aspects of a Linux server, particularly the speed of saving to or retrieving from disk, of files or data (especially on database servers). This has a ripple effect on the performance of applications and services.

1. iostat – Shows Device Input and Output Statistics

iosat is one of the many terminal-based system monitoring utilities in the sysstat package, which is a widely used utility designed for reporting CPU statistics and I/O statistics for block devices and partitions.

To use iostat on your Linux server, you need to install the sysstat package on your Linux system by running the applicable command for your Linux distribution.

sudo apt install sysstat          [On Debian, Ubuntu and Mint]
sudo yum install sysstat          [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux]
sudo emerge -a app-admin/sysstat  [On Gentoo Linux]
sudo apk add sysstat              [On Alpine Linux]
sudo pacman -S sysstat            [On Arch Linux]
sudo zypper install sysstat       [On OpenSUSE]    

To show a simple device utilization report, run iostat with the -d command line option. Usually, the first report provides statistics about the time since the system startup (boot time), and each subsequent report is concerned with the time since the previous report.

Use the -x for an extended statistics report and the -t flag to enable time for each report. Besides, If you wish to eliminate devices without any activity in the report output, add the -z flag:

iostat -d -t 
OR
iostat -d -x -t 
iostat - Monitor Device Statistics in Linux
iostat – Monitor Device Statistics in Linux

To display statistics in kilobytes per second as opposed to blocks per second, add the -k flag, or use the -m flag to display stats in megabytes per second.

iostat -d -k
OR
iostat -d -m

iostat can also display continuous device reports at x second intervals. For example, the following command displays reports at two-second intervals:

iostat -d 2

Related to the previous command, you can display n number of reports at x second intervals. The following command will display 10 reports at two-second intervals.

iostat -d 2 10

Alternatively, you can save the report to a file for later analysis.

iostat -d 2 10 > disk_io_report.txt &

For more information about the report columns, read the iostat man page:

man iostat

2. sar – Show Linux System Activity

sar is another useful utility that ships with the sysstat package, intended to collect, report, or save system activity information. Before you can start using it, you need to set it up as follows.

First, enable it to collect data in the /etc/default/sysstat file.

vi /etc/default/sysstat

Look for the following line and change the value to “true” as shown.

ENABLED="true"
Enable Sar in Linux
Enable Sar in Linux

Next, you need to reduce the data collection interval defined in the sysstat cron jobs. By default, it is set to every 10 minutes, you can lower it to every 2 minutes.

You can do this in the /etc/cron.d/sysstat file:

# vi /etc/cron.d/sysstat
Configure Sar Cron in Linux
Configure Sar Cron in Linux

Save the file and close it.

Finally, enable and start the sysstat service using the following systemctl command:

systemctl enable --now sysstat.service
systemctl start sysstat.service

Next, wait for 2 minutes to start viewing sar reports. Use the sar command and the -b command line option to report I/O and transfer rate statistics and -d to report activity for each block device as shown.

sar -d -b
Sar - Monitor Linux System Activity
Sar – Monitor Linux System Activity

3. iotop – Monitor Linux Disk I/O Usage

Similar to the top monitoring tool in terms of design, iotop is a simple utility that enables you to monitor disk I/O activity and usage on a per-process basis.

You can get it installed on your Linux server as follows (remember to run the appropriate command for your Linux distribution):

sudo apt install iotop             [On Debian, Ubuntu and Mint]
sudo yum install iotop             [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux]
sudo emerge -a sys-processs/iotop  [On Gentoo Linux]
sudo apk add iotop                 [On Alpine Linux]
sudo pacman -S iotop               [On Arch Linux]
sudo zypper install iotop          [On OpenSUSE]    

To monitor per-process I/O activity, you can run iotop without any arguments as follows. By default, the delay between iterations is 1 second. You can change this using the -d flag.

iotop
OR
iotop -d 2
iotop - Monitor Linux Disk Usage
iotop – Monitor Linux Disk Usage

iotop will by default display all threads of a process. To change this behavior so that it only shows processes, use the -P command line option.

iotop -P

Also, using the -a option, you can instruct it to display accumulated I/O as opposed to showing bandwidth. In this mode, iotop shows the amount of I/O processes performed since iotop was invoked.

iotop -P -a

4. dstat – Versatile Real-Time Resource Statistics

dstat is a powerful all-in-one replacement for older tools like vmstat, iostat, netstat, and others. It provides real-time stats for various system resources—including CPU, disk, memory, and network—in a clean, color-coded format.

To install dstat, use the relevant command for your Linux distro:

sudo apt install dstat             # On Debian, Ubuntu, and Mint
sudo yum install dstat             # On RHEL, CentOS, Fedora, Rocky Linux, AlmaLinux
sudo emerge -a sys-process/dstat   # On Gentoo Linux
sudo apk add dstat                 # On Alpine Linux
sudo pacman -S dstat               # On Arch Linux
sudo zypper install dstat          # On OpenSUSE

To run it with default settings (which includes CPU, disk, and network I/O):

dstat

If you want to focus only on disk activity, use:

dstat -d

You can also mix and match different options. For example, to monitor CPU, memory, and disk:

dstat -cdm

To log output to a CSV file for later analysis:

dstat -cdm --output system_stats.csv

dstat is super flexible and great for getting a quick, holistic view of your system in real time.

5. atop – Advanced System and Process Monitor

atop is like top, but on steroids, which gives you detailed, per-process resource usage, including disk I/O, memory, CPU, and network, making it great for in-depth analysis, especially when diagnosing performance issues over time.

Install it using your distro’s package manager:

sudo apt install atop             # On Debian, Ubuntu, and Mint
sudo yum install atop             # On RHEL, CentOS, Fedora, Rocky Linux, AlmaLinux
sudo emerge -a sys-process/atop   # On Gentoo Linux
sudo apk add atop                 # On Alpine Linux
sudo pacman -S atop               # On Arch Linux
sudo zypper install atop          # On OpenSUSE

To launch it:

atop

By default, it updates every 10 seconds. You can change the interval like this:

atop 2

One of its best features is that, it records data to a log file automatically (usually in /var/log/atop/).

atop -r /var/log/atop/atop_YYYYMMDD

It’s especially useful for tracing performance issues after they’ve already happened.

That’s all we had for you! We would like to know your thoughts about this guide or the above tools. Leave a comment via the feedback form below.

You can also inform us about tools that you think are missing in this list, but deserve to appear here.