Sign In
Sign In

How to Use DNF to Manage Packages on CentOS

How to Use DNF to Manage Packages on CentOS
Adnene Mabrouk
Technical writer
Linux
18.10.2024
Reading time: 4 min

DNF (Dandified Yum) is the next-generation version of Yum, the default package manager for CentOS and Fedora distributions. It is designed to resolve dependencies more efficiently, handle larger package sets, and improve performance over its predecessor. DNF simplifies the management of software packages by allowing users to install, update, and remove packages from the command line with a user-friendly interface.

Installing and Removing Packages with DNF

One of the primary functions of DNF is installing and removing software packages. To install a package using DNF, you need root or sudo privileges. The syntax is straightforward:

sudo dnf install package_name

For example, to install the Apache HTTP server:

sudo dnf install httpd

To remove a package, the command is similar:

sudo dnf remove package_name

For example, to remove Apache HTTP server:

sudo dnf remove httpd

Updating and Upgrading Packages

Keeping your system up to date is essential for security and performance. DNF makes this process simple. To update all the packages on your system, use:

sudo dnf update

This command will update installed packages to the latest versions available in the configured repositories. If you want to upgrade your entire system to the latest release (such as when moving between CentOS versions), you can use:

sudo dnf upgrade

The difference between update and upgrade is that the latter will also remove obsolete packages, whereas update does not.

Searching for Packages in DNF

DNF allows users to search for packages before installing them. This is helpful if you're unsure of the exact package name or want to explore available options. To search for a package:

sudo dnf search <keyword>

For example, to search for packages related to Apache:

sudo dnf search apache

DNF will list all packages that match the search term, along with a brief description.

Managing Repositories with DNF

Repositories are essential for managing where DNF pulls its packages from. DNF automatically handles repository configuration files, usually located in /etc/yum.repos.d/. You can add, enable, or disable repositories with DNF.

To add a new repository, you need to create a .repo file in /etc/yum.repos.d/. For example, let's say you want to add the EPEL (Extra Packages for Enterprise Linux) repository, which provides additional packages not available in the default CentOS repositories.

  • Install the EPEL repository using DNF

EPEL is available as a package that can be installed directly:

sudo dnf install epel-release

This command automatically creates the necessary .repo file and enables the EPEL repository.

  • Manually adding a repository

If you want to manually add a repository, you would create a .repo file, for instance, myrepo.repo, in /etc/yum.repos.d/, and add the following content:

[myrepo]
name=My Custom Repo
baseurl=http://example.com/repo/centos/$releasever/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://example.com/repo/RPM-GPG-KEY-myrepo

Here:

  • name specifies the name of the repository.

  • baseurl defines the URL from where the packages will be downloaded.

  • enabled=1 ensures the repository is active.

  • gpgcheck=1 enables GPG key checking for security.

  • gpgkey provides the URL to the GPG key used to verify the packages.

  • To disable the epel repository:
sudo dnf config-manager --set-enabled epel
  • To enable it again:
sudo dnf config-manager --set-enabled epel

Cleaning Up Unused Packages

Over time, your system may accumulate unnecessary packages and cache files, which take up valuable space. DNF includes a built-in command to clean up unused packages and free up disk space:

sudo dnf autoremove

This will remove any orphaned packages that are no longer required by the system. Additionally, you can clean up cached data using:

sudo dnf clean all

This command clears all cached package files stored in /var/cache/dnf/.

Troubleshooting DNF Issues

Occasionally, you may encounter issues when managing packages with DNF. Common problems include broken dependencies or repository errors. Here are some troubleshooting tips:

  1. Broken dependencies: If you're facing dependency issues, try running:

sudo dnf install --best --allowerasing

This command attempts to resolve conflicts by allowing DNF to erase conflicting packages.

  1. Corrupted cache: If the cache becomes corrupted, clean it up using:

sudo dnf clean metadata
  1. Failed transactions: If a DNF transaction fails, try rebuilding the database:

sudo rpm --rebuilddb

By using these tips, you can quickly resolve most issues you might face with DNF.

Conclusion

DNF is a powerful and efficient package manager that makes software management on CentOS easy. From installing and updating packages to managing repositories and cleaning up unused files, DNF provides a wide range of features to ensure your system runs smoothly. With this guide, you should be well-equipped to handle package management tasks on your CentOS system.

On Hostman, you can try Linux VPS hosting for your projects. 

Linux
18.10.2024
Reading time: 4 min

Similar

Mail

How to Send Email in Linux from the Command Line with Sendmail and Mailx

For those managing servers or working on automation tasks, knowing how to send emails from the Linux terminal is essential. It offers complete control over email functions and eliminates the need for complex mail programs. This is useful in scenarios where speed and simplicity matter most. Common tools such as sendmail and mailx are frequently used for sending messages, checking SMTP settings, automating alerts, and integrating with scripts. They are straightforward yet effective, making them perfect for tasks like informing teams about server updates, automating reports, or testing email setups. This guide is designed for users looking to manage their email directly from the terminal. It covers the installation of essential tools and delves into more advanced tasks, such as sending attachments and configuring email tools. Why Choose Command-Line Email Tools? Two commonly used tools, sendmail and mailx, are reliable options for mail transmission in Linux. They come with a certain set of benefits: Efficiency: Traditional email software can be slow and resource-intensive. These tools enable quick and lightweight email sending directly from the terminal. Automation: They integrate smoothly with shell scripts, cron processes, and system monitoring tools. Automating mail alerts and notifications for repeated actions is possible via these Linux mail tools. Troubleshooting SMTP Problems: Debugging SMTP setups becomes more manageable. These commands provide visibility into message delivery, ensuring mail logs and errors are easier to inspect. Flexibility: Whether it’s sending alerts or generating automated reports, command-line tools like sendmail and mailx offer versatility across a range of tasks. Prerequisites  Before utilizing these Linux mail command line tools, ensure you have terminal access. Root privileges may be required in some cases, especially for configuring each mail command on Linux discussed in this guide. Setting Up a SMTP Server SMTP servers are essential for sending emails. These servers fall into two categories: External and Local SMTP servers. External SMTP Servers It refers to a mail server hosted by a third-party provider. These servers are utilized to deliver emails over the internet to recipients who are not part of your local network. They are built to manage global mail delivery while ensuring proper authentication, encryption, and spam prevention. Examples  Gmail  Address: smtp.gmail.com Port: 587 (with TLS) or 465 (with SSL) Outlook  Address: smtp.office365.com Port: 587 These servers need appropriate authentication methods (such as a username, password, or app-specific passwords) and encryption (like TLS or SSL) to ensure secure communication. Note: We’ve already provided a guide for setting up external SMTP servers. The command to send emails through Postfix remains the same as mentioned in this article. Simply configure the SMTP settings using our guide, and replace the email address with Gmail or any other preferred provider for proper email delivery. Local SMTP Servers This server functions solely within a private network or system. It is perfect for: Sending emails between users on the same network or domain (e.g., tom@office.local to jerry@office.local). Local testing and development tasks. Internal communication within an organization. Does not need internet access to operate, as they manage mail delivery internally. Setting Up a Local SMTP Server Here are the procedures to set up a local SMTP server using Postfix: Install Postfix via: sudo apt install postfix Modify the Postfix configuration file: sudo nano /etc/postfix/main.cf Update or confirm these key settings: myhostname = mail.office.local mydomain = office.local myorigin = $mydomain inet_interfaces = loopback-only local_recipient_maps = proxy:unix:passwd.byname mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain Save and exit the file after doing changes, then restart Postfix: sudo systemctl restart postfix To create email addresses like linux@office.local and hostman@office.local, set up user accounts on the server: sudo adduser linuxsudo adduser hostman Overview of sendmail sendmail is a prominent mail transfer agent (MTA) in Linux. It works flawlessly with SMTP servers for mail delivery and allows emails to be sent and routed from local systems or scripts.  Installing sendmail  Before sending emails, you must install the Linux sendmail tool. Execute the commands below based on your distribution: For Debian/Ubuntu sudo apt install sendmail For CentOS/Red Hat sudo yum install sendmail Starting and Enabling Service Once installed, make sure sendmail is running and configured to start at boot: sudo systemctl start sendmailsudo systemctl enable sendmail Testing the Configuration Check the sendmail is set up correctly by executing: echo "Testing sendmail setup" | sendmail -v your-email@example.com Verify email by executing the mail command: mail Note: Install mailutils package in case the mail command is not working. sudo apt install mailutils Or utilize the cat command: cat /var/mail/user Editing the Configuration File To customize settings for sendmail, modify the configuration file located at /etc/mail/sendmail.mc: sudo nano /etc/mail/sendmail.mc Make the required changes to fit your server. For example, if you want to define the domain name for your server, you can add or modify the following line: define(`confDOMAIN_NAME', `your_domain.com')dnl Here, replace your_domain with your actual domain name. Then rebuild the configuration file: sudo m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf If a "permission denied" error occurs, use: sudo sh -c "m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf" Finally, restart the service: sudo systemctl restart sendmail Sending Email Via sendmail With sendmail, you can easily deliver emails, customize subjects, and even add attachments using external tools. Let’s go over the process to send emails: Basic Example To send an email with sendmail, use the below-given instructions: First, create a file to hold the message: nano email.txt Add any content to the file, for example: Subject: Test Email from HostmanThis is a test email sent using sendmail on Linux. Deliver the file's contents: sendmail recipient@example.com < email.txt The contents of email.txt will be sent to the designated recipient. For verification, apply: mail Adding Attachments  sendmail by itself doesn’t support attachments. You’ll need to utilize uuencode or similar tools to include files. First, install sharutils for uuencode: sudo apt install sharutils Here’s how to attach a file: ( echo "Subject: Email with attachment"; uuencode file.txt file.txt ) | sendmail recipient@example.com In the above sendmail example we send an email with file.txt attached. To verify, apply the Linux command mail: mail Overview of mailx  The mailx Linux command is a simple and effective terminal application for managing emails. It is included in the mailutils package found in most Linux distributions. Installing mailx  Install mailutils package on your system to utilize the mailx command on Linux: For Debian/Ubuntu systems sudo apt install mailutils For Red Hat-based systems sudo yum install mailx Sending Email with mailx This is a simple example demonstrating the use of mailx. Include a subject line and message in your email: echo "This is the body of the email" | mailx -s "Test Email from Mailx" recipient@example.com Utilize the Linux mail command for verification: Example with Attachments Use the -A flag with the mailx command to send emails from Linux with attachments: echo "Please find the attached document" | mailx -s "Email with Attachment" -A email.txt recipient@example.com This sends email.txt as an attachment to the recipient. Conclusion Sending email from the Linux command line is an effective method for automating communication tasks, troubleshooting servers, or testing configurations. Using tools such as sendmail and mailx, you can manage everything from simple messages to more complex setups with attachments. This guide has provided detailed instructions to help you begin without difficulty. Utilize these Linux email commands to improve your workflow. If you face any issues, feel free to refer back to this tutorial.
18 March 2025 · 7 min to read
Linux

How to Compress Files in Linux Using tar Command

The tar command basically functions to put together all files and directories into one archive without altering their structure. The approach simplifies organization, creation of the backup, and the transfer of files. Once packaged, you can compress these archives by using multiple ways such as using gzip, bzip2, or xz, which help optimize storage and enhance transfer speeds. Modern Linux distributions come with updated versions of tar, enabling seamless integration with compression tools like gzip for more efficient data handling. This makes tar a valuable asset for users managing large datasets, as it supports both file consolidation and compression in a single command. Thanks to its flexibility, tar is widely used across different Linux environments. It not only facilitates backup creation but also streamlines software distribution and the management of the important data. With an array of choices available, all users can customize archives according to their requirements, whether by excluding particular directories or files, preserving permissions, or securing sensitive data. For anyone dealing with extensive information or complex storage requirements, learning everything about the tar command is crucial. This all makes it an important utility to learn for Linux users. Understand the Syntax of tar  The tar command is fundamentally divided into four distinct parts: tar (keyword) -flags (options), used to execute a specific action name of the archive path to the desired file or directory It would be written as follows: tar -flags (archive_name) (path) Archiving Files and Directories tar used with the flag -cvf has the power to essentially archive the files and also the directories. For a File: tar -cvf collectionX.tar snake.txt For a Directory: tar -cvf DRcollection.tar newDir/ This would essentially archive the file snake.txt to collectionX.tar and the directory newDir to DRcollection.tar respectively.  If desired outcome is to archive multiple files and directories, then use the following commands.For Multiple Files: tar -cvf collectionX.tar snake.txt panther.txt Tiger.txt For Multiple Directories: tar -cvf DRcollection.tar newDir1/ newDir2/ newDir3/ Compressing Files and Directories tar used with the flag -czvf has the power to compress the files as well as the directories: For a File: tar -czvf collectionX.tar.gz snake.txt For a Directory:  tar -czvf DRcollection.tar.gz newDir/ -c archives the directories and files, -z pushes for gzip compression, -v is verbose which essentially shows what’s going on with compression, and -f allows to name the archive that is going to be compressed. Add .gz after tar, if you want to compress the files and directories. For Multiple Files: tar -cvf collectionX.tar.gz snake.txt panther.txt Tiger.txt  For Multiple Directories: tar -cvf DRcollection.tar.gz newDir1/ newDir2/ newDir3/ .bz2 used with tar and both used with -cjf allow to archive and compress files and directories. -j applies bzip2 compression. For a File (with bz2): tar -cjf collectionX.tar.bz2 snake.txt For a Directory (with bz2): tar -cjf DRcollection.tar.bz2 newDir/ .xz used with .tar and both used with -cJf allow you to archive and compress files and directories. In -cJf, -J means compress with xz. For a File (with xz): tar -cJf DRcollection.tar.xz file1.txt For a Directory (with xz): tar -cJf collectionX.tar.xz newDir/ Extracting Compressed .tar Files arch1.tar.gz, arch1.tar.bz2 and arch1.tar.xz are three compressed files. Extract tar.gz: tar -xvzf arch1.tar.gz -x stands for file extraction. Extract tar.bz2: tar -xvjf arch1.tar.bz2 Extract tar.xz: tar -xvJf arch1.tar.xz Extracting Specific Files Using Wildcards If you need to extract only a specific type of file out of an archive, do this: tar -xvf arch1.tar --wildcards '*.sh' It will give you only the files with .sh extension. --wildcards help search that specific type of file and enable pattern matching while *.sh ensures that you only extract the .sh type of files. Extracting to a Specific Directory If you need to extract the complete archive to a specific directory, do this: tar -xvf arch1.tar -C ./destinationDir/pathDir/ -C changes to the specified directory path and -xvf helps extract the archive there.  Managing .tar Archives Check Contents without Extracting If you need to know what's inside an archive but don't want to uncompress files, use commands like this: tar -tzf arch1.tar.gztar -tjf arch1.tar.bz2tar -tJf arch1.tar.xz -t gives details about what’s inside the compressed archives without performing extraction on it. Appending Files to an Existing Archive To append a new file to an archive: tar -rvf arch1.tar new.sh new.sh will be added to arch1.tar. That’s how you append a file into an existing archive.  Removing a Specific File from an Archive What if you need to delete a file from an archive without having to extract it, it can be done by using --delete. tar --delete -f arch1.tar new.sh  This will remove the file new.sh from the archive arch1.tar without extracting it.  Note that --delete does not work on the compressed files, only on archives.  Comparing Archive Contents with Current Directory If you have to examine the contents of your current working directory and compare them with the archive? use: tar --diff -f arch1.tar --diff will help compare the contents of arch1.tar with the content available in the present working directory. Troubleshooting Common .tar Errors "tar: Removing leading '/' from member names" This warning appears when absolute paths are used in an archive: tar -cvf arch1.tar /home/user/file.txt Solution: Use -p to preserve absolute paths. tar -cvpf arch1.tar /home/user/file.txt "tar: Error opening archive: Unrecognized archive format" This error occurs when the archive is corrupt or the wrong decompression command is used. Solution: Verify the file type: file arch1.tar.gz Use the correct decompression command: tar -xvzf arch1.tar.gz  # For .tar.gztar -xvjf arch1.tar.bz2  # For .tar.bz2tar -xvJf arch1.tar.xz   # For .tar.xz If corruption is suspected, check integrity: gzip -t arch1.tar.gzbzip2 -tv arch1.tar.bz2 Conclusion The tar utility serves as an important tool for archiving, compression and extraction. It provides efficiency, making it a crucial component of Linux storage management. With a variety of configurations and settings, tar functions as an evergreen solution catering to diverse use scenarios. Options such as -czvf and -xvzf determine the way files are stored and retrieved, granting users complete control over data compression. Furthermore, tar supports multiple compression tools like gzip, bzip2, and xz, allowing users to optimize both speed and compression ratio based on their specific needs. For Information Technology professionals, developers, and Linux users, learning everything about tar is invaluable. Whether it’s for managing backups, distribution of data effectively, or optimizing storage, tar is by far one of the most influential archiving tools. By selecting the right configurations and commands, users can significantly enhance their workflow, automate tasks, and efficiently handle large datasets.
12 March 2025 · 6 min to read
Linux

How to Use the Screen Utility in Linux

The Screen utility is a Linux window manager that allows you to switch between multiple processes in a single physical terminal. Screen provides a scrollable history buffer and a mechanism for copying and pasting text between windows. With Screen, you can create new windows with different programs, close the current windows, view a list of active windows, enable and disable output logging, and switch between windows. All windows work independently, and programs continue to run even when the session is disconnected from the user's terminal. This makes Screen a useful tool for efficiently managing multiple tasks in a single terminal. Installing the Screen Utility The Screen may be pre-installed in the operating system or require separate installation depending on the distribution. To install Screen, use the following command: For Ubuntu and Debian: apt install -y screen For CentOS and Fedora: yum install -y screen Or: dnf install -y screen Basic Commands Let's go over the basic commands for managing Linux Screen sessions. Starting a Screen Session To start Screen, simply enter the following command in your terminal: screen This will open a Screen session, create a new window, start a shell in it, and you will see a new window. Press Enter to proceed to enter commands. Creating a Named Session You can name your sessions, which is especially useful when working with multiple Screen sessions. To create a named session, use the following command: screen -S session_name It’s always helpful to choose a descriptive name for the session. Detaching from a Screen Session in Linux To detach from a Screen session at any time, type: Ctrl+a d The program running in the Screen session will continue to run in the background after you detach. Reattaching to a Screen Session in Linux To resume your Screen session, use the command: screen -r If you have multiple Screen sessions running, you need to specify the session ID or its name after the -r parameter. To see the list of currently running sessions, use: screen -ls You will see a list of sessions like this: There are screens on: 1468393.hostman (01/25/2025 02:07:34 PM) (Detached) 1466624.pts-3.1495851-user (01/25/2025 01:54:05 PM) (Detached) 2 Sockets in /run/screens/S-linuxize. To resume the session with ID 1466624.pts-3.1495851-username, enter: screen -r 1466624 To resume a session using its name, type: screen -r session_name Additional Options Screen offers a variety of useful features for convenient session management in the terminal.  You can customize each window to suit your needs, such as adjusting its size according to display settings or configuring options using a custom configuration file.  You can also pause a session and resume it later or run Screen in daemon mode to keep it running in the background.  Additionally, you can customize command keys, manage data flow, and enable logging.  It's also possible to switch between windows, change their titles, and use UTF-8 encoding, making terminal work more comfortable and adaptable to different tasks. Screen options: -a: Enables all possible features for each window, maximizing functionality. -A -[r|R]: Automatically adjusts all windows to fit the new screen width and height. -c file: Specifies an alternate configuration file instead of the default .screenrc. -d (-r): Detaches the current Screen session without terminating it so that you can reconnect later. -D (-r): Terminates the active connection to a remote session, but the session itself remains running and can be resumed. -D -RR: Takes all necessary actions to reconnect to an existing Screen session if one is available. If not, it starts a new one. -e xy: Changes the default keybindings for Screen commands to custom ones, which is useful for avoiding conflicts with other programs. -f: Enables data flow control; -fn disables it; -fa enables automatic flow control, which is helpful when working with large amounts of data. -h lines: Sets the scrollback buffer size, allowing you to scroll through more command history. -i: Interrupts data output on the screen when flow control is enabled, preventing terminal overload. -l: Logs session information to the system log to keep track of active sessions; -ln disables this. -ls [pattern]: Displays a list of all active Screen sessions currently connected. -L: Enables logging of all terminal output to a log file. -p window: Automatically selects the specified window on startup if it exists. -q: Runs Screen in “quiet” mode, suppressing unnecessary error messages. -V: Displays the version of Screen and then exits. -r [session]: Reconnects to a previously started but detached Screen session. -R: If an existing session is found, it reconnects to it; if not, it starts a new one. -S session_name: Assigns a name to the new session, making it easier to reconnect to it later. -t title: Sets a title for the window, which is displayed in the window list. -U: Enables UTF-8 encoding support for text display. -v: Displays the current version of the Screen program. -x: Attaches to an active session, allowing it to be used simultaneously on multiple screens. -X: Executes the specified command within an active Screen session. Working with Screen Windows You can work with multiple Screen sessions simultaneously, with several windows open for each session. To create a new window with a shell, press: Ctrl+a c The window will be automatically assigned a number from 0 to 9. Below are the common commands for managing windows in Screen: Ctrl+a c — Create a new window (with a shell). Ctrl+a " — Display a list of all windows. Ctrl+a 0 — Switch to window 0 (by number). Ctrl+a A — Rename the current window. Ctrl+a S — Split the current region horizontally into two regions. Ctrl+a | — Split the current region vertically into two regions. Ctrl+a tab — Move the input focus to the next region. Ctrl+a Ctrl+a — Toggle between the current and previous windows. Ctrl+a Q — Close all regions except the current one. Ctrl+a X — Close the current region. To see all commands, enter: Ctrl+a ? When Screen starts, it reads its configuration settings from /etc/screenrc and ~/.screenrc, if they exist. You can customize Screen's default settings to suit your preferences using the .screenrc file. This example includes a custom status line and several additional options: # Disable the startup message startup_message off # Automatically detach from the session when the connection is lost autodetach on # Set the scrollback buffer to 10,000 lines defscrollback 10000 # Enable logging for the current session logfile /path/to/screenlog Additional recommendations for customizing Screen configuration: Automatic Window Splitting on Startup Useful if you frequently work with multiple windows and want them to open automatically when Screen starts. screen -t shell1 split focus screen -t shell2 Logging All Sessions Useful for keeping a record of work. deflog on logfile $HOME/.screen/screenlog.%t Automatic Reconnection on Disconnection Useful when working with unstable connections. autodetach on reattach on Examples of Using Screen Example 1: To monitor file changes in real-time, you can use two Screen windows: one for editing the file and another for displaying its content using the command: tail -f filename This allows you to instantly see all changes made without having to re-run the command. Example 2: When working in a terminal over SSH using a Screen session, you won’t lose data if the connection is interrupted. Even if the connection drops, you can reconnect and resume work exactly where you left off by simply reattaching to the Screen session. Example 3: For long-running tasks, such as compiling code or performing a backup, you can start the task in one Screen session and monitor its progress. You can safely disconnect anytime, knowing the task will continue running. Later, you can reconnect to the session to check the results. Conclusion In this guide, we covered how to use Linux Screen to manage terminal sessions effectively. You learned how to: Create multiple windows within a single session. Switch between windows. Manage sessions, including detaching and resuming them. We also discussed how to customize the terminal using the .screenrc configuration file to make your work environment more convenient and personalized. You can now use Screen for a more comfortable and productive terminal experience by mastering these basic features. For more information about Screen, check out the Screen user's manual.
20 February 2025 · 7 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support