43% found this document useful (7 votes)
7K views566 pages

Official CompTIA Linux+ Student Guide

Uploaded by

Tapos Mondal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
43% found this document useful (7 votes)
7K views566 pages

Official CompTIA Linux+ Student Guide

Uploaded by

Tapos Mondal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 566

The Official

CompTIA
Linux+
Student Guide
(Exam XK0-005)

Linux+_XK0-005_TTL_ACK_ppi-ii.indd 1 28/04/22 1:56 PM


Course Edition: 1.0

Acknowledgments

Damon Garn, Author


Becky Mann, Director, Product Development
James Chesterfield, Senior Manager, User Experience and Design
Katherine Keyes, Senior Specialist, Product Development

Notices
Disclaimer
While CompTIA, Inc. takes care to ensure the accuracy and quality of these materials, we cannot guarantee their accuracy,
and all materials are provided without any warranty whatsoever, including, but not limited to, the implied warranties of
merchantability or fitness for a particular purpose. The use of screenshots, photographs of another entity’s products, or
another entity’s product name or service in this book is for editorial purposes only. No such use should be construed to imply
sponsorship or endorsement of the book by nor any affiliation of such entity with CompTIA. This courseware may contain links
to sites on the Internet that are owned and operated by third parties (the “External Sites”). CompTIA is not responsible for
the availability of, or the content located on or through, any External Site. Please contact CompTIA if you have any concerns
regarding such links or External Sites.

Trademark Notice
CompTIA®, Linux+®, and the CompTIA logo are registered trademarks of CompTIA, Inc., in the U.S. and other countries.
All other product and service names used may be common law or registered trademarks of their respective proprietors.

Copyright Notice
Copyright © 2022 CompTIA, Inc. All rights reserved. Screenshots used for illustrative purposes are the property of the software
proprietor. Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed
in any form or by any means, or stored in a database or retrieval system, without the prior written permission of CompTIA,
3500 Lacey Road, Suite 100, Downers Grove, IL 60515-5439.
This book conveys no rights in the software or other products about which it was written; all use or licensing of such software
or other products is the responsibility of the user according to terms and conditions of the owner. If you believe that this
book, related materials, or any other CompTIA materials are being reproduced or transmitted without permission, please call
1-866-835-8020 or visit https://help.comptia.org.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_TTL_ACK_ppi-ii.indd 2 28/04/22 1:56 PM


Table of Contents | iii

Table of Contents

Lesson 1: Introducing Linux............................................................................................. 1

Topic 1A: Identify Linux Characteristics.............................................................. 2

Topic 1B: Understand Bash Interaction with Linux............................................ 9

Topic 1C: Use Help in Linux.................................................................................. 20

Topic 1D: Identify the Linux Troubleshooting Methodology........................... 24

Lesson 2: Administering Users and Groups................................................................. 31

Topic 2A: Manage User Accounts........................................................................ 32

Topic 2B: Manage Group Accounts..................................................................... 43

Topic 2C: Configure Privilege Escalation............................................................ 47

Topic 2D: Troubleshoot User and Group Issues................................................. 54

Lesson 3: Configuring Permissions............................................................................... 61

Topic 3A: Configure Standard Linux Permissions............................................. 62

Topic 3B: Configure Special Linux Permissions................................................. 74

Topic 3C: Configure Access Control Lists............................................................ 77

Lesson 4: Implementing File Management.................................................................. 83

Topic 4A: Understand the Linux File System..................................................... 84

Topic 4B: Use File Management Commands...................................................... 92

Topic 4C: Find File Locations.............................................................................. 108

Lesson 5: Authoring Text Files..................................................................................... 119

Topic 5A: Edit Text Files...................................................................................... 120

Topic 5B: Manage Text Files............................................................................... 128

Lesson 6: Managing Software...................................................................................... 139

Topic 6A: Understand Software Management................................................ 140

Topic 6B: Manage RPM Software Packages and Repositories....................... 145

Topic 6C: Manage Debian-based Software Packages and Repositories....... 157

Table of Contents

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_TOC_ppiii-vi.indd 3 09/06/22 4:14 PM


iv | Table of Contents

Topic 6D: Compile from Source Code................................................................ 162

Topic 6E: Acquire Software................................................................................ 165

Topic 6F: Run Software in a Sandbox................................................................ 168

Lesson 7: Administering Storage................................................................................. 173

Topic 7A: Understand Storage........................................................................... 174

Topic 7B: Deploy Storage.................................................................................... 179

Topic 7C: Manage Other Storage Options........................................................ 197

Topic 7D: Troubleshoot Storage........................................................................ 205

Lesson 8: Managing Devices, Processes, Memory, and the Kernel......................... 215

Topic 8A: Gather Hardware Information......................................................... 216

Topic 8B: Manage Processes.............................................................................. 223

Topic 8C: Manage Memory................................................................................. 234

Topic 8D: Manage the Linux Kernel.................................................................. 239

Lesson 9: Managing Services....................................................................................... 251

Topic 9A: Manage System Services................................................................... 252

Topic 9B: Configure Common System Services................................................ 263

Topic 9C: Configure Localization Settings........................................................ 277

Lesson 10: Configuring Network Settings.................................................................. 285

Topic 10A: Understand Network Fundamentals............................................. 286

Topic 10B: Manage Network Settings............................................................... 292

Topic 10C: Configure Remote Administrative Access..................................... 305

Topic 10D: Troubleshoot the Network............................................................. 313

Lesson 11: Configuring Network Security.................................................................. 327

Topic 11A: Configure the Firewall..................................................................... 328

Topic 11B: Monitor Network Traffic................................................................. 337

Table of Contents

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_TOC_ppiii-vi.indd 4 09/06/22 4:14 PM


Table of Contents | v

Lesson 12: Managing Linux Security........................................................................... 355

Topic 12A: Harden a Linux System.................................................................... 356

Topic 12B: Manage Certificates......................................................................... 363

Topic 12C: Understand Authentication............................................................ 369

Topic 12D: Configure SELinux or AppArmor..................................................... 375

Lesson 13: Implementing Simple Scripts................................................................... 385

Topic 13A: Understand Bash Scripting Basics.................................................. 386

Topic 13B: Use Shell Script Elements................................................................ 390

Topic 13C: Implement Scripts with Logical Controls...................................... 401

Lesson 14: Using Infrastructure as Code.................................................................... 419

Topic 14A: Understand Infrastructure as Code............................................... 420

Topic 14B: Implement Orchestration............................................................... 424

Topic 14C: Manage Version Control with Git................................................... 429

Lesson 15: Managing Containers in Linux.................................................................. 437

Topic 15A: Understand Containers................................................................... 438

Topic 15B: Deploy Containers............................................................................ 441

Topic 15C: Understand Virtualization Concepts.............................................. 448

Lesson 16: Installing Linux........................................................................................... 453

Topic 16A: The Linux Boot Process.................................................................... 454

Topic 16B: Modify Boot Settings........................................................................ 462

Topic 16C: Deploy Linux..................................................................................... 468

Appendix A: Mapping Course Content to CompTIA Linux+ (Exam XK0-005)...........A-1

Appendix B: Linux Command Reference Guide..........................................................B-1

Solutions......................................................................................................................... S-1

Glossary...........................................................................................................................G-1

Index................................................................................................................................. I-1

Table of Contents

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_TOC_ppiii-vi.indd 5 09/06/22 4:14 PM


LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_TOC_ppiii-vi.indd 6 09/06/22 4:14 PM


1
About This Course
CompTIA is a not-for-profit trade association with the purpose of advancing the
interests of IT professionals and IT channel organizations; its industry-leading IT
certifications are an important part of that mission. CompTIA’s Linux+ certification
is an intermediate-level certification designed for professionals with at least 12
months of hands-on experience working with Linux servers in a junior Linux
support engineer or junior cloud/DevOps support engineer job role. In addition,
the knowledge gained in CompTIA’s A+, Network+, and Server+ courses, or the
equivalent, is strongly recommended.
The CompTIA Linux+ certification exam will verify the successful candidate
has the knowledge and skills required to configure, manage, operate, and
troubleshoot Linux in on-premises and cloud-based server environments while
using security best practices, scripting, containerization, and automation.

CompTIA Linux+ Exam Objectives

Course Description
Course Objectives
This course can benefit you in two ways. If you intend to pass the CompTIA Linux+
(Exam XK0-005) certification examination, this course can be a significant part of
your preparation. But certification is not the only key to professional success in
the field of systems administration. Today’s job market demands individuals with
demonstrable skills, and the information and activities in this course can help you
build your sysadmin skill set so that you can confidently perform your duties in any
intermediate-level Linux systems administration role.
On course completion, you will be able to:
• Configure, manage, and troubleshoot Linux systems.

• Operate Linux in both on-premises and cloud-based server environments.

• Implement security best practices.

• Use scripting, containerization, and automation to optimize a Linux system.

Target Student
The Official CompTIA Linux+ (Exam XK0-005) is the primary course you will need to
take if your job responsibilities include Linux system administration, installation,
and security within your organization. You can take this course to prepare for the
CompTIA Linux+ (Exam XK0-005) certification examination.

Prerequisites
To ensure your success in this course, you should have at least 12 months of
hands-on experience working with Linux servers. CompTIA A+, Network+, and
Server+ certifications, or the equivalent knowledge, are strongly recommended.

The prerequisites for this course might differ significantly from the prerequisites for
the CompTIA certification exams. For the most up-to-date information about the exam
prerequisites, complete the form on this page: www.comptia.org/training/resources/
exam-objectives.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Preface_ppvii-x.indd 7 28/04/22 11:12 AM


viii | Preface

How to Use the Study Notes


The following notes will help you understand how the course structure and
components are designed to support mastery of the competencies and tasks
associated with the target job roles and will help you prepare to take the
certification exam.

As You Learn
At the top level, this course is divided into Lessons, with each representing an area
of competency within the target job roles. Each Lesson is composed of a number of
topics. A Topic contains subjects that are related to a discrete job task and mapped
to objectives and content examples in the CompTIA exam objectives document.
Rather than follow the exam domains and objectives sequence, lessons and topics
are arranged in order of increasing proficiency. Each topic is intended to be studied
within a short period (typically 30 minutes at most). Each topic is concluded by one
or more activities, designed to help you apply your understanding of the study
notes to practical scenarios and tasks.
In addition to the study content in the lessons, there is a glossary of the terms and
concepts used throughout the course. There is also an index to assist in locating
particular terminology, concepts, technologies, and tasks within the Lesson and
topic content.

In many electronic versions of the book, you can click links on key words in the topic
content to move to the associated glossary definition and on page references in the
index to move to that term in the content. To return to the previous location in the
document after clicking a link, use the appropriate functionality in your eBook viewing
software.

Watch throughout the material for the following visual cues.

Student Icon Student Icon Descriptive Text


A Note provides additional information, guidance, or hints about a
topic or task.

A Caution note makes you aware of places where you need to be


particularly careful with your actions, settings, or decisions so that
you can be sure to get the desired results of an activity or task.

As You Review
Any method of instruction is only as effective as the time and effort you, the
student, are willing to invest in it. In addition, some of the information that you
learn in class may not be important to you immediately, but it may become
important later. For this reason, we encourage you to spend some time reviewing
the content of the course after your time in the classroom.
Following the lesson content, you will find a table mapping the lessons and topics to
the exam domains, objectives, and content examples. You can use this as a checklist
as you prepare to take the exam and review any content that you are uncertain
about.

About This Course

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Preface_ppvii-x.indd 8 28/04/22 11:12 AM


Preface | ix

As a Reference
The organization and layout of this book make it an easy-to-use resource for future
reference. Guidelines can be used during class and as after-class references when
you’re back on the job and need to refresh your understanding. When taking
advantage of the glossary, index, and table of contents, you can use this book as a
first source of definitions, background information, and summaries.

How to Use the CompTIA Learning Center


The CompTIA Learning Center is an intuitive online platform that provides access
to the eBook and all accompanying resources to support The Official CompTIA
curriculum. The CompTIA Learning Center can be accessed at learn.comptia.org.
An access key to the CompTIA Learning Center is delivered upon purchase of the
eBook.
Use the CompTIA Learning Center to access the following resources:
• Online Reader: The interactive online reader provides the ability to search,
highlight, take notes, and bookmark passages in the eBook. You can also access
the eBook through the CompTIA Learning Center eReader mobile app.

• Videos: Videos complement the topic presentations in this study guide by


providing short, engaging discussions and demonstrations of key technologies
referenced in the course.

• Assessments: Practice questions help to verify your understanding of the


material for each lesson. Answers and feedback can be reviewed after each
question or at the end of the assessment. A timed Final Assessment provides
a practice-test-like experience to help you determine how prepared you feel to
attempt the CompTIA certification exam. You can review correct answers and full
feedback after attempting the Final Assessment.

• Strengths and Weaknesses Dashboard: The Strengths and Weaknesses


Dashboard provides you with a snapshot of your performance. Data flows into
the dashboard from your practice questions, final assessment scores, and your
indicated confidence levels throughout the course.

About This Course

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Preface_ppvii-x.indd 9 28/04/22 11:12 AM


LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Preface_ppvii-x.indd 10 28/04/22 11:12 AM


Lesson 1
Introducing Linux
1

LESSON INTRODUCTION
Working with Linux begins with an understanding of licensing and the operating
system’s history. The open-source nature of Linux has resulted in many different
distributions, so it’s important to understand how distributions differ from each
other. Linux servers are primarily managed from the command line, using shells
such as Bash. Bash enforces a particular syntax, or way of structuring commands.
In addition, Linux holds its configurations in text files, so it’s critical that sysadmins
can edit these files to manage system settings. Man pages are available as
quick reference documents to help administrators recall the function of specific
commands and any available options.
Misconfigurations or physical failures may provide troubleshooting opportunities,
so sysadmins should follow a standard methodology to help narrow the scope of
problems, solve the root cause of the issue, and manage documentation related to
configuration issues.

Lesson Objectives
In this Lesson, you will:
• Identify Linux characteristics.

• Understand basic interaction with Linux.

• Use help documentation in Linux.

• Identify the troubleshooting methodology.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 1 03/06/22 3:36 PM


2 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 1A
Identify Linux Characteristics
2

EXAM OBJECTIVES COVERED


This topic provides background information about the history and features of Linux and
does not cover a specific exam objective.

Linux is characterized by a free and open-source software licensing approach,


which makes the operating system freely distributable and encourages the release
of modified versions. These versions are known as distros or distributions. Distros
are purpose-specific combinations of the Linux OS and particular applications
geared toward supporting defined goals, such as enterprise services, database
management, or virtualization hosting. Finally, Linux is distinctive for frequently
being managed from a command-line interface, which is often more efficient and
easier on resources, rather than a graphical interface.

Characteristics of Free and Open-Source Software


Much of today’s software is closed-source software, or proprietary software
that’s released under copyright law. These laws restrict intellectual property,
such as closed-source software, from duplication and re-release by competitors.
Open-source software takes a different approach.
In general, software licensed as open-source can be duplicated, shared, and
modified, and the modified versions can be released to consumers. Code licensed
as free and open-source software (FOSS) can be used and changed without cost.
In fact, changes are encouraged as a form of improvement, even by individuals who
do not work for the original developers. Any changes must also be made available
and released for free.

Some examples of open-source licenses include the Apache License 2.0, the GNU
General Public License, and Mozilla's Public License. While the exam does not focus on
the specifics of these licenses, they are a good sample of the open-source requirements
and permissions.

The History and Philosophy of Unix and Linux


Unix is one of the oldest operating systems still in use. It was created in 1969, and it
was not released as open-source software. Instead, Unix versions were associated
with many different tech organizations, including IBM, Hewlett-Packard, and AT&T.
These various Unix versions are referred to as Unix “flavors” and were proprietary
to each company.
In 1991, Linus Torvalds created a new Unix-like operating system kernel. He
released this kernel, which he called Linux, under the GPL license. The Linux
kernel, as well as much of the software released with it, is open-source; it can be
modified, shared freely, and re-released. This collaborative approach allows Linux
to grow and evolve rapidly. As a result of this approach, there are now more than
200 Linux versions, or distributions (abbreviated “distros”).

Lesson 1: Introducing Linux | Topic 1A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 2 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 3

Of the three primary operating systems in the marketplace today (Linux, macOS,
and Windows), two can trace their roots back to Unix. The macOS kernel evolved
from a Unix flavor named BSD and shares many of the same standards and some
software as Linux. However, Apple’s OS is not FOSS. Microsoft Windows also uses a
proprietary kernel with a more restrictive licensing method.

The timeline of early OS development. Unix, released in 1969, directly generated the Linux and the
macOS systems.

Traits of the Linux Operating System


Like any operating system, Linux has characteristics that may or may not fit the
needs of a given organization. Here are a few general considerations:
• Free: No licensing fees or tracking associated with most Linux distributions.

• Security: Because of the open-source nature of Linux and its associated


software, many developers can and do review code for vulnerabilities. Such
vulnerabilities tend to be addressed quickly.

• Support: Community-driven support may provide easy, efficient, and cost-


effective solutions. However, support may be limited to the community, without
a strong corporate support structure implemented by the distribution’s vendor.

• Performance: Linux often provides greater performance and stability compared


to other operating systems.

• Software availability: Fewer or less familiar software options may exist,


especially for nonbusiness applications, such as games.

• Hardware requirements: Linux may consume fewer hardware resources,


making it easier to retain older systems for longer.

• Hardware flexibility: Linux runs on a wide variety of hardware platforms,


adding to its flexibility in areas such as Internet of Things (IoT). Specialized
hardware may require specific drivers that may not exist for Linux.

• Learning curve: Some find that Linux has a steeper learning curve than
Windows or macOS does.

Lesson 1: Introducing Linux | Topic 1A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 3 03/06/22 3:36 PM


4 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

• Distribution creation: If existing Linux distributions do not fit your needs,


you are welcome (and encouraged) to create your own. The sheer number and
purpose of Linux distributions can be confusing and overwhelming. There is
not a big name in the marketplace that represents Linux and lends it a sense of
stability.

Understand Linux Distributions


Because anyone can create and release their own version of Linux, there are
thousands of different options. These individual releases are called distributions
(or “distros” for short). Distributions are purpose-specific versions of Linux that
address a specific need, such as system security or application hosting.
Many distributions trace their history back to one of two specific Linux distributions:
Red Hat Linux or Debian Linux. One of the main differentiators between these two
distros is how they manage software. Those distros derived from Red Hat Linux use
different software managers than those derived from Debian Linux. The software is
also packaged differently.

Software management, including more differences between the Red Hat method and the
Debian method, are discussed in a later section.

Some of the most common distros include:


• Fedora Linux

• Ubuntu Desktop, Server, Core

• Red Hat Enterprise Linux (RHEL)

• Linux Mint

• Debian

• openSUSE

After the release of Linux in 1991, the two major branches, Debian and Red Hat, followed quickly
and generated hundreds of distros.

Lesson 1: Introducing Linux | Topic 1A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 4 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 5

Many of these distributions fulfill specific roles in the marketplace, including


desktop or workstation computer, server, IoT device, mobile device, or other
functions. While mobile and IoT implementations are common, the focus of this
course is on server deployments. One of the most important characteristics of a
distribution is its included software.
Some distributions contain end-user applications, such as word processors or
presentation software. Others contain server services, such as web services or file
storage. Still other distributions include security software or creative applications,
such as music editing.
Linux server deployments are put to use in the following ways:
• Webserver: Hosts one or more websites.

• Name resolution: Hosts Domain Name System (DNS) name resolution services.

• File: Stores business data, usually in some form of text document.

• Print: Manages the print process and access to print services.

• Log: Centralizes and stores log files from other systems.

• Virtualization/container: Hosts virtual machine or container virtualization


software.

• Database: Hosts one or more databases.

• Cluster: Works with other cluster nodes to host high-performance, fault-tolerant


services.

Linux is heavily involved in newer forms of infrastructure management. A DevOps


approach to the management of such Linux servers and services works toward high
quality, iterative, and frequent updates and releases. Linux tends to include security
in design and implementation throughout the development lifecycle (this approach
is sometimes called DevSecOps).

Most commands are consistent across distributions. A few commands, such as those
for software management, may be specific to one group of distributions or another. For
example, Red Hat Linux uses the rpm command to manage software, while Debian
Linux uses apt.

The Command-Line Interface


One distinguishing characteristic of Linux compared to other operating systems is
its reliance on the command-line interface (CLI). Linux administrators frequently
use the CLI for everyday tasks, while administrators of other platforms often use
graphical user interface (GUI) utilities. In fact, the installation of a GUI is often
optional with Linux and may be frowned upon for performance and security
reasons.
A GUI consumes a great many hardware resources, specifically memory and
processor time. On a server, these resources should be dedicated to the service
provided, such as handling database queries or managing print jobs. Desktop
systems might need a user-friendly GUI but servers usually do not.
CLI advantages:
• Quicker: It’s usually quicker to execute a series of commands at the CLI
(assuming you know the commands).

Lesson 1: Introducing Linux | Topic 1A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 5 03/06/22 3:36 PM


6 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

• Performance: CLI environments consume fewer hardware resources, leaving


those resources free to support the server’s purpose.

• Scriptable: CLI commands can be written into a text file, which the system then
reads and executes in a consistent, efficient, repeatable, and scheduled manner.

CLI disadvantages:
• Learning curve: Remembering many different commands and their related
options is difficult.

• Nonintuitive: Commands are often difficult to relate to or understand, with no


apparent logic.

• Inconsistent: Many commands differ from each other in small but distinctive
ways, making it difficult to recall exactly how to use them.

Common CLIs
Command-line interfaces are available in Linux, Windows, and macOS. Users type
commands using a specific syntax, and the system processes the commands. At
first, such input may seem intimidating or difficult, but CLI environments get easier
with use. These environments are usually faster and offer automation options that
are not available in GUIs.

Several sample commands and their output, including whoami, pwd, and date.

Shells provide the CLI. Each shell has its own syntax, or way of structuring
commands.
Common Linux shells:
• Bash: Default Linux shell

• ksh: Korn shell

• zsh: Z shell

These shells are differentiated by their syntax and user-friendly features.

The Bash shell is covered in more detail later in this Lesson. It is the only shell covered
by the CompTIA Linux+ exam objectives.

Lesson 1: Introducing Linux | Topic 1A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 6 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 7

Common GUIs
Just as there are many different Linux distributions, there are also many different
Linux graphical environments. Windows and macOS users have one GUI available
to them—whatever graphical environment Microsoft and Apple choose to provide.
Linux users have the freedom to install zero, one, or many GUI environments and
switch between them.
These GUIs are usually distinguished by two characteristics: user-friendly interface
and performance. Some users like the look and feel of a particular GUI over others.
In addition, some GUIs consume more processor time and memory than others do.
Luckily, many options are available in the Linux world.
Common GUI environments include GNOME, KDE Plasma, Cinnamon, and MATE.

Example of a GUI with running apps and menus.

Another important attribute of Linux GUIs is support for graphics-based


applications, such as web browsers, presentation software, and image-editing
programs. These types of software are critical to today’s business environments and
users.
Linux graphical interfaces provide many accessibility features that are worth
exploring. Some of these include high-contrast displays, screen readers, magnifiers,
visual alerts, and keyboard sticky keys.

Lesson 1: Introducing Linux | Topic 1A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 7 03/06/22 3:36 PM


8 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
3

Linux Characteristics
Answer the following questions:

1. Compare the advantages and disadvantages of GUI and CLI


environments.

2. Explain how distributions differ from each other.

3. Why do servers tend to rely on CLI administration and desktops rely on


GUI environments?

4. How might anyone contribute improvements to a piece of free and


open-source software?

Lesson 1: Introducing Linux | Topic 1A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 8 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 9

Topic 1B
Understand Bash Interaction
with Linux
5

EXAM OBJECTIVES COVERED


1.2 Given a scenario, manage files and directories.

Command-line administration relies on interfaces called shells. The default Linux


shell is Bash, which has a particular syntax, or way of structuring commands. The
syntax includes commands, command modifiers called options, and arguments.
Bash also includes features such as tab completion and a history file. There are
several common commands, directories, and applications available on most Linux
systems, including the Vim and Nano text editors. Bash also supports privilege
escalation. A solid understanding of Bash and its syntax makes Linux administration
much easier.

Command Shells
The CLI is provided by software called a shell. The shell accepts user input,
processes the input for syntax, and provides output back to the user. The default
shell for most Linux distributions is Bash, and this is the shell that sysadmins
should be prepared to work with.
Other common Linux shells include ksh, or KornShell, which is common among
Unix servers; Zsh, or Z Shell, with quite powerful scripting capabilities; and Fish, or
friendly interactive shell, an interface that provides a user-friendly experience and
web-based configurations.
By way of comparison, Windows Server also uses shells: the traditional, DOS-like
cmd.exe shell and Microsoft PowerShell. The current (at the time of this writing)
default shell for macOS is the Zsh.

Bash is the Linux default and the only shell to concern yourself with for CompTIA Linux+.

Bash Characteristics and Syntax


Commands must be entered into Bash using a specific structure, or syntax. Each
component of the syntax has a name to make it easier to understand.
The syntax components are:
• Command: The primary instruction given to the system.

• Subcommand: A secondary, more detailed instruction supporting the


primary command.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 9 03/06/22 3:36 PM


10 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

• Option: A command modifier that slightly changes the way a command is processed.

• Argument: The object on which the command acts. For example, in a command
to delete a file, the argument is the name of the file to be deleted.

There are two basic forms, normal command and command-subcommand, to this
syntax.

Normal Command Syntax


The normal command syntax relies on the three primary components of the Bash
syntax: the command, options to modify the command, and an argument for the
command to act upon.

Observe that there is a space between each of the three components!

As an example, here are several ways to use the list (ls) command with options
and arguments.

Normal Command Syntax for


the ls Command Purpose
ls List directory contents.

ls -la List all (-a) directory contents in long format


(-l).
ls /var/log List the contents of the /var/log directory.
ls -la /var/log List all contents of the /var/log directory
in long format.

Most Bash error messages are descriptive, so be careful to read the error message to
understand what went wrong.

Command-Subcommand Syntax
Many Linux commands support subcommands to specify particular information
that the sysadmin needs. These commands rely on a different syntax from the basic
format in normal command syntax. The sysadmin enters the primary command,
then follows it with a space and a subcommand, and then a space and argument.
The ip command uses this format.

Command-Subcommand Syntax for


the ip Command Purpose
ip addr Display all IP addresses for all
interfaces.
ip addr show eth0 Display only IP address information for
the eth0 interface.
ip help Display basic help about the ip
command.
ip link help Display help about the ip link
subcommand.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 10 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 11

The ip command showing address information for the eth0 interface.

Use Basic Bash Commands


There are many Bash commands. Some of the most often-used commands deal
with file management functions, such as displaying files and file contents, moving
from one directory (or folder) to another, or editing files.

It is customary in Linux to refer to folders as "directories."

Use Common Commands


The following commands exemplify the Bash syntax and enable users to begin
working with the files and directories that make up Linux. These commands are
used throughout this course and will quickly become familiar.

Example with
Command Purpose Options Result
ls List the contents of the ls /tmp List the contents of
current directory the /tmp directory
touch Create a new empty file touch Create a new file
or update the timestamp newfile.txt named newfile.txt
on an existing file
cd Change from one cd /etc Changes the
directory to another current directory
to /etc
cat Display the contents of a cat data.txt Display the
text file on the screen contents of the
data.txt file
less Display the contents of a less Display the
file in windows that fit on data.txt contents of the
the screen data.txt file screen
at a time when
the file would not
normally fit on one
screen
tree Display the directory tree /etc Display the
structure in a tree subdirectories and
format files in the /etc
directory in a tree
structure
shutdown Shut down the system shutdown Restart the system
-r now immediately

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 11 03/06/22 3:36 PM


12 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Two common commands do not use options to generate an output. Use whoami
to display the current user, and use pwd to display the present working directory.

Command line interface showing the output of ls, pwd, whoami, and touch.

The number of Bash commands can be overwhelming. Start by using a few commands
at a time, and make them a habit. The longer you work with Linux, the more
comfortable you’ll become with the commands.

Use Bash Tab Completion and History


Bash supports tab completion. Users can type in enough of a command to make
it unique from any other command. Select the Tab key, and Bash automatically
completes the command. This feature also works with file and directory names. Tab
completion reduces typographical errors and increases speed at the CLI.
Bash also keeps a record of previously entered commands in a history file. This file
can be referenced and used to repeat or edit commands.
The simplest way to work with history is by using the Up and Down Arrow keys.
Select the Up Arrow key one time to recall the most recently used command. You
can cycle through the command history by pressing Up Arrow or Down Arrow
multiple times. Select Enter once the appropriate command is displayed.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 12 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 13

Typing the history command displays the contents of the history file. Each entry in
the file is numbered. Type ! and the command number executes that command.

Retrieving a past command with the history command.

Some shells cache command history in memory. When the system is rebooted, the
commands are no longer available. Bash writes the command history to a file stored on
the hard disk. The commands are available even after multiple reboots.

Shell Tips and Tricks


Tab completion and history can make working in Bash far more efficient and less
frustrating. Try to get comfortable using both features as quickly as possible, along
with trying these other tips for easier use:
• Tab completion: Get in the habit of using tab completion for speed and to
minimize typographical errors.

• Use command history instead of rewriting long commands: When you make
a typographical error in a command or file name, do not manually retype the
entire line. Repeat the line with the mistake by hitting the Up Arrow key one
time, and then use the Left and Right Arrow keys to move to the mistake so that
you can correct it.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 13 03/06/22 3:36 PM


14 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

• Read the command backward: When troubleshooting your commands, start


from the right and read to the left. This method makes it a great deal easier to
notice missing or duplicate characters.

• Clear the screen: Enter the clear command to clear the CLI of all text. This
is useful when you’re starting a new task and want to eliminate any distracting
information from past command entries.

Introducing Vim and Nano


Linux stores its configurations in text files. When a sysadmin needs to change
system settings, these text files must be edited. There are many familiar text
editors in GUIs, but what about Linux systems that do not have a graphical interface
available, such as Linux server installations?
Two standard text editors exist that are run from the CLI and do not need a mouse
or graphical interface: Vim and Nano. Here is a very brief overview of using these
two editors.

Vim
Vim is very powerful and complex. It uses three different modes, where each
mode maps keyboard keys to different functions. For example, in Insert mode
the keyboard acts as normal, inserting text into the file. If you’re in Insert mode
and type “abc,” those three characters appear in the file’s content. In Command
mode, pressing a key on the keyboard issues commands to Vim instead of entering
text in the file. Selecting the i key tells Vim to switch from Command mode to
Insert mode. The third mode is Execute. This mode is entered by selecting the
colon character, : , and it provides a command prompt to Vim where additional
commands can be issued. For example, :wq places Vim in Execute mode, writes
the files to the disk (save), and then quits Vim (q).
The many modes and commands can make Vim a little confusing. Strive to
understand four basic functions: create/open, edit, save, close.

Function Command Result


Create/Open vim filename Create a new empty file, or open an
existing file in Vim.
Edit i Enter Insert mode, and begin making
edits.
Save ESC and :w Move out of Insert mode and into
Command mode, and then save (write)
changes.
Close ESC and :q Move to Command mode, and then exit.

For efficiency, type :wq to combine the save and close options.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 14 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 15

The Vim editor. Note the INSERT flag in the lower left corner.

Vim is covered in more detail in Lesson 5. A summary is provided here to permit


immediate editing of text files if necessary.

Nano
Nano is a popular and common alternative to Vim. It’s simpler but less powerful.
However, in many cases sysadmins don't need the power offered by Vim, which
makes Nano a useful choice for basic editing functions.
Nano does not have modes. Pressing keys on the keyboard inserts text into the
file, just as expected with most editors. To save and close the file, use keyboard
shortcuts using the Ctrl meta key. For example, Ctrl+O saves the file, and
Ctrl+X exits the file. You may have used similar keyboard shortcuts in other
applications.
As with Vim, it’s critical that you are capable of using Nano to create or open, edit,
save, and close files.
• Type nano filename to create a new empty file or open an existing file with
Nano.

• To edit the file, simply begin typing. Use the arrow keys to move the cursor.

• Type Ctrl+O to save changes.

• Type Ctrl+X to exit Nano after saving changes.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 15 03/06/22 3:36 PM


16 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The Nano editor. Note the menu at bottom of the window.

Nano is covered in more detail in Lesson 5. A summary is provided here to permit


immediate editing of text files if necessary.

Some Linux distributions install both Vim and Nano by default, while others will
include only one or the other. It is essential for you to be able to use both editors at
a very basic level (open, edit, save, close) so that you are capable of editing files with
whichever tool is available.

Introducing su and sudo


There are three types of accounts on Linux systems: root, standard user, and
service.
The administrator account in Linux is called root. Logging in to the system with
administrator access is frowned upon. The security best practice is to log on with
a standard user account, and then, if necessary, switch your user account to root.
The command to accomplish this is su.
Type su root to switch from the standard user to root.
Type exit to leave the root user and return to the standard user.
Type su - root to switch from the standard user to root with the root profile.
Note that there is a space on each side of the dash character. Again, type exit to
close the root login and return to the standard user account login.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 16 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 17

Elevate privileges from standard user to root, and confirm the change with
the whoami command.

The problem with the su - root command is that it grants all administrative
privileges to the escalating user, assuming the user knows the root password.
In other words, the user is either a non-privileged account with almost no
administrative authority or the full root user account with all possible administrative
authoring—and nothing in between. Sometimes, administrators want to delegate
specific, defined activities that require root authority, but only those particular
activities.
Sysadmins can edit a file named /etc/sudoers to delegate specific tasks to
individual users and groups. The specified identity may exercise that task as if
they are root, but nothing else. This is a much safer alternative than giving full
root privileges to individuals who may not be fully qualified to run the system. This
delegation concept is critical to good security.
To accomplish a delegated task, simply precede the command with sudo. You will
usually be prompted for your password and given a warning to be careful on the
system. The command then executes.
As a security measure, some distributions disable the root user account and force
the use of sudo on specific user accounts.

Privilege escalation using su and sudo are covered in more detail in a later Lesson.
A summary is provided here in case it’s needed for hands-on activities.

Identify Common Directories


With so many Linux distributions available, administrators rely on the Filesystem
Hierarchy Standard to understand the default location of particular resources.
There are three common directories that administrators work with on a regular
basis.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 17 03/06/22 3:36 PM


18 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

• /home/username: Each standard user has a specific and private directory used
to store personal files, profile settings, and other data. These user directories are
subdirectories of /home.

• /etc: Most system configuration files are stored in the /etc directory.

• /var/log: Log files for the system and applications are stored in the /var/log directory.

Use the command ls /home to display a few existing user directories.

There are many other standard directories, and they are covered in a later Lesson.

Log In Using the GUI and CLI


If the Linux system is configured to boot to the CLI (or doesn’t have a GUI at all),
users are prompted for a username and password. After entering these two values,
the system authenticates the account and loads profile settings from files stored in
the user’s home directory.

Logging in from the command line.

If the system boots to the GUI, a login prompt is displayed that may show available user
accounts. A password is entered, and then the user is authenticated. Profile settings
related to the GUI—such as desktop backgrounds and menu items—are then loaded.

Logging in from a GUI.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 18 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 19

Review Activity:
Interact with Linux
6

Answer the following questions:

1. An administrator asks you to make a change to the system’s


configuration. Why would you need to use Vim or Nano to accomplish
this task?

2. What types of files will be found in the /etc directory?

3. Explain the difference between the su and sudo commands.

Lesson 1: Introducing Linux | Topic 1B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 19 03/06/22 3:36 PM


20 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 1C
Use Help in Linux
4

EXAM OBJECTIVES COVERED


This topic covers the foundational concepts of documentation and does not address a
specific exam objective.

Linux includes strong built-in documentation in the form of manual pages,


which provide brief explanations of the command, available options, and a few
examples. They are short, concise references. It is essential that sysadmins become
comfortable accessing and using manual pages. More significant documentation
may be built into applications, stored on the system, or available online at vendor
websites.

Linux Documentation
There are several ways of getting help in Linux. The most common are the manual
pages, referred to as “man pages” for short. There is built-in documentation for the
system and some applications, too. Many online resources also exist, and they are
often the most up to date.
Because there are so many commands, and because each command has so many
options, it’s very common to use the man pages as a quick reference for displaying
the available options.

Manual Pages
It’s common for new Linux users to ask for help and then be asked, “Did you check
the man pages?” That’s because man pages are the primary reference for standard
Linux commands. The man pages provide syntax information and usage examples.
Perhaps most important, the available options are displayed. Because of the
number of options for each command, and the fact that many options differ from
command to command, the man pages provide an essential quick reference.
The syntax for using man pages is man {command}.
For example, to display help for the ls command, type man ls.

Obtaining help for the ls command, using the man pages.

Man Page Sections


Man pages are organized into eight sections. A section defines what category the
command belongs to. These sections are displayed by a number following the
command. For example, fsck (8) indicates that the fsck command is found in
section eight.

Lesson 1: Introducing Linux | Topic 1C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 20 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 21

The man page for fsck.

Note that the numbers in this list are man page section numbers, not merely
part of the list. In other words, “System calls” is in Section 2 of the man pages
documentation, not just the second item in this grouping.
Section eight is probably the most commonly used section for administrators.

It is not necessary to memorize the section numbers. Sometimes it can be useful to


recognize what section might contain the man page for a given command. If you're
interested in a deeper dive into the conventions and configurations of man pages, take
a look at the man-pages project website.

man Page Navigation


You can use several different keys to navigate through the man pages, all mapped
to specific actions.
Home -- Move to the beginning of the man page.
End -- Move to the end of the man page.
Page Up -- Scroll up one page.
Page Down -- Scroll down one page.
/ -- Begin a search for a term or text string.
n -- Move to the next occurrence of the search term.
p -- Move to the previous occurrence of the search term.
q -- Exit the man page, and return to the shell.
For example, to search for the string “directory” in the ls man page, open the man
page and then type a forward slash character and the word “directory.”
$ man ls
/directory
The first line opens the man page for ls, and the second line searches the keyword
directory.

Built-In Documentation
Most commands include help references. Add the -h option, or help after the
command to display this reference material.
The whatis command provides a brief description of the specified command.
The syntax for whatis is whatis {command}.

Lesson 1: Introducing Linux | Topic 1C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 21 03/06/22 3:36 PM


22 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Finally, built-in documentation can be found at /usr/share/doc. This


directory contains some Linux and application help files. Not all applications
store documentation at this location, but it’s worth checking.

Online Documentation
There is a great deal of information available online that covers Linux
administration, applications, security configurations, and network services. This
documentation may be provided by vendors, community groups, online forums,
article repositories, and other sites.
• Linux distribution vendors: Vendors such as Red Hat and Ubuntu have large
repositories of reference information.

• Linux application vendors: Vendors for products such as Apache web server,
Vim, and Firefox provide many references for their applications.

• Linux Documentation Project: This is a community project dedicated to


providing documentation for Linux, including how-to documents, man pages,
and guides. These references are found at https://tldp.org/.

Lesson 1: Introducing Linux | Topic 1C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 22 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 23

Review Activity:
Help in Linux
5

Answer the following questions:

1. Name three things a man page might provide a user.

2. Why might vendor websites be the best source of information about an


application or service?

Lesson 1: Introducing Linux | Topic 1C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 23 03/06/22 3:36 PM


24 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 1D
Identify the Linux Troubleshooting
Methodology
3

EXAM OBJECTIVES COVERED


This topic covers the foundational concepts of troubleshooting and does not address a
specific exam objective.

One of the primary skills and duties of a systems administrator is to troubleshoot


problems with servers, the network, and data access. It is important to have a
methodology for troubleshooting. You should also recognize that troubleshooting
methods may change by situation, skill level, and experience with the network
environment.

Troubleshooting Methodology
A formalized and consistent troubleshooting methodology can make identifying
issues and discovering fixes more efficient. While the steps can vary depending
on the actual issue and components involved, there are several universal
troubleshooting steps.
The following list represents the basic steps in a troubleshooting methodology:
• Identify the problem.

• Determine the scope of the problem.

• Establish a theory of probable cause/question the obvious.

• Test the theory to determine the cause.

• Establish a plan of action.

• Implement the solution or escalate the issue.

• Verify full system functionality.

• Implement preventive measures.

• Perform a root cause analysis.

Throughout the process you will find it helpful to document findings, actions, and
outcomes of the various steps.

Identify the Problem and Determine the Scope


Identify the Problem
The first troubleshooting phase is to identify the problem. The problem may be
discovered for you by the end users you support, exposed by log files, identified
by monitoring software, or indicated by lights on the server. There are many ways
through which the problem may be detected. Once a problem is identified, a service
desk ticket is used to track it.
Lesson 1: Introducing Linux | Topic 1D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 24 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 25

Determine the Scope of the Problem


Once a problem is identified, gather additional information to determine the
scope of the problem. Start this process by asking users for additional details or
examining log files. Attempt to replicate the problem by asking users to show you
what they were doing when the problem was encountered or to try to recreate
the situation where the problem first arose. It is a good practice to back up data
if there is any risk to the data during the troubleshooting phase. You must use
your own judgment as to whether a data backup is necessary before you begin
troubleshooting. Finally, consider whether you have the skills to address the
problem or if you need to escalate the service desk ticket to another administrator.
One of the most important steps is to determine whether the problem exists
on only one server or on multiple servers. The scope of the problem could be
hardware based and, if so, may be isolated to that device. It could be network
based, in which case, multiple devices may be affected. It could be software based,
such as a misconfiguration or a bug. This also may impact multiple servers.
For example, if one workstation cannot access a file server, but all other
workstations can, the problem likely lies with that workstation. If many workstations
cannot access the file server, the problem likely lies with that server or with the
network between the workstations and the server.

In Linux, the log file service is named "rsyslog." Services are covered in Lesson 9.

Establish and Test a Theory of Probable Cause


Establish a Theory of Probable Cause: Question the Obvious
The next troubleshooting phase is to establish a probable cause for the problem.
It is essential to keep this step as simple as possible. Troubleshooting often begins
with very basic steps, such as confirming that the system is plugged in and powered
on. More complex problems may require you to examine log files, talk to users or
other administrators, or check the hardware.
When troubleshooting, identify any common elements or similar problems that might
span multiple servers or network devices. Such common elements might include a
new or updated piece of software, a new device driver, or a new configuration.
Check for any recent changes to the environment. These changes may have been
implemented by another IT staff member or a stakeholder, such as a manager or
other user. Recent changes are common culprits for issues.

Test the Theory to Determine the Cause


Next, test the theory by verifying that the likely cause is indeed the culprit. This
phase involves research or other testing. Very simple problems may actually be
solved during this step. If your theory is confirmed, then move on to the next phase,
which is to establish a plan of action. If your theory is not confirmed, then you must
establish and test a new theory.

Establish and Implement a Plan of Action


Establish a Plan of Action
The plan of action for addressing the problem must recognize that service
interruptions and data loss should be avoided. If a server needs to be brought
Lesson 1: Introducing Linux | Topic 1D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 25 03/06/22 3:36 PM


26 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

down to replace hardware, or if data has been lost due to a HDD failure, the end
users must be notified. The plan of action defines the steps to be taken. These steps
should be defined ahead of time rather than created during the implementation of
the solution. It is useful to provide the impacted users with an expected duration of
the outage.

Implement the Solution or Escalate


In this phase, follow the plan of action established earlier. It is important not to
deviate from the plan. You may not have the knowledge to implement the plan and
need to escalate the problem to the vendor’s support team or other members of
your own team.
When following a plan of action, be sure to only make one change at a time, and
then test the result. If you make multiple changes simultaneously, it is difficult to
identify exactly which change corrected the problem. If a given change does not
solve the problem, reverse that change, and then try another option.

Verify, Prevent, Analyze, and Document


Verify Full System Functionality
Once the potential solution has been implemented, the next phase is to test for
functionality. Your goal is to ensure that the server has returned to the service
levels that are defined by the system parameters. The server performance baseline
that you performed during the deployment portion of the server lifecycle will be
very useful as a comparison.

Implement Preventive Measures


It may be possible to preemptively reconfigure other servers to avoid a repeat of
the same problem. It may also be possible to implement additional technologies
(such as a redundant array of independent/inexpensive disks [RAID]) or additional
practices (such as backups) to prevent future instances of failure. In some cases,
additional training or documentation may also be necessary.

Perform a Root Cause Analysis


Once service is restored to your users, it is time to evaluate why the problem
occurred. Identifying the root cause permits you to change processes or implement
different technologies to avoid the problem in the future.

Document Findings, Actions, and Outcomes Throughout


the Process
Documenting the symptoms of the problem, the results of research into potential
solutions, and the results of each step of the plan of action (whether the step
was successful or not) permits you to understand your environment better and
therefore helps to prevent possible future problems. Note that documentation
is not a separate step but rather a good practice used during each phase of the
troubleshooting process.

Some service desk management software requires the use of tickets. Such software may
require that troubleshooting documentation be entered before the ticket can be closed.

Lesson 1: Introducing Linux | Topic 1D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 26 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 27

Review Activity:
Troubleshoot in Linux
4

Answer the following questions:

1. A user contacts you to find out why they cannot access a directory. Using
the troubleshooting methodology, how would you narrow the scope of
the problem?

2. When should you escalate a problem?

3. True or False? Documentation should be created only at the end of the


troubleshooting process.

Lesson 1: Introducing Linux | Topic 1D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 27 03/06/22 3:36 PM


28 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Lesson 1
Summary
4

By understanding how open-source licensing allows many Linux distributions to


exist, it is easier to differentiate between Linux and other operating systems. Linux
is widely used with various hardware, but one of its most common roles is as a
server OS. Servers need to maximize the use of available hardware resources, so
Linux is often managed via the Bash shell rather than a graphical interface. Bash is
more hardware-efficient and allows tasks to be scripted and scheduled.
Command-line administration has its challenges, however, especially when
managing system configurations through text files. Applications such as the
Vim text editor are used to edit these files, resulting in updated settings. Text
editors and Bash commands may be difficult to remember and often rely on
one or more options to modify their behavior. Administrators use built-in man
pages to reference command functions and options. Often, such references are
made as part of a larger troubleshooting methodology that attempts to provide
comprehensive and effective problem-solving.

Guidelines
These best practices and guidelines are provided for your use as revision tools or as
quick references in your job role.
• FOSS: Recognize and describe free and open-source software, including
advantages and disadvantages.

• GPL: Understand how the GPL influences the development and availability of the
Linux OS.

• Distributions: Understand what a distribution is and how distributions differ


from each other.

• GUI vs CLI: Understand the advantages and disadvantages of each environment.

• Use Vim and Nano to open, edit, save, and close files.

• Recognize both command syntax structures:

• command -option argument

• command subcommand argument

Lesson 1: Introducing Linux

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 28 03/06/22 3:36 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 29

Command Reference Table


This list of commands and their associated syntax can also be found in Appendix B.

Command Syntax Purpose Covered in


ls ls [option] List the contents of the Lesson 1, Topic B
current directory.
cat cat Display the contents of Lesson 1, Topic B
[file-name] a text file on the screen.

cd cd /etc Change from one Lesson 1, Topic B


directory to another.
pwd pwd Displays the present Lesson 1, Topic B
working directory.
whoami whoami Displays the username Lesson 1, Topic B
of the current user.
touch touch Create a new empty file Lesson 1, Topic B
[file-name] or update the times-
tamp on an existing file.
man man Display manual, or help, Lesson 1, Topic C
[command] pages for a specific
command.
whatis whatis Provides a brief Lesson 1, Topic C
[command] description of the
specified command.

Practice Questions: Additional practice questions are available on the CompTIA


Learning Center.

Lesson 1: Introducing Linux

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 29 03/06/22 3:36 PM


LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson01_pp001-030.indd 30 03/06/22 3:36 PM


Lesson 2
Administering Users and Groups
1

LESSON INTRODUCTION
Modern operating systems require users to prove their identity. This identification
process, referred to as authentication, provides access to major functions. First, the
user’s identity can be used to control access to resources via permissions and other
rules. Second, the user’s environment can be customized to fit that individual’s work
style and habits.
The first task is to understand user account management, including its related
configuration files and commands. However, managing individual users can be
inefficient, so users are often placed into groups for simplicity. Group management
involves a different set of configuration files and commands. Next, administrators
should log on to the server with non-privileged accounts and then elevate privileges
only when necessary. The administration of privilege elevation and its related
commands is covered in the third Topic. Finally, this lesson will cover applying
configuration files and commands in troubleshooting and security auditing.

Lesson Objectives
In this lesson, you will:
• Manage user accounts.

• Manage group accounts.

• Configure privilege escalation.

• Troubleshoot user and group issues.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 31 28/05/22 11:04 AM


32 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 2A
Manage User Accounts
2

EXAM OBJECTIVES COVERED


2.2 Given a scenario, implement identity management.

Sysadmins are responsible for, among other things, managing user accounts. These
accounts customize the user environment and provide access to resources. It’s
difficult to administer user accounts effectively without a solid understanding of the
files and tools used to manage accounts. This Topic covers user configuration files
and management commands.

User Configuration Files


Like most Linux settings, user accounts are stored in text files. However,
administrators do not simply edit these text files directly to manage user accounts.
Instead, specific applications are used to create, modify, and remove user accounts
on the Linux system. It’s still important to know what files maintain user account
information.

User Account Storage


Two files store user account data: /etc/passwd and /etc/shadow. Note
that both of them are stored in the /etc directory, where most Linux configuration
files reside. The /etc/passwd file stores the actual user account and maintains
various settings related to accounts. The /etc/shadow file stores password
information for the accounts.

Field Content
User Name The name the user logs into the system with
Password User password represented as an x; the actual password is
stored elsewhere
User ID Unique number representing the user to the system
Group ID Unique number representing the user’s primary group
Comment Typically displays the user’s full name
Home directory Absolute path to the user’s home directory
Login shell Absolute path to the user’s default shell (usually /bin/bash)

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 32 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 33

The /etc/shadow file. Note the long string representing the hashed password.

Field Content
User name The name the user logs into the system
with
Password Hash value of the user’s password
Days since last password change Number of days since the last password
change; counted from January 1, 1970
Days before password may be Minimum changeable period, typically
changed set at 1 day
Days before password must be Maximum number of days since the last
changed password change before the password
must be changed again; a value of
99999 means the password never
needs to be changed, but often set at
90 days
Days until the user is warned to Days before the date the password
change password must be changed that the warning is
issued, often set to 7 days
Days after password expires that Number of days after the password
the account is disabled expires until the account is disabled;
should be immediate
Days until account expires Number of days until the account
expires and cannot be used
Unused field Reserved for potential future use

It may seem odd that account information is distributed across two files and that
specifically password information is stored in a different file than user accounts.
Passwords were originally stored in the second field of the /etc/passwd file.
This file, however, is “world-readable,” meaning that all users have read permissions
to the file. The password itself, or the encrypted version of it, could be viewed by all
users. To increase security, the password was moved to the /etc/shadow file,
which only the root user (administrator) can access.
The default shell setting, defined in the last field of the /etc/passwd file,
specifies which shell will launch when the user logs in. There are many different
shells, and some users may prefer one over another. Bash is the default shell and
therefore the most common.
For example, User1 has experience with several Unix flavors and is already familiar
with the Korn shell (ksh). The sysadmin may install ksh and set it as the default shell
for this user. The last field of the User1 line in /etc/passwd will read /bin/
ksh. User2, however, might be more comfortable with the Bash shell. In that case,
the sysadmin leaves the default shell value as /bin/bash.

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 33 28/05/22 11:04 AM


34 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

System and User Profiles


Users are allowed to define preferred settings within a CLI environment. Each
user may have a custom profile tailored to their unique preferences. System
administrators may also define profiles to provide required settings to all users on
the system. Additionally, shell features such as command history are unique to each
user and stored in the individual user’s home directories.
As a sysadmin, you can use a few different files to set the system up the way your
institution prefers. Use /etc/profile to set system-wide environment variables
and startup programs for new user shells. Use /etc/bashrc to establish
system-wide functions and aliases for new user shells.
Users can customize their preferred settings as well. The ~/.bash_profile sets
user-specific environment variables for new Bash shells, and ~/.bashrc runs
when noninteractive shells are launched.

The tilde character (~) represents the current user's home directory. For example, the
~ character means the same as /home/user1 (assuming user1 is the currently
logged-in user).

The system-wide files process first, and then the user-specific files are executed.
The user-specific configuration files take precedence over system files, allowing
users to customize their environments to suit their needs.
Finally, a sysadmin can store files in the /etc/skel directory and have those files
copy automatically to the home directory of any new user. This feature is useful for
pre-populating configuration files such as .bashrc with suggested settings for users
or for distributing policy documents all users should have access to.

Account Management Commands


There are three primary commands for managing user accounts in Red Hat–based
distributions. The useradd command creates users, while usermod modifies
existing users and userdel removes existing users. Many Debian-based
distributions also recognize these commands, but they support the adduser
command as well.

The user management lifecycle, including adding, modifying, and deleting a user.

Options for useradd


By default, the user management commands rely on the /etc/login.defs
file to define default account settings, including home directory location, preferred
shell, and account expiration values.
The /etc/login.defs file contains the user mailbox location, password aging
values, the UID and GID ranges, home directory creation, the default umask, and
the password encryption hash.

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 34 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 35

The default values found in the /etc/login.defs file can be overridden with
various options, providing administrators with flexibility. Common options include
the comment field or default shell settings.
Some common options for the useradd command include:

Option for the useradd Command Purpose


-c Set the comment value, usually the user’s
full name.
-e Set an expiration date for the user
account, format YYYY-MM-DD.
-m Create a user home directory in /home.

-s Set a default shell for the user.

-u Set a specific user ID value.

-D Display the default settings.

The syntax for using useradd is useradd -options argument


For example, if you are asked to create a new user account; define its full user
name; set it to expire on December 31, 2025; and configure the Korn shell as the
default, the command would look like this:
useradd -c "Kai Garcia" -e 2025-12-31 -s /bin/ksh
kgarcia
Confirm that the new user has been created by displaying the last line in the
/etc/passwd file.

Observe that the comment value is enclosed in double quotes. The quotes cause Bash to
recognize the enclosed information as a single object. If the quotes did not exist, the first
name would be seen as a separate item from the last name, resulting in an error.

Set a Password
The useradd command creates the user but does not set a password. Most
Linux systems will not allow a user to log in with a blank password, so while the
account exists, it is not yet usable. The passwd command sets passwords for user
accounts.
The syntax for using passwd is passwd [username]
Helpdesk Ticket #01982
Submitted by: Department: Assigned to: Date Opened:
Kai Garcia Engineering you 2024-03-08

Subject Forgot Password


Ticket Detail Hi, can you please reset my password?
Thank you,
KG
Date last updated 2023-03-08

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 35 28/05/22 11:04 AM


36 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

For example, to reset Kai Garcia’s password, type passwd kgarcia

Resetting the password for the kgarcia account.

You are prompted to enter a new password twice. Use the passwd command to
configure a password for a new account as well as to reset a forgotten password for
an existing user.

The adduser Command


Some Linux distributions use the adduser command instead of useradd.
Some systems recognize both. The adduser command prompts administrators
for details, including home directory locations and full names. Perhaps most
importantly, adduser prompts sysadmins to set a user password. The adduser
command can be added to a Linux system.

The adduser command walks the admin through each field of the user account information.

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 36 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 37

Modify and Delete User Accounts


Of course, the sysadmin doesn’t only make new accounts. A new policy might
require sysadmins to update some users’ accounts from time to time, or a user’s
preference might change. Just as you add new users when they onboard, you must
remove user accounts during the offboarding process to ensure the integrity of the
system.

The usermod Command

Helpdesk Ticket #01983

Submitted by: Department: Assigned to: Date Opened:


Anna Tanaka HR you 2024-03-29

Subject Account changes


Ticket Detail A recent security audit shows that the account for temporary
employee Alex Lee should expire on December 31, 2025.
Another finding is that the comment field for Joseph Deng’s
account is blank but should be populated in the usual
manner, “firstname lastname.” Please update.
Date last updated 2024-03-30

Modify these existing user accounts by using the usermod command. In these
two cases, the commands will look like this:
# usermod -e 2025-12-31 alee
# usermod -c "Joseph Deng" jdeng
Helpdesk Ticket #01984
Submitted by: Department: Assigned to: Date Opened:
Kai Garcia Engineering you 2024-04-01

Subject Change default shell


Ticket Detail Can you change my default shell to Ksh? I’m much more
comfortable with Unix and Ksh over Bash.
Thank you,
KG
Date last updated 2024-04-01

You’ll update Kai Garcia’s default shell like this:


# usermod -s /bin/ksh kgarcia

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 37 28/05/22 11:04 AM


38 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The userdel Command

Helpdesk Ticket #01985

Submitted by: Department: Assigned to: Date Opened:


Anna Tanaka HR you 2024-11-25

Subject Personnel update


Ticket Detail Effective today, Alex Lee is no longer with the company. Please
disable Alex’s account, but hold on to the data until we can
reassign it to other team members.
Date last updated 2024-11-25

The userdel command removes existing users from the system. By default, the
command does not remove the user’s home directory. This is important, as the user
data may need to be assigned to other users. However, the -r option can be added
to the command to remove the account and its associated home directory.
The syntax for using userdel is userdel {user-name}
For example, to delete the Alex Lee account, type userdel alee
Neither the usermod nor userdel commands will modify users if the accounts
have running processes.
The deluser command removes user accounts from the system on some
distributions.

Deleted user accounts cannot be recovered. They can be recreated, but they will be a
different identity (unless created with the same UID value). It is often better to disable a
user account rather than delete it.

Verification
When you use the useradd, usermod, or userdel commands to manage
users, the result of the command is recorded, even if nothing is displayed on
the screen. For example, when you create a user, there is no message displayed.
When something goes wrong, an error is displayed explaining the issue. While the
messages are self-explanatory, such as “Username already in use” informing you
that the username you tried to set exists already, the results are actually labeled
using an exit code number. Display the results of the most recent command by
typing the following:
# echo $?
0
A zero indicates success; any other value indicates an error of some sort.
Some examples of those exit codes are provided here.

Exit Code for the useradd Command Result


0 Success
1 Couldn’t update the passwd file
9 Username is already in use
12 Couldn’t create the home directory

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 38 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 39

The error values differ slightly for the usermod and userdel commands.

Exit Code for the usermod and


Result
userdel Commands
0 Success
1 Couldn’t update the passwd file
2 Invalid command syntax
6 Specified user doesn’t exist
8 Cannot delete user because the
specified user is currently logged in
There are many other exit codes, with some shared among the three user
management commands and some unique. View the man page for the command to
see its specific exit values.

All Executables have exit codes. Use the echo $? command to display the exit status
of the most recent command.

Account Configuration Commands


Linux includes many additional account management and configuration commands.
Several commands display account information, while others configure password
settings and other default values. Finally, configuration files set default values for
new user accounts.

Display Account Information


The Bash command prompt can be configured to display the current user, but that
setting is optional. Typing the whoami command displays the current username
and is useful when the prompt does not display this information.
The w and who commands display all current logins on the system, including those
that might have remote terminal connections. Suppose you’ve decided to restart a
Linux server, but you wish to know whether any users are currently on the system.
Type the w command to display the users so you can warn them of the impending
restart.
You can also display account information with the id command. Typing id with no
argument displays information for the current user. An existing username is added
to id to display information about that account, including user ID, group ID, and
group memberships.
The syntax for using the id command is id {user-name}
For example, to gather account information for the Kai Garcia account, type id
kgarcia
General password settings are pulled from /etc/login.defs, and specific
passwords are managed with the passwd command. Password requirements are
also configured by using the chage command.

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 39 28/05/22 11:04 AM


40 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Option for the passwd Command Purpose


-d Delete a password and disable the account.

-e Immediately expire a password, forcing a


password change by the user.
-l Lock the account (for example, during a
leave of absence).
-u Unlock a locked account.

To set a password for your own account, type:


$ passwd
As the root user, you can change a password for any account. The syntax is
passwd username
You will be prompted to type the password twice. Note that no characters will show
in the Terminal while entering the new password.
Values displayed by the chage -l command:
• Last password change date

• Password expiration date

• Account inactive date

• Account expiration date

• Minimum days between password changes

• Maximum days between password changes

• Number of days before password expiration a warning is displayed

The chage command options:

Option for the chage Command Purpose


-l Display the current values.
-M Specify the maximum number of days
between password changes.
-m Specify the minimum number of days
between password changes.
-W Specify the number of warning days before
a password expires.
-E Lock an account after a specified date.

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 40 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 41

Helpdesk Ticket #01986

Submitted by: Department: Assigned to: Date Opened:


Anna Tanaka HR you 2024-04-12

Subject Account settings updates


Ticket Detail Tuesday’s security audit showed that some accounts are out
of compliance.
Can you please adjust Ali Selassi’s account password settings
for a 5 day warning, change required within four months,
and change not allowed within 1 day of a new password?
Date last updated 2024-04-12

Your response will look like this:


# chage -l aselassi
# chage -m 1 -M 120 -W 5 aselassi
Pluggable Authentication Models
Standard Linux authentication relies solely on the /etc/passwd and /etc/
shadow files. Often, more flexible authentication standards are needed. Pluggable
Authentication Modules (PAM) supplement authentication methods. Modules
provide additional options and flexibility.
Two PAM modules help administrators manage authentication. The first is
pam_tally2, and the second is faillock.
The pam_faillock module tracks login attempts and can block authentication
if too many attempts fail. Sysadmins may configure the pam_faillock module
to lockout a user account after three failed login attempts. The root user can display
login attempt tally information by using the faillock command.
The pam_tally2 module is deprecated and should only be used if
pam_faillock is not available on the system.

Lesson 12 contains additional details on Pluggable Authentication Modules (PAM).

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 41 28/05/22 11:04 AM


42 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
User Account Management
3

Answer the following questions:

1. Why are user passwords stored in the /etc/shadow file and not the
/etc/passwd file?

2. What is the purpose of the /etc/skel directory?

3. Why might an administrator change a user’s default shell?

Lesson 2: Administering Users and Groups | Topic 2A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 42 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 43

Topic 2B
Manage Group Accounts
4

EXAM OBJECTIVES COVERED


2.2 Given a scenario, implement identity management.

Like the management of user accounts in the previous section, managing groups
requires an understanding of the configuration files and commands used to govern
groups. Groups simplify the process of granting access to resources to multiple
users.

Group Configuration Files


Groups associate user accounts that have similar security requirements. For
example, it is easier to grant permissions to a resource to a single group with five
members than it is to individually grant access to each user account. Groups are a
standard administrative tool for controlling access to resources.
Like user accounts, groups are stored in a configuration file. The file is /etc/
group, and displaying its contents shows existing groups and any user accounts
that are a member of those groups.
One way of displaying the contents of /etc/group is to use the tail
command. For example, type tail /etc/group. The output displays the last
10 entries in the file, including the most recently added groups.

Output of the tail /etc/group command, showing the most recently added groups.

Lesson 2: Administering Users and Groups | Topic 2B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 43 28/05/22 11:04 AM


44 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Group Management Commands


The commands to manage groups are similar to user management commands.
Groups have a standard life cycle, including creation, modification, and deletion.

Group Management Command Purpose


groupadd Create a new group.

groupmod Modify an existing group.

groupdel Remove an existing group.

Helpdesk Ticket #01987


Submitted by: Department: Assigned to: Date Opened:
Anna Tanaka HR you 2024-04-18

Subject group updates


Ticket Detail The group named Marketing is evolving to handle publicity
only. Please update the group name.
We’re also starting a new Sales group and need a group for
that.
Date last updated 2024-04-19

As the help desk tech, you run the following two commands to complete the service
request:
# groupmod -n publicity marketing
# groupadd sales
The -n option changes the group name.
Deleting a group does not delete the user accounts that are a member of that
group. A group is a separate object from the user.
Note that you cannot remove the primary group of an existing user. You must
remove the user account first by using the userdel command.
Some distributions rely on addgroup and delgroup to manage groups.
These commands are more interactive than groupadd and groupdel. If the
commands are not installed on the system, they can be added.

Be sure to search for files or other resources that may be associated with the group
before deleting it. Configure another group with access to those resources before
deleting the original group.

Verification
Group management commands are usually straightforward, but things can go
wrong. The messages printed on the screen should be plenty to guide you toward a
solution. However, you can also display the exit values by using echo $?

Exit codes were discussed in additional detail in Topic 2A.

Lesson 2: Administering Users and Groups | Topic 2B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 44 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 45

Exit Code for the groupadd


Command Result
0 Success
2 Invalid argument syntax
4 GID not unique
9 Group name not unique

Exit Code for the groupmod and


groupdel Commands Result
0 Success
2 Invalid command syntax
6 Specified group doesn’t exist
8 Can’t remove user’s primary group
(for groupdel only)
10 Can’t update group file
There are many other exit codes; some shared among the three user management
commands and some unique. View the man page for the command to see its
specific exit values.

Add Users to Groups


Adding a user to a group is a modification of the user, not the group. Use the
usermod command covered earlier to add a user to an existing group.
Two specific options are used with usermod to manage group membership:

Option for the usermod


Command Purpose
-a Append the user to the group, and
maintain any existing group
memberships.
-G Specify a group to which the user will be
added.
If the -a option is not selected, the user is removed from all other groups and
added only to the specified group. Users can be a member of multiple groups, so
such a mistake could have drastic consequences.
The syntax for using the usermod command is usermod -options
argument
For example, the command to add Joseph Deng to the sales group while retaining
membership in all other groups is:
usermod -aG sales jdeng.

The group management lifecycle.

Lesson 2: Administering Users and Groups | Topic 2B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 45 28/05/22 11:04 AM


46 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Group Account Management
5

Answer the following questions:

1. Suggest at least two ways to display group membership information.

2. What command adds a user to a group?

3. What is the result if an administrator forgets to add the -a option when


adding a user to a group?

4. Why might a user be a member of multiple groups?

Lesson 2: Administering Users and Groups | Topic 2B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 46 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 47

Topic 2C
Configure Privilege Escalation
5

EXAM OBJECTIVES COVERED


2.4 Given a scenario, configure and execute remote connectivity for system
management.
4.4 Given a scenario, analyze and troubleshoot user access and file permissions.

One should avoid logging on to a system as the root user. The root user’s broad
privileges are unnecessary for most day-to-day user tasks, such as managing data
or browsing the Internet. If the standard practice is to log on with a non-privileged
standard account, then what about situations where administrative privileges are
required? Instead of logging off and then logging back on as root, Linux provides
ways of switching identities or running commands as a different user.
This section introduces privilege escalation and then covers tools such as su,
sudo, and pkexec. Proper use of privilege escalation helps to maintain the
security of the system and satisfy security policy requirements.

What is Privilege Escalation?


The root user is the system’s administration account. It has full privileges to do
anything on the system. This is both necessary for managing the system and
dangerous in the hands of malicious or inexperienced users. Logging in as root is
frowned upon.
Standard user accounts typically have privileges to manage their own data and
some basic system settings and preferences. Most standard accounts cannot run
commands that would damage or disable the system, which also means they
cannot usually make the configuration changes necessary to administer Linux.
Service accounts represent services running on the system that consume
resources. Because the services are represented by service accounts, their ability
to consume system resources can be controlled. This helps prevent a service from
overwhelming the system or blocking other services from accessing resources.

A common idiom for privilege escalation is "get root."

Understand a Disabled Root Account


Your organization’s security policy may require that you log on to server systems
with a non-privileged account. This is a very good practice to keep in mind; however,
it often isn’t possible to execute administrative tasks with nonadministrative
privileges. Logging on with a standard user account and then changing your identity
to one with administrative privileges is referred to as privilege escalation. There
are two ways of managing privilege escalation: su and sudo.
Many Linux distributions disable the root user account by default. During the OS
installation, an “admin” account is created that has privileges delegated via sudo.

Lesson 2: Administering Users and Groups | Topic 2C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 47 28/05/22 11:04 AM


48 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Those distributions that do not disable the root user still suggest that sysadmins log
in with non-privileged accounts and then elevate privileges by using su.

Avoiding signing in as the root user is an example of the principle of least privilege. This
principle states that the minimum level of access should be granted to accomplish a
given task.

Elevate Privileges with su


The su utility provides the ability to “switch user” to another account. The most
common example is a sysadmin that follows proper security practices by signing
in as a standard user and then switches to the root user to accomplish system
administration tasks.
The syntax for using su is su {user-name}.
For example, to switch to the root user, type su root.
The su command, without an option, enables a user to switch their identity to that
of another user, but it retains the original user’s profile and variables. The switched
user also remains in the home directory. Anyone using su except the root user will
be challenged for the password of the user account they are switching to.

Note that in this discussion, the string "su - {user-name}" has a space on each side of the
dash. This is a rare instance in Linux where this is true; the majority of other commands
are spaced as "command -option," which has a space only on the left side of the dash.

Using su with a hyphen following it enables a user to change users and launch a
new shell under the context of that new user. This is a much better practice. Anyone
using the su - except the root user will be challenged for the password of the
user they are switching to. It is most common to switch to the root user, but any
user can switch to any other user as long as they know that user’s password.

Without a user name argument, the su - command will assume you mean to sign in
as root.

Elevate Privileges with sudo


With the su command, any user who knows the root password can “get root” and
do anything the root user can do. An account using su - root essentially is the
server administrator. This is often much more power than should be delegated
to users. A better practice is to delegate specific functions to users, rather than
granting system-wide root privileges.
The sudo command enables the server administrator to delegate specific
commands to specific users, without granting them full privileges on the server.
Delegation is done in the /etc/sudoers file by using the visudo editor.
Users and groups may be given specific commands to run in order to fulfill their
responsibilities without having full administrator privileges.
The syntax for using the sudo command is sudo -options command.
For example, to run a command by using sudo, type sudo shutdown -h now.
Recall that you will be prompted for your password.

Lesson 2: Administering Users and Groups | Topic 2C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 48 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 49

You can check your sudo privileges by using the -l option. For example, type
sudo -l, and your privileges are displayed.

It may be difficult to get into the habit of using sudo before each command. Recall
that Bash keeps a history of recent commands and that !! repeats the most recent
command. If you forget to type sudo in front of a command, rerun the command by
typing sudo !!.

Understand visudo
While the /etc/sudoers file is a normal text file, it is essential not to directly
edit it with a standard text editor like Vim or nano. The /etc/sudoers file
controls access to all elevated privileges, and a mistake in this file can render it
impossible to gain root privileges on the server. Most distributions will set a default
editor (usually Vim or nano) for /etc/sudoers. When using the visudo
command, the system verifies the syntax of the /etc/sudoers file before
committing changes, enabling the administrator an opportunity to correct mistakes
before they become part of the running configuration.

A portion of the /etc/sudoers file displaying delegated privileges.

The following are some options you can use with the visudo command:

Option for the visudo Command Purpose


-c Check the existing sudoers file for errors.
-f Edit or check a sudoers file in a different
location than the default.
-s Check the sudoers file in strict mode—
any aliases that are used before being
defined will result in errors.
-x Output the sudoers file to the specified
file in JavaScript Object Notation (JSON)
format.
Because the /etc/sudoers file is sensitive to misconfigurations that could
result in not being able to elevate privileges, it’s critical to check the file after edits.
The visudo editor does this automatically, but various types of checks can be run
with the -c, -f, or -s options.

Lesson 2: Administering Users and Groups | Topic 2C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 49 28/05/22 11:04 AM


50 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The syntax for /etc/sudoers entries is username hostname =


(user) command where username is the user to whom privileges are being
given, hostname is the terminal from which commands can be run, user is the
level of access, and command is the delegated executable.
For example, to grant full administrative privileges to Kai Garcia, type:
kaigarcia ALL=(ALL:ALL) ALL.
The user will be prompted for their password. Be very careful with this level
of delegation!
Additionally, assuming that SHUTDOWN_CMDS is aliased to all related options
for the shutdown command, to delegate the ability to execute these shutdown
commands without entering a password, type:
KAIGARCIA ALL=(ALL) NOPASSWD: SHUTDOWN_CMDS.

The /etc/sudoers file contains aliases, or combinations of commands. For


example, an alias of SHUTDOWN_CMDS is associated with several commands that
manage system reboot or shutdown.

The wheel Group


The root account is used for a great deal more than just administrative tasks.
Some parts of the actual Linux operating system run under root credentials.
Many distributions disable the root account for users, preventing sysadmins from
logging on as root. Instead, these distros allow administrative functions based on
membership in the wheel group.
Members of the wheel group exercise the administrative privileges of root with
less potential for damaging the system. For example, members of the wheel
group use the sudo command to avoid having to sign in as the root user. Add
users to the wheel group to give them the privileges necessary to complete
administrative tasks, but be very cautious about this membership.
Use the visudo command to edit the privileges of the wheel group, if necessary.

The sudoedit Command


Some Linux files require root user privileges to edit. This could be accomplished
with a sudo configuration, but a simpler and more secure option is to use the
sudoedit command. This command permits a user to edit a file with their own
credentials, even if the file is only available to the root user. In addition, the user can
use their preferred text editor.
To use sudoedit, you must make an entry in the sudoers file. For example,
the following line could be added to the sudoers file:
%editors ALL = sudoedit /path/to/file
Any member of the editors group could then enter the following command to edit a
file: sudoedit /path/to/file.
The sudo configuration is appropriate for commands that need to be executed
with elevated privileges, while the sudoedit option is appropriate for files that
need to be edited with elevated privileges.

Lesson 2: Administering Users and Groups | Topic 2C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 50 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 51

PolicyKit Rules
The polkit (PolicyKit) toolkit provides a different way of delegating privileges than
sudo does. The polkitd daemon works with systemd to permit administrators to
delegate more granular control to users than sudo allows. Unlike sudo, polkit
does not grant full root access to a process but instead grants specific access to
defined actions.
One example of polkit’s benefits is software management. Using polkit rules,
sysadmins can permit a user to update existing software but prevent the
installation of new software. Other delegated tasks include system shutdown or
hibernation, configuring network devices, controlling device access, and mounting
or unmounting filesystems on removable media.

Some topics in this section, such as systemd and software management, are covered in
more detail elsewhere.

Configure polkit Rules


Rules are written that define what actions can be performed by what users. The
actions, or specified processes, are written into text files. The rules are also text files
that reference the actions.
Actions are defined in XML files stored at /usr/share/polkit-1/actions.
These files have a .policy file extension. Rules files are stored in two different directories:
/etc/polkit-t/rules.d for local policies and /etc/share/polkit-1/
rules.d for third-party policies. Rules use a .rules file extension. Administrators write
rules in JavaScript notation to reference actions defined in the actions files. When a user
attempts an action, the rules are checked to determine success or failure.

pkexec and Other polkit Commands


Four commands are associated with polkit. These commands display details,
authorization information, or enable a user to execute a command with elevated
privileges.

polkit Command Purpose


pkexec Allows an authorized user to execute an
action.
pkaction Displays details about an action.

pkcheck Displays whether a process is authorized.

pkttyagent Provides a text-based authentication


agent.

Use of pkexec to create a user account with confirmation that the account has been created.

The syntax for using pkexec is pkexec program argument.

Lesson 2: Administering Users and Groups | Topic 2C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 51 28/05/22 11:04 AM


52 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

For example, to launch nano with pkexec and edit the /etc/named.conf
configuration file, type:
pkexec nano /etc/named.conf.
Recall that the su - root command actually changes the user identity to root,
with all related privileges. This could be dangerous. The sudo and polkit utilities
allow administrators to delegate specific tasks to specific users without granting
complete administrative privileges to the system.

Troubleshoot Privilege Escalation Issues


You field the following four phone calls in the course of your week.

Phone Call 1: su
A user calls and says that the su command is not responding as expected. You ask
the user to type whoami and the user reports the result is root. You also ask the
user to type pwd and the user reports the result is their own home directory. When
the user switches identities, they remain in their own home directory with their own
profile settings. The user wants to know what is preventing them from switching to
root and gaining the root user’s profile.
In this case, it’s likely that they are using the incorrect syntax. The user failed to
include the space on both sides of the dash between the su command and the
username, su - root.

Phone Call 2: sudo


A user calls and says sudo is broken on their system after they edited the /etc/
sudoers file with Nano. The user wants you to fix it.
Open /etc/sudoers with visudo, and allow it to identify syntax errors that
Nano would not have caught. Let the user know to use visudo in the future.

Phone Call 3: Authorization


A user indicates they cannot accomplish administrative tasks that they are
authorized for.
The likely problem is that they are not a member of the wheel group or they have
not been delegated the tasks directly via /etc/sudoers. The easiest solution is
to add them to the wheel group.

Phone Call 4: New Command


A user calls after attempting to run a command that was referenced on an Internet
website. The user preceded the command with sudo and with pkexec, as
suggested on the site. The command failed to run, however.
The likely problem is that the privilege has not been delegated via either sudo or
polkit.

Lesson 2: Administering Users and Groups | Topic 2C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 52 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 53

Review Activity:
Privilege Escalation
6

Answer the following questions:

1. A developer at your organization needs the ability to reboot a test


server, but their account’s standard privileges do not permit this. The
developer requests the system's root user password in order to use su
to reboot the server. Is there a more secure option that aligns with the
principle of least privilege?

2. How are the su root and su - root commands different?

3. You must delegate the shutdown -h privilege to SOMEUSER. What tool is


used to modify the /etc/sudoers file, and what line must be added to that
file?

4. Whose password must be entered with sudo? Whose password must be


entered with su?

Lesson 2: Administering Users and Groups | Topic 2C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 53 28/05/22 11:04 AM


54 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 2D
Troubleshoot User and Group Issues
5

EXAM OBJECTIVES COVERED


4.4 Given a scenario, analyze and troubleshoot user access and file permissions.

User and group management is a straightforward task, but troubleshooting


opportunities still arise. Sysadmins must review configuration files and individual
user account settings to help identify and resolve login or configuration issues. In
addition, security audits or troubleshooting may require a record of when users
attempted to log in and whether the attempts were successful.

Troubleshoot User Management Issues


User account management involves creating, modifying, and deleting user
accounts. Group account management is similar, though there are some additional
restrictions, such as deleting a user’s primary group. The following scenarios define
some common user management issues.

Account Management Issues


Only authorized users may create, modify, or remove user and group accounts. The
root user can do this, as can anyone else delegated such privileges via sudo. If you
cannot create or modify a user or group, ensure you’re using an account with the
proper authorization.
Account management problems often relate to whether the account or group
exists. Recall that each user account is assigned a unique user ID. New groups are
also given a unique group ID. One way to view these identifiers is to check
the /etc/passwd or /etc/group files. If a user account or group cannot
be created, check to see if the name or ID is already in use.
Halt any active processes associated with the user. If the delete attempt fails, check
for any running processes belonging to the user. The ps command can be helpful
for identifying processes. The command to halt or kill all processes for the user is:
sudo killall -u {username}
When you create a user account, an associated group may also be created. Whether
this occurs depends on the Linux distribution. This group, known as the user’s
primary group, cannot be deleted unless the user is also deleted.
Be sure to add the -r option to the userdel command if you want the user’s
home directory deleted when the account is created.

Troubleshoot User Login Issues


Like other troubleshooting opportunities, begin solving login issues by starting with
basic checks. Ensure accounts exist and have a valid password. Consider the login
procedure and the order in which profile files are processed. Linux has several
commands to help administrators gather information about login attempts and
current user sessions.

Lesson 2: Administering Users and Groups | Topic 2D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 54 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 55

Users may fail to authenticate to the system. These failures are often associated
with user account and password misconfigurations. Recall that account information
is stored in the /etc/passwd and /etc/shadow files.

User Login Attempt Failures


Confirm the user has an account on the system by displaying the contents of
/etc/passwd. If necessary, create an account for the user by using the
useradd command.
If the account exists, confirm that a password is set. Display the contents of /etc/
shadow, and verify a hashed password exists. Use the passwd command to set a
password if one did not exist.
If the account exists and a password is set, the user may have forgotten the correct
password. Reset the password with the passwd command.
If the account exists and a password is set, the password may be expired. Reset the
password by using the passwd command.
If the account exists and a password is set, the account may be locked. Unlock the
account by using the chage command.

Review the Login Process


Refer to the login process to help pinpoint specific issues. The system goes through
a logical order, and understanding where in that process a failure could occur is a
great place to begin troubleshooting.
1. The operating system boots and the kernel is loaded. Assume the system
boots to the CLI and displays an authentication prompt.

2. The user enters a name and password combination. These are checked
against the /etc/passwd and /etc/shadow files. Settings such as
expired passwords and locked accounts are checked for at this point.

3. System and user profile files are processed, and the user is presented with an
authenticated and customized environment.

The boot process is covered in a future Lesson.

Use User Login Commands


Administrators need to know who has tried to log in and succeeded as well as who
has tried to log in and failed. Linux tracks this information, and it can be displayed
by using several different commands.
The lastlog command displays the last login times for accounts. This
information allows administrators to know who was logged in at any given time.
Use this information in system audits and security reviews. The lastlog utility uses
its own log file (usually found at /var/log/lastlog).
The last command displays the contents of the wtmp file, which includes every
login and logoff event on the system. The output can be filtered by timestamp
and even displays information for remote users. The wtmp file is usually found at
/var/log/wtmp.

Lesson 2: Administering Users and Groups | Topic 2D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 55 28/05/22 11:04 AM


56 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The last command displays the most recent logins and logouts.

It is a good security practice to delete unused user accounts, and these tools help
identify such accounts.

While the historical data displayed by last and lastlog can be helpful, it’s
also useful to know what users are currently on the system. Both the w and who
commands display this information. The w command is particularly useful because
it shows the user idle time, which indicates the user may be logged on but no longer
interacting with the session.

Lesson 2: Administering Users and Groups | Topic 2D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 56 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 57

Review Activity:
User and Group Troubleshooting
6

Answer the following questions:

1. List at least three scenarios where you might need records of who logged
in to a Linux system.

2. Another administrator asks you to explain the value of editing the /etc/
sudoer’s file with visudo rather than a traditional text editor. What is
your response?

3. List at least three reasons a user account might be locked.

4. During a security audit it is discovered that a user does not have a


password set. When you check the /etc/passwd file, the password field is
properly populated with the x character. What file would actually display
whether a password has been set for the user?

5. A user places sudo before a command, but the command still fails to run.
What might be the cause?

6. An administrator asks you how to delegate Linux administrative


privileges to a specific user. What group is used for such delegation?

Lesson 2: Administering Users and Groups | Topic 2D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 57 28/05/22 11:04 AM


58 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Lesson 2
Summary
7

Observe how user authentication allows the system to uniquely identify the logged-
on user. The primary purpose of this identification is to enforce permissions on files
and directories. Permissions can be granted (or denied) to identities, allowing tasks
such as read-only file access, script execution, or application execution. Users are
placed into groups when more than one user must be restricted by permissions.
The use of user identities is further exemplified by considering privilege escalation.
What privilege escalation actually provides is the ability to move from one user
identity to another to exercise different levels of resource access.

Command Reference Table


This list of commands and their associated syntax can also be found in Appendix B.

Command Syntax Purpose Covered in


passwd passwd Manage user Lesson 2, Topic A
[user-name] passwords.

chage chage -options Manage password Lesson 2, Topic A


settings.
w w Display current Lesson 2, Topic A
users on the
system.
who who Display current Lesson 2, Topic A
users on the
system.
useradd useradd Add a user. Lesson 2, Topic A
-options
argument
usermod usermod Modify a user. Lesson 2, Topic A
-options
argument
userdel userdel Delete a user. Lesson 2, Topic A
[user-name]
id id [user-name] Gather and display Lesson 2, Topic A
account
information.
groupadd groupadd Create a new Lesson 2, Topic B
[group-name] group.

groupmod groupmod Modify an existing Lesson 2, Topic B


-options group.
argument
groupdel groupdel Remove an Lesson 2, Topic B
[group-name] existing group.

Lesson 2: Administering Users and Groups

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 58 28/05/22 11:04 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 59

Command Syntax Purpose Covered in


su su - [user- Switch user to the Lesson 2, Topic C
name] specified user or
account name.
sudo sudo -options Exercise delegated Lesson 2, Topic C
[command] privileges.

pkexec pkexec program Allows an Lesson 2, Topic C


argument authorized user
to execute an
action.

Practice Questions: Additional practice questions are available on the CompTIA


Learning Center.

Lesson 2: Administering Users and Groups

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 59 28/05/22 11:04 AM


LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson02_pp031-060.indd 60 28/05/22 11:04 AM


Lesson 3
Configuring Permissions
1

LESSON INTRODUCTION
The identity of an authenticated user provides context for enforcing permissions.
Once the system knows which user is logged on, it can limit the actions that user
can take. Linux relies on a simple yet effective permissions structure that recognizes
three identities (users, groups, and all others) and provides three access levels
(read, write, and execute). More complex permissions options exist, including
special permissions and access control lists (ACLs).
Administrators manage group membership, file ownership, and group association
to control access to resources. As such, the permissions discussion in this Lesson is
a natural extension of the account management subject of the previous lesson.

Lesson Objectives
In this lesson, you will:
• Configure standard Linux permissions.

• Configure special Linux permissions.

• Configure access control lists.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 61 01/06/22 12:35 PM


62 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 3A
Configure Standard Linux Permissions
2

EXAM OBJECTIVES COVERED


2.5 Given a scenario, apply the appropriate access controls.
4.4 Given a scenario, analyze and troubleshoot user access and file permissions.

The authentication process provides users with an identity on the system. Based on
this identity, the system can enforce levels of access to system resources, such as
processes and files. This type of access control allows users to share systems and
resources with the appropriate levels of confidentiality and privacy.
Sysadmins rely on default Linux settings, such as umask, to define some levels of
access. Administrators also define explicit controls by associating specific access
levels with particular identities. Linux has several permissions structures, including
standard, special, and access control list mechanisms. Users are organized into
groups to make access control more efficient. Proper permissions settings and
owner/group associations are critical to Linux security and administration.

Understand Permissions Concepts


Standard permissions provide a way for sysadmins to enforce levels of access on
users for files and directories. Standard permissions are relatively simple, with
three identities given up to three levels of access. Permissions and file ownership
are managed with the chmod and chown commands, and permissions are
displayed by using the ls -l command.

Principle of Least Privilege


The principle of least privilege enforces the idea that users should be given as
little access to resources as necessary for them to do their jobs, with no additional
unneeded access.
Two scenarios illustrating this concept are provided here.
Kai Garcia needs to be able to read file1.
• Proper: They are granted the read permission only.

• Improper: They are granted the read, write, and execute permissions and could
potentially change the file.

Joseph Deng needs to create files associated with their own job but doesn’t need to
perform system administrative tasks.
• Proper: Joseph logs on with a standard user account.

• Improper: Joseph logs on with the root user account.

Keep the principle of least privilege in mind in all access control configurations,
especially those involving file permissions.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 62 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 63

Access Levels
Standard Linux permissions define three levels of access: read, write, and execute
(rwx). These permissions perform differently depending on whether they are
applied to files or directories.

Files Directories
Read (r) The ability to access and The ability to list the
view the contents of a file. contents of a directory.
Write (w) The ability to save changes The ability to create,
to a file. rename, and delete files
in a directory. Requires
the execute attribute to
also be set.
Execute (x) The ability to run a script, The ability to access a
program, or other software directory, execute a file
file. from that directory, or
perform a task on that
directory (e.g., a search).

The three permissions levels are abbreviated with r, w, and x. These abbreviations
are used in conjunction with permissions management commands, so be able to
recognize them.

Access Identities
Standard Linux permissions define three identities to which permissions can be
applied: user (owner), group, and others.
The user (u) identity is a single resource owner. Only one user identity is associated
with the resource with standard permissions, and specific permissions are applied
to this identity. By default, the user is the identity of the account that created the
resource, but that can be changed. This user identity is referred to as the resource
“owner.”

The chown command allows administrators to change the associated user (and group).
The chown command is covered later in this Topic.

The group (g) identity is a single group of users associated with the resource. In
standard Linux permissions, only one group is assigned to the resource and a
specific set of permissions is assigned. By default, the creator’s group is set on the
resource, but that can be changed.
A group allows multiple users to access the resource at a given level. For example,
a sales group consisting of several user accounts can be granted read access to a
sales file, allowing all members of the group to view the contents of the file.
The others (o) identity represents all accounts that are not the user (u) identity or
a member of the one associated group (g). The others identity means “everyone
else” who is not the user and not a member of the group. These other accounts
are granted a level of access. Frequently, that permissions level is either read or
no access.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 63 01/06/22 12:35 PM


64 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Linux permissions are enhanced with special permissions and access control lists (ACLs),
which are both covered later in this Topic.

View Permissions
The ls command, introduced earlier, relies on the -l option to display
permissions. Think of the ls -l command as “list in long format,” where the
long format includes the display of permissions. Sysadmins use this command
frequently to confirm permissions settings.

The ls -l command displays details about permissions, owner, group, size, and more.

In the following example, note that the resource is a file (based on the leftmost
dash character), the owner (root) has rwx, the group (grp) has rwx, and all others
have r only.
-rwxrwxr-- root grp fileA
Interpreting Permissions Strings
The permissions string consists of 10 fields, with each field containing different
information.
The first field defines whether the resource is a file or a directory. A file is identified
by a dash character (-), while a directory is identified by a d character.

The first column of the permission string, listing one directory and three files.

The next three fields are related and identify the permissions assigned to the
resource for the user identity. If a permission is granted, it is identified with one of
three characters: r, w, or x. If the permission is not granted, the dash character is
used as a placeholder.
For example, if the user is granted read but not write or execute, the three fields
appear like this: r--. If the user is granted read and write, but not execute, the three
fields appear as rw-. Note that the permissions are always displayed in the rwx
order, and the - is a placeholder for any unassigned permission.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 64 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 65

The second three columns list the permissions assigned to the user identity. Here the user
has rwx access to the directory and the first file, rw access to the second file, and read
only access to the third file.

The same structure applies to permissions assigned to the group, in the fifth, sixth,
and seventh fields.

The group permissions are outlined here. The group has r-x access to the directory, rw access to
the first and second files, and no access at all to the third file.

And the final three fields use the same structure for others.

The final three columns show permissions for others not in the user or group identity.
Permissions are more stringent here, with others having r-x access to the directory
and read only access to the first file, with no access at all to the last two files.

Some other examples are provided here.


A file named fileA, with the user having read, write, and execute; the group having
read and write; and others having read-only would appear as:
-rwxrw-r-- fileA

Additional fields, such as owner, group, and file size, have been removed from these
examples to provide clarity.

A file named file A, with the user having read, the group having read, and others
having no access would appear as:
-r--r----- fileA
A directory named dir1, with the user having read, write, and execute; the group
having read and execute; and others having read and execute would appear as:
drwxr-xr-x dir1

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 65 01/06/22 12:35 PM


66 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

A directory named dir1, with the user having read and execute, the group having
read and execute, and others having no access would appear as:
dr-xr-x--- dir1

Recall that the execute (x) permission is required for the user to use cd to move into
the directory. If a user does not have execute to a directory, they cannot change into
that directory.

Default Permissions
The ls -l command displays the existing permissions, but what if permissions
need to be changed? Administrators can set file and directory permissions for all
resources, and resource owners (the account identified by the user (u) permissions)
can also configure permissions.
A value named umask defines default permissions on a per-user basis. The “change
mode” or chmod command changes permissions settings from the default values.

Configure Default Permissions


The umask command alters the default permissions on newly created files and
directories. Changing default permissions can be useful if you’d like to automatically
control how new objects can be used, rather than changing these permissions
manually on every new object.
With umask, you set default permissions using an octal numeric format. However,
instead of specifying which permissions to set, you specify which permissions to
mask, or clear, from the default. For example, the default permissions for non-
executable files in Linux are 666 (rw-rw-rw-). If you want the owner to retain
these permissions, but you want the group and others to only have read access,
you’ll need to set the umask to 022. Each number is explained as follows, in order
from left to right:
• 0 means that the current owner permissions should not be masked at all (i.e.,
left as read and write).

• 2 means that the group permissions should be masked by 2 (i.e., subtract 2 from
the default [6] and you get 4). Group members now only have read access.

• 2 does the same thing as the previous number, but it does so for other users.
You can use the umask command directly in the CLI to set the default permissions
for that session, or you can set the default permissions for each user in their
.bashrc or .profile file.
The syntax of the umask command is umask {number}.

Because it subtracts from the default (666), the umask command cannot force newly
created files to set the execute bit.

Absolute and Symbolic Modes


The chmod command enables you to modify the permissions of a file or directory.
Only the owner of the file or directory or the system administrator can change
the permissions of the object. This command has several options and may be
configured by using two different modes.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 66 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 67

The syntax of the chmod command is chmod [options] {mode} {file/


directory name}
The chmod command supports different options to modify permissions. One or
more of these options may be used at a time.

Option for the chmod Command Purpose


-c Report changes that are made in
permissions.
-f Hide most error messages.

-v Display a diagnostic entry for every


file processed.
-R Modify permissions of files and
directories recursively.

The chmod command has two different syntaxes for setting permissions: absolute
mode and symbolic mode. Both approaches provide the same results. Some
administrators find one approach more logical than the other, and it does not
really matter which is used. Sysadmins should understand and be able to use both
modes.

Absolute Mode
Absolute mode uses octal (base-8) numbers to specify permissions. Each
permission (r/w/x) has an associated number.
Absolute mode octal values:
• Read = 4

• Write = 2

• Execute = 1

By adding the octal numbers for the permissions you want to grant, you get
the overall permission number to assign to a directory or file. For example, full
permissions (read, write, and execute) are equivalent to 4 + 2 + 1, or 7. Read and
write permissions are equivalent to 4 + 2, or 6. Complete permissions are expressed
as a three-digit number, where each digit corresponds to the owner, the group, and
others, respectively.
In absolute mode, the syntax of the chmod command is chmod {number}
{file/directory name}
Three-digit and Four-digit Modes
When written in octal, numeric format, file permissions typically have three digits,
with each digit corresponding to the user, group, and others permissions. However,
file permissions may also be written with four digits, with the new, leading digit
signifying any advanced permissions to be defined (or 0, for none). For example,
the permissions for a non-executable file in Linux might be rw-rw-r--, or 664. This is
equivalent to the octal format of 0664.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 67 01/06/22 12:35 PM


68 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Symbolic Mode
Symbolic mode enables you to set permissions using three components, namely:
• Permission contexts: u/g/o/a (a applies the permissions to all three contexts)

• Permission operators: +/-/=

• Permission attributes: r/w/x

Permission operators determine whether a permission is to be granted or


removed.
The operator + (plus sign) grants permissions. The operator - (minus sign, or
hyphen) denies permissions. Operator = (equal sign) assigns permissions exactly as
provided, rather than being additive or subtractive.
In symbolic mode, the syntax of the chmod command is: chmod
{access
context}{operators}{permission attributes} {file/
directory names}
As an example, to add read and write permissions to myfile for the owner and the
group: chmod u+rw,g+rw myfile

Permission Absolute Mode Symbolic Mode


User has read-write-execute. 755 u=rwx,g=rx,o=rx
Group has read and execute.
Others have read and execute.
User has read-write-execute. 700 u=rwx,g=,o=
Group has no permissions.
Others have no permissions.
User has read and write. 644 u=rw,g=r,o=r
Group has write.
Others have write.
User has read and write. 600 u=rw,g=,o=
Group has no permissions.
Others have no permissions.
User has read and write. 640 u=rw,g=r,o=
Group has read.
Others have no permissions.
Some common permissions and their representations in absolute and symbolic modes.

While sysadmins tend to prefer one mode or the other, it is worthwhile to understand
both modes. Documentation, online resources, and other administrators may provide
permissions settings using either mode, so you must be able to interpret whichever
mode is presented.

Set Permissions in a GUI


In most GUI desktop environments, right-click a file or directory, select Properties,
and select the Security tab. Check the appropriate permissions boxes for the
identity and access level you wish to set.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 68 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 69

GUI environment permissions output.

Configure Ownership
Although you’ve restricted access to your data by assigning permissions, you may
need to allow users to modify those permissions for certain files and directories.
This is where the concept of ownership comes into play.
As you’ve seen, the first permission context is the owner or user. In Linux,
ownership refers to the property by which a user can apply and modify the
permissions of a file or directory. By default, the owner of a file or directory is the
user who created that file or directory. Other than the superuser, no other user
can change the permissions of an object that is owned by someone else. While the
most common application of ownership is the changing of read, write, and execute
permission attributes, owners can also alter advanced and special permissions of
the objects they own.

Use the chown Command

Helpdesk Ticket #01988

Submitted by: Department: Assigned to: Date Opened:


Kai Garcia Engineering you 2024-04-22

Subject Ownership change


Ticket Detail Hello, can you please update the Projects directory and set
Joseph Deng as the owner? Joseph will be taking over that
duty now that Alex has left.
Date last updated 2024-14-22

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 69 01/06/22 12:35 PM


70 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The chown command is used to change the owner, the group, or both for a
file or directory. At times, you may wish for someone else to manage an object’s
permissions other than the user who created that object.

Changing the owner with chown. The file named “project1.txt” was owned by root, but is now
owned by student5 in this example.

The chown command syntax varies based on the desired outcome:


• Change the owner but not the group: chown {newowner} {filename}
• Change both the owner and the group: chown
{newowner}:{newgroup} {filename}
• Change the group but not the owner: chown :{newgroup} {filename}
You can also combine the chown command with the -R option to recursively
change ownership through a directory structure.

Use the chgrp Command


The chgrp command is used to change the group ownership of a file or directory.
Changing the group ownership of an object ensures that the group permissions are
applied to the specific group.
The syntax of the chgrp command is chgrp {group name}
{file/directory name}

Configure Attributes
Files can have one or more attributes set on them that define how the system
interacts with those files. These attributes go beyond typical permissions and
enable you to more granularly customize what the system is and is not allowed to
do with a file.
There are many such attributes. Some examples include:
• Only allow the file to be open for writing in append mode (i.e., don’t allow the file
to be overwritten).

• Set the file to be automatically compressed.

• Save the file if it is deleted, providing an opportunity for it to be recovered.

• Make the file immutable.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 70 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 71

The Immutable Flag


The immutable flag is an attribute of a file or directory that prevents it from being
modified, even by the root user. In other words, no one can delete, rename, or write
to an immutable file. Setting the immutable flag is useful for files with a high degree
of sensitivity and importance (and with the unlikelihood of changing any time soon).
A careless user or an errant process will be unable to delete the immutable file.
The immutable flag is not set on all files. A single directory can have a mix of
mutable and immutable files and subdirectories. Also, an immutable subdirectory
can have mutable files.
When viewing file attributes, the lowercase i character indicates that the
immutable flag is set.

Attribute Management with lsattr


Administrators use the lsattr command to list the attributes of a file or
directory.

The lsattr command displays current attribute settings, such as this immutable flag.

Some of the options for the lsattr command are:

Option for the lsattr Command Purpose


-R Recursively list the attributes of
directories and their contents.
-a List all files in directories.

-d List directories like files, instead of listing


their contents.
-v List the version number of the file.

The syntax of the lsattr command is lsattr [options]


{file/directory names}
Attribute Management with chattr
The chattr command is used to change the attributes of a file or directory.

The chattr command modifies attribute settings.

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 71 01/06/22 12:35 PM


72 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The chattr command includes these options:

Option for the chattr Command Purpose


-R Recursively change the attributes of
directories and their contents.
-v {version} Set the version number of a file.

+i Mark the file as read-only, or immutable.


Requires superuser privileges.
-i Remove the read-only, or immutable,
attribute of the file. Requires superuser
privileges.
The syntax of the chattr command is chattr [-R] [-v {version}]
[+-{attributes}] {file/directory names}

Troubleshoot Access Issues


Permission-based access problems usually consist of misapplied permissions or
misunderstood identities.

Helpdesk Ticket #01989

Submitted by: Department: Assigned to: Date Opened:


Ali Selassi Marketing you 2024-04-25

Subject Access issues


Ticket Detail Hi, can you help me with access to File1? I’m in the Sales
group, which manages DirectoryA, and should be able to
get into File1, but I can’t get in.

Thanks,
Ali
Date last updated 2024-04-25

Is the user actually a member of the sales group?


Confirm the user’s membership in sales with the group or id commands, and
confirm the permissions applied to sales for the file by using ls -l
Are the permissions set correctly?
Display permissions with ls -l, and check permissions of the file.
Are permissions set recursively from the parent directory?
Use su to test access, then reapply permissions, being careful of your absolute or
symbolic mode syntax.

Attribute Issues
Attribute problems are typically related to whether or not the attribute is set. Often
the solution is to either set or unset the value.
If the file can be deleted and should not be, set the immutable attribute with
chattr +i {filename}
If the file cannot be deleted and should be, unset the immutable attribute with
chattr -i {filename}

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 72 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 73

Review Activity:
Standard Linux Permissions
3

Answer the following questions:

1. How does the principle of least privilege help mitigate threats and
mistakes?

2. What octal value is used in absolute mode to set permissions at all


access for all identities?

3. Write the command by using symbolic mode that removes the read
permission from others for fileA without impacting other permissions.

4. Interpret the results of the following command: chown -R USERA:sales


dirA

Lesson 3: Configuring Permissions | Topic 3A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 73 01/06/22 12:35 PM


74 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 3B
Configure Special Linux Permissions
5

EXAM OBJECTIVES COVERED


2.5 Given a scenario, apply the appropriate access controls.
4.4 Given a scenario, analyze and troubleshoot user access and file permissions.

The standard read, write, and execute permissions are good enough in most
circumstances. However, there are additional permissions and attributes that you
can use to restrict access in a more specialized way. These permissions permit
users to run software as someone else or allow directory contents to inherit group
associations, providing default access control settings.

Understand User and Group ID


Special permissions are used when normal permissions become inadequate. With
special permissions, less-privileged users are allowed to execute a file by assuming
the privileges of the file’s owner or group. This enables the user to temporarily take
on these higher-level privileges in a limited context.
In Linux, two main special permissions are set user ID (SUID) and set group
ID (SGID). SUID, or setuid, is the permission that allows a user to have similar
permissions as the owner of the file. Certain executable files and commands,
such as passwd, require access to additional resources that the user may not
have explicit permissions to. Instead of granting those permissions individually,
the passwd command is configured so that any user will execute it as root (the
owner), giving them permission to the additional resources.
SGID, or setgid, is the permission that allows a user to have permissions that are
similar to those of the file’s group owner . In addition to files, SGID can also be
set on directories. Any subdirectories created in this directory will automatically
inherit the SGID permission. Likewise, all new files and subdirectories created in
this directory will inherit the directory’s group ID, rather than the group ID of the
user who created the object. This inheritance is useful because users in a shared
environment don’t need to change their group when they create objects in the
directory. Note that the SGID permission is not applied to existing objects in the
directory, nor is it applied to objects that are moved from other locations into
the directory.
SUID and SGID are both set using the chmod command, and you can do so using
either symbolic mode or absolute mode. When using ls -l to see permissions,
the execute permission for the owner will appear as s for the SUID, and the execute
permission for the group will appear as s for the SGID.

Set Special Permissions with Absolute and Symbolic Modes


Symbolic mode uses this syntax:
• To set the SUID: chmod u+s {file-names}
• To set the SGID: chmod g+s {directory-names}

Lesson 3: Configuring Permissions | Topic 3B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 74 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 75

Absolute mode uses this syntax:


• To set the SUID: chmod 4--- {file-names}
• To set the SGID: chmod 2--- {directory-names}
Note the last three bits in absolute mode are whatever standard permissions you
choose.
Removing the SUID and SGID is as simple as using the - (minus) operator in
symbolic mode or setting the first permission bit to 0 in absolute mode.

Understand the Sticky Bit


A sticky bit is a special permission bit that protects files in a directory. It ensures
that only the owner of a file or directory (or root) can delete the file or directory.
Without the sticky bit, any user with write and execute permissions on an object
can delete that object. The sticky bit ensures that these users do not have delete
privileges but still have the rest of the privileges that come with writing and
executing files and directories.
Like SUID and SGID, you set a sticky bit using the chmod command. Using ls -l
you can see the sticky bit in the execute position for other users (the last position)
as the lowercase letter t or the capitalized letter T if the execute permission is not
set for others.
In older versions of the kernel, a sticky bit could force a program or file to remain
in memory so that it wouldn’t need to be reloaded when it was invoked again. A
sticky bit on a file indicated to the operating system that the file would be executed
frequently. Modern versions of the Linux kernel ignore the sticky bit on files; if you
want to protect specific files, you need to apply the sticky bit on the directory that
contains them.
Setting the sticky bit uses this syntax in symbolic mode:
# chmod +t {directory names}
Setting the sticky bit uses this syntax in absolute mode:
# chmod 1--- {directory names}
As with SUID and SGID, use - or 0 to clear the sticky bit.

Troubleshoot Special Permissions Access


Troubleshooting special permissions is more difficult than finding issues with
standard permissions, but the steps are much the same. First, confirm any identities
and group memberships. Next, ensure permissions are set correctly by using ls -l,
and make any updates with chmod.
• Confirm the SUID permission is set correctly for executable files.

• Confirm the SGID permission is set correctly for directories to permit files
created in the directory to inherit the group association.

• Confirm the sticky bit permission is set correctly.

Lesson 3: Configuring Permissions | Topic 3B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 75 01/06/22 12:35 PM


76 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Special Linux Permissions
6

Answer the following questions:

1. How would SGID benefit users when set on the /projects directory where
multiple users are members of the associated group and need access to
each other’s files in the directory?

2. Why might a sysadmin set the sticky bit on a configuration file?

Lesson 3: Configuring Permissions | Topic 3B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 76 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 77

Topic 3C
Configure Access Control Lists
3

EXAM OBJECTIVES COVERED


2.5 Given a scenario, apply the appropriate access controls.
4.4 Given a scenario, analyze and troubleshoot user access and file permissions.

One weakness of standard Linux permissions is that only a single user, a single
group, and all others who are not that user or a member of that group can be
granted access. With standard permissions, a sysadmin cannot provide UserA with
rw- and UserB with r--. Nor can GroupA be given rwx to a directory while GroupB is
given r-x.
Access control lists, a feature of the filesystem, do permit the system to recognize
multiple identities and enforce different levels of access on those identities. In other
words, with ACLs the scenarios above are possible.
ACLs do not replace standard permissions, but rather they enhance them.
Everything you know about standard permissions still applies and is then
supplemented with additional ACL features.

Access Control List Concepts


An access control list (ACL) is a list of permissions attached to an object. ACLs
can be used for situations where the traditional file permission concept does not
suffice. ACLs enable you to assign permissions to individual users or groups even if
these do not correspond to the object’s owner or group.
For example, members of two department groups may need different levels of
access to the same resource. Group 1 might need rwx to a directory, whereas
Group 2 only needs r-x access. By using ACLs, you can grant different levels of
access to different users, groups, and even processes. ACLs enable a more granular
level of control.

Configure Access Control Lists on Files


Two commands are the basis for ACL configuration. The first is getfacl, which
is used to display existing ACL settings. The setfacl command configures ACL
permissions.

Display ACL Entries


The getfacl command is used to retrieve the ACLs of files and directories.
The basic output format of the getfacl command shows metadata about
the object, including its owner, its group, any SUID/SGID/sticky bit flags set, the
standard permissions associated with the object, and the individual permission
entries for users and groups. Directories can also have default ACL entries that
pertain to any new files or subdirectories created within them.

Lesson 3: Configuring Permissions | Topic 3C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 77 01/06/22 12:35 PM


78 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The syntax of the getfacl command is getfacl {filename}

The getfacl command output shows the file owner, group, and standard permissions.

Configure ACL Entries


The setfacl command is used to change the permissions associated with the
ACL of a file or directory. This command has several options. Some of the most
common options are:

Option for the setfacl Command Purpose


-R Recursively set ACL options for
directories and their contents.
-s Set the ACL of an object, replacing any
existing ACL.
-m Modify the existing ACL of an object.

-x Remove entries from an existing ACL.

-b Remove all ACL entries (not including the


standard permissions).
The syntax of the setfacl command is setfacl [-bR] [-mx
{acl_spec}] {file/directory names}
The ACL specification can be formatted in one of several ways:
• When working with users, the format is u:{user name}:{permissions}
• When working with groups, the format is g:{group name}:{permissions}

Lesson 3: Configuring Permissions | Topic 3C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 78 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 79

The setfacl command uses the -m option to modify the access control list already in place.

ACL Entry Examples


Consider the following examples. Note the ability to manage users, groups, or both.
To set an ACL entry for usera with rwx access:
# setfacl -m u:usera:rwx fileA
To set an ACL entry for groupa with rwx access:
# setfacl -m g:groupa:rwx fileA
To set an ACL entry usera with rwx access and group sales with rw access:
# setfacl -m u:userA:rwx,g:sales:rw fileA
To remove an ACL entry for usera for fileA:
# setfacl -x u:usera fileA

ACL settings do not replace standard permissions. Standard permissions are still
enforced as described earlier in this Lesson, but they are further enhanced by ACL
capability.

Troubleshoot ACL Issues


Like troubleshooting standard permissions issues, ACL troubleshooting involves
displaying the existing ACL entries by using the getfacl command and ensuring
they are set as expected. If they are not, use setfacl to configure the correct
entries in the ACL.
It is also common to see access control issues based on identities and group
memberships, so be sure to confirm the user is signed in with an identity that
should have access. Adjust group memberships as needed with the usermod
command.

Lesson 3: Configuring Permissions | Topic 3C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 79 01/06/22 12:35 PM


80 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
ACL Configuration
4

Answer the following questions:

1. Explain the benefit offered by ACLs compared to standard Linux


permissions.

2. What commands are used to set ACL entries for USERA with rwx and
USERB with r-- for fileA?

3. Does the ACL structure replace standard permissions?

Lesson 3: Configuring Permissions | Topic 3C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 80 01/06/22 12:35 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 81

Lesson 3
Summary
4

The identity of a user or a user’s membership in a particular group governs access to files and
directories. This access control, provided mainly by permissions, allows the possible viewing,
editing, or running of files. Additional controls, such as attributes, default permissions, and
access control lists, permit administrators to exercise more granular control over resources.

Guidelines
These best practices and guidelines are provided for your use as revision tools or as quick
references in your job role.
• Understand the principle of least privilege, which enforces the idea that users should be
given as little access to resources as necessary for them to do their jobs, with no additional
unneeded access.

• Recognize access levels and identities.

• Absolute mode and symbolic mode provide the same information in different ways.
Absolute mode displays in octal numerals, while symbolic mode displays information using
operators.

• The immutable flag is an attribute of a file or directory that prevents it from being modified,
even by the root user.

Command Reference Table


This list of commands and their associated syntax can also be found in Appendix B.

Command Syntax Purpose Covered in


umask umask {number} Alter the default Lesson 3,
permissions on Topic A
newly created files
and directories.
chmod chmod [options] Modify the Lesson 3,
{mode} {file/directory permissions of a Topic A
name} file or directory.

chown Varies based on desired outcome: Change the owner, Lesson 3,


the group, or both Topic A
• Change the owner but not the
for a file or
group: chown {newowner}
directory.
{filename}
• Change both the owner
and the group: chown
{newowner}:{newgroup}
{filename}
• Change the group but
not the owner: chown
:{newgroup} {filename}

Lesson 3: Configuring Permissions

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 81 01/06/22 12:35 PM


82 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Command Syntax Purpose Covered in


chgrp chgrp {group name} Change the group Lesson 3,
{file/directory name} ownership of a file Topic A
or directory.
lsattr lsattr [options] List attributes Lesson 3,
{file/directory names} of a file or a Topic A
directory.
chattr chattr [-R] Change attributes Lesson 3,
[-v {version}] of a file or a Topic A
[+- {attributes}] directory.
{file/directory
names}
getfacl getfacl {filename} Retrieve the ACLs Lesson 3,
of files and Topic C
directories.
setfacl setfacl [-bR] Change the Lesson 3,
[-mx {acl_spec}] permissions Topic C
{file/directory associated with
names} the ACL of a file
or directory.

Practice Questions: Additional practice questions are available on the CompTIA


Learning Center.

Lesson 3: Configuring Permissions

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson03_pp061-082.indd 82 01/06/22 12:35 PM


Lesson 4
Implementing File Management
1

LESSON INTRODUCTION
This Lesson covers the Filesystem Hierarchy Standard (FHS) that defines consistent
locations for data across the various Linux distributions and makes it easier for
users to navigate among directories to find and manage files and directories. Users
rely on an understanding of the FHS to perform file management tasks such as
creating and deleting resources. This Lesson covers the necessary commands to
perform these file operations. In addition, commands such as find and locate are
used to search for resources using many different parameters.

Lesson Objectives
In this lesson, you will:
• Understand the Linux file system.

• Use file management commands.

• Locate files.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 83 25/05/22 6:43 PM


84 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 4A
Understand the Linux File System
2

EXAM OBJECTIVES COVERED


1.1 Summarize Linux fundamentals.
1.2 Given a scenario, manage files and directories.
3.1 Given a scenario, create simple shell scripts to automate common tasks.

Linux relies on a standardized series of directories to organize data into a


filesystem. The benefit of such standardization is that both administrators and
applications know where to find specific types of data. Configuration files are held
in one consistent location, and log files are held in a different consistent location.
This filesystem is named the Filesystem Hierarchy Standard (FHS). Sysadmins
must understand what types of files are held where. Navigate to these locations
utilizing paths, which may be defined from the root of the filesystem (represented
by the forward slash character) or from the user’s present location. Files may also
be linked, making their contents accessible from multiple locations within the
filesystem. This is usually done for convenience.

Linux File Organization


While there are a great many Linux distributions—thousands of them with varied
utilities for varied uses—there are a few things the distros have in common. These
common features allow compatibility between Linux offers and permit a certain
amount of comfort and standardization with regard to where to find specific types
of files. For example, Linux distributions store most configurations in the /etc
directory, most users have a private directory in the /home directory, and log files
are found in /var/log. Such standardization allows software installers to expect
resources in certain locations and sysadmins to anticipate where particular settings
can be found.
This standardization is achieved via the Filesystem Hierarchy Standard (FHS).

The Filesystem Hierarchy Standard


The Filesystem Hierarchy Standard (FHS) is a collaborative document that specifies
a set of guidelines for the names of files and directories and their locations on
Linux systems. Most Linux distributions are FHS-compliant and therefore support
compatibility with other systems. The FHS also creates a naming convention that
helps administrators, users, and applications consistently find the files they are
looking for as well as store files where other entities can easily find them.
As defined in the FHS, the top-most directory in a Linux file system is the root
directory, indicated by a single forward slash (/). Below the root directory are
various subdirectories that are standardized as part of the FHS.

Standard Subdirectories
/bin - Stores essential command-line utilities and binaries. For example, the
/bin/ls is the binary for the ls command.
/boot - Stores the files necessary to boot the Linux operating system.

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 84 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 85

/dev - Stores hardware and software device drivers. This directory maintains file
system entries that represent the devices connected to the system (for example,
the /dev/sda1 partition).
/etc - Stores basic configuration files. For example, the /etc/ samba/smb.
conf file stores Samba configuration data.
/home - Stores users’ home directories, including personal files.
/lib - Stores shared program libraries required by the kernel, command-line
utilities, and binaries.
/media - Stores mount points for removable media such as CD-ROMs and floppy
disks.
/mnt - This is the mount point for temporarily mounting file systems.
/opt - Stores optional files of large software packages. These packages normally
create a subdirectory bearing their name under the /opt directory and then place
their files in the subdirectory. For example, the /opt/nessus subdirectory
contains files for the Nessus vulnerability scanning program.
/proc - This is a virtual file system (VFS) that represents continually updated kernel
information to the user in a typical file format (for example, the /proc/mounts file).
/root - The home directory of the root user.
/sbin - Stores binaries that are used for completing the booting process and also
the ones that are used by the root user. For example, the /sbin/ifconfig file is
the binary for the ifconfig command that is used to manage network interfaces
on the system.
/sys - This is another VFS, and it primarily stores information about devices.
For example, /sys/block includes links to devices that are stored in various
subdirectories under the /sys/ devices/ location, which presents a hierarchy
of devices in the kernel.
/tmp - Stores temporary files that may be lost on system shutdown.
/usr - A read-only directory that stores small programs and files accessible to all
users.
The /usr directory contains some important subdirectories.
• /usr/bin - Includes executable programs that can be executed by all
users.
• /usr/local - Includes custom build applications that are stored here
by default.
• /usr/lib - Includes object libraries and internal binaries that are
needed by the executable programs.
• /usr/lib64 - Serves the same purpose as /usr/lib, except it is
meant only for 64-bit systems.
• /usr/share - Includes read-only architecture independent files. These
files can be shared among different architectures of an operating system.

/var - Stores variable files, or files that are expected to constantly change as
the system runs. Examples include log files, printer spools, and some networking
services’ configuration files.

The FHS is displayed by running the following command: ls / (recall that the
forward slash represents the root of the filesystem).

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 85 25/05/22 6:43 PM


86 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Key Directories
The critical directories to know from the FHS are /etc, /home, /root, and
/var/log.
/etc
The /etc directory contains files and subdirectories that hold configuration
information for the system and its services. It’s reasonable to assume that if you
need to adjust firewall rules, manage Secure Shell (SSH) access, or configure
software-management settings, you will need to work with files stored in /etc.

/home
The home directory contains a user’s personal files or files that are otherwise
specific to that user. The home directory is where you are placed when you log
in to the system. In Linux, by default, every user except the root user is assigned
a subdirectory in /home that corresponds to their user name. A user can create
subdirectories and files within this directory.
The home directory path is set to a variable named $HOME. When the string
$HOME is used, it references the path to the current user’s home directory, such as
/home/student-user. This text will often reference the home directory using
the $HOME variable. In many shells, including KornShell, C shell, and Bash, the tilde
character (~) represents your home directory.

Output of the ls-a command.

/root
The home directory of the root user is /root. This is not to be confused with the
root directory (/), which is the top-most part of the file system hierarchy.

/var/log
Linux and installed services typically write to log files stored in the /var/log
directory. As a sysadmin investigating a system issue or auditing system access, you
will likely find the information required in log files stored at /var/log.
Familiarity with all of the directories is important, but the directories listed above
are more commonly used and accessed.

Display File Metadata


When examining files it can be useful to display information such as permissions,
size, storage location, modification times, etc. The ls command has options that
provide much of this data, but the output may not be very clear. The stat and
file commands provide good information about file properties.

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 86 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 87

Use the stat and file Commands


The stat command displays file metadata in a relatively user-friendly structure.
File size, access information, storage data, and more are displayed. Use the man
page to display various options that supplement stat.
The syntax for the stat command is stat {filename}
The file command displays different metadata. Specifically, it examines the file
type and provides information based on that. It may show PDF version information
for .pdf files or image information for .jpg files. Such information is used to ensure
compatible applications are available to work with the files.
The syntax for the file command is file {filename}

Output of the file and stat commands.

File Naming Conventions


A file name is a string of characters that identify a file. By using the right
combination of characters in file names, you can ensure that the files are unique
and easy to recognize. On an ext4 file system, a file name may be up to 255 bytes
long and contain any byte except NULL (\0) and the forward slash (/). File names
of user files may not be a single dot . or two dots .. because these are special,
reserved file names. Various file systems may enforce different requirements for
file names. Although file names may contain a space, convention on Linux systems
dictates that words in a file name are more frequently demarcated by a hyphen or
an underscore, as these are easier to manage on the command-line. For example,
auditfile.txt or audit_file.txt are acceptable

Absolute and Relative Paths


A path defines the series of directories to be traversed to find a specific file (or
subdirectory). For example, if a text file is stored in the resources directory of your
home directory, the path defines what directories to travel through to arrive at the
file. There are two types of paths: absolute and relative.

Absolute Path
The absolute path defines the directories to traverse, starting from the root of
the filesystem. Recall that the filesystem root is depicted using a forward slash
character (/). The absolute path is the complete path from the top of the directory
structure.

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 87 25/05/22 6:43 PM


88 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Suppose a user named student-user wants to find the widgets.txt file, which
is stored in the inventory subdirectory of the resources directory of their home
folder. The absolute path is:
/home/student-user/resources/inventory/widgets.txt
Relative Path
A relative path is dependent upon the user’s current location in the filesystem.
Using the above scenario, if the user is already in their home directory, then the
entire path is unneeded, and all that needs to be specified is the remainder of the
path from the current location. Assuming the user is in their home directory, the
relative path is:
resources/inventory/widgets.txt
In other words, relative to your current location, what’s the rest of the path?

It is a good practice to use absolute paths in resources such as scripts and


configuration files. Relative paths may be different depending on where the file
resource executes from.

Configure File Links


The ln command creates a link to a file. Linking enables a file name in one
directory (the link) to point to a file in another directory (the target). A link does not
contain data of its own. It only contains a reference to the target file. Any changes
to the link will reflect in the target file. If you don’t specify the link name, the ln
command will create the link in your current working directory (CWD).

Helpdesk Ticket #01990


Submitted by: Department: Assigned to: Date Opened:
Ali Selassi Marketing you 2024-05-02

Subject Shorter path option?


Ticket Detail Hello, I’m regularly using a file that is buried in a bunch of
subfolders (the path is: /projects/2022/finance/YTDsales/
Final/salesdata.txt ). Can you help me with an easier way
to access this file rather than drilling down the directory
branches over and over?
Response Sure, I’ve set up a soft link in your home directory.
Look for the file at /home/aselassi and let me know if you
need anything else.
Date last updated 2024-05-03

Understand Inodes
An index node (inode) is an object that stores metadata about a file or directory
on a file system. This metadata can include time-based values such as when a file
was created and last modified, permission and ownership information, the block
locations of a file’s data on a storage device, and other miscellaneous information.

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 88 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 89

Each inode on a file system is identified by a unique integer called an inode


number. Whenever the system or an application tries to access a file, it searches for
the appropriate inode number in a data structure called an inode table. The inode
table maps an inode number to its corresponding file or directory name.
Some file systems set a maximum number of inodes when that file system is
created, usually by considering the overall size of the file system. The total number
of files and directories cannot exceed this inode maximum. However, some file
system types, such as XFS, use a dynamic inode allocation system that scales as a
percentage of the file system’s capacity. In other words, these file systems do not
set a strict inode limit.

Use the ls -i command to list the inode numbers for files and directories.

Link Types
Using the ln command, you can create two types of links: hard and symbolic
(soft). Hard and symbolic links are a feature of the file system and are common in
most file systems supported by Linux. The ext2, ext3, ext4, and XFS file systems all
support hard and symbolic links.
The syntax of the ln command is ln [options] {target name}
{link name}
The ln command has various options. Some of these options include:

Option for the ln Command Purpose


--backup Back up existing destination files.

-f Remove existing destination files.

-s Make symbolic links instead of hard


links.

-i Prompt to remove destination files.

-v Print the name of a file before linking.

Configure Hard Links


A hard link is a reference to another file; it enables the file’s data to have more
than one name in different locations in the same file system. Applications treat a
hard link as a real file. If the original file is deleted after a hard link is created, all its
contents will still be available in the linked file. This is because the inode of a hard
link is the same as its target; in other words, it points to the same object on the
file system. Hard links cannot be created between two directories, nor can they be
created between two files in different file systems.
The syntax for hard links is ln /business-docs/current-projects.
txt ~/projects.txt
Configure Symbolic Links
A symbolic link is a reference to a file or directory that can span multiple file
systems. If the original file or directory is deleted after a symbolic link is created,
then the original content is lost. This is because the inode of a symbolic link is
different from its target; in other words, it points to a different object on the file
system. A symbolic link is also known as a soft link.

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 89 25/05/22 6:43 PM


90 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The syntax for symbolic links is ls -s /business-docs/current-


projects.txt ~/projects.txt
Use the long format display of the list command to view link information: ls -l

Symbolic links are often referred to as "sym links" for short.

Symbolic link output, showing the "sym-file1" string.

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 90 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 91

Review Activity:
The Linux File System
3

Answer the following questions:

1. You are installing a new application on your Linux system. The


documentation states that configuration files and log files will be added
to your system. Where will these files likely be stored, and how does the
FHS make such installations easier?

2. You are in the new-projects directory, which is stored in the projects


directory within your home directory. What is the absolute path to the
new-projects directory?

3. A user submits a ticket regarding a file access issue. The first file,
projectA.txt, had a second hard link named my-project.txt. The same
data was available via either link. The user deleted the my-project.txt
file, and the data was still available via projectA.txt. The second file,
projectB.txt, had a sym link that pointed to the projectB.txt link. When
the projectB.txt link was deleted, the data was no longer available via
the sym link. The user wants to know why the first file is still available
after a link deletion but the second is not.

Lesson 4: Implementing File Management | Topic 4A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 91 25/05/22 6:43 PM


92 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 4B
Use File Management Commands
4

EXAM OBJECTIVES COVERED


1.2 Given a scenario, manage files and directories.
3.1 Given a scenario, create simple shell scripts to automate common tasks.

Once the FHS is familiar, navigation among directories is much easier. Commands
such as pwd and cd allow users to understand where in the filesystem they are
and how to move to another location. Over the years, shortcuts have been added
to reduce the amount of typing at the command prompt. Users must manage
file operations—tasks such as moving, copying, creating, and deleting files and
directories—to manage their data correctly. Users must also be able to redirect
information into or out of files.

Navigate Directories
Directories store system configuration files, user data, log files, and other
resources. Linux users move from directory to directory by using various navigation
commands. Shortcuts make the navigation process quicker and simpler.
Knowing how to navigate through the directories allows Linux users to understand
specific directory navigation information such as:
• Where in the file system you are.

• How to change where in the filesystem you are.

• How to use shortcuts to get where you want to go.

Navigation Shortcuts
Absolute and relative paths clearly delineate how to travel from one directory to
another, but over the decades, shortcuts have been established to make common
tasks easier.
The single dot character (represented by “.“) means “here“ or this directory. If your
present working directory is /home/USERNAME/resources, then that path
can be abbreviated as a dot: .
The term parent directory refers to whatever directory is above the current directory.
If your current location is /home/USERNAME/resources/inventory, then
the parent directory of inventory is resources. The parent directory of resources is
USERNAME. The parent directory is often referenced in commands (particularly with
cd), and it has been abbreviated as two dots (represented by “..“). In the above
scenario, the result of typing cd .. is to move to the resources directory. This is far
less typing than the absolute path of /Home/USERNAME/resources.
One of the most useful shortcuts is the tilde symbol (~). This abbreviation means
the home directory of the currently logged-in user. This is incredibly handy. A user
could type cd ~ instead of cd /home/USERNAME to jump to their home
directory. The ~ can be combined with many other commands covered below,
including copy and paste functions.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 92 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 93

Using the cd command to return to your home directory is so common that even the ~
is strictly necessary. If you type cd with no argument (path), Bash assumes you wish to
return to your home directory.

A command-line output showing all three ways (/home/student/, ~, and cd)


of getting "home."

Change Directories
The cd command moves your present working directory to another directory. For
example, if you type pwd and discover you are currently in your home directory,
then you could type cd /etc to move to the /etc directory, where many
configuration files are stored.
The cd command is the primary filesystem navigation command in Bash.
The syntax for the cd command is cd {path}
Note that either an absolute or relative path can be specified, depending on your
current location in the filesystem and the desired destination. To traverse the
filesystem to the inventory subdirectory in the resources directory of your home
directory, type the following:
cd /home/USERNAME/resources/inventory
Know Your Location
The critical piece of knowledge for navigation is to know your current location. In
Linux, this is referred to as the “present working directory,“ and the pwd command
displays that. The output is an absolute path from the root of the filesystem to the
directory the shell is currently focused on. The output from pwd may be used to
confirm your location before a backup job, a file transfer, or the deletion of files.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 93 25/05/22 6:43 PM


94 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The syntax for the pwd command is pwd

Output of the pwd command, showing that the user is in the /home/student directory.

Some Linux distributions are configured to display the name of the current directory
as part of the command prompt. Note that this is not the absolute path but merely the
name of the current directory. The prompt configuration can be changed.

It may be difficult to visualize a location in the filesystem with a text-based path.


This is especially true for users who are more familiar with graphical user interfaces.
The tree command displays the filesystem in a more familiar structure, perhaps
making it easier to understand a directory’s location relative to other directories.

Output of the tree command, showing a hierarchical representation of the directories'


relationship to each other.

The syntax for the tree command is tree {dirname}

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 94 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 95

Some options commonly used with tree are:

Option for the tree Command Purpose


-a Display all files, including hidden files.

-d Display directories only.

-s Display file size.

-D Display last modification date.

File Management Scenario: Starting the Project


In order to illustrate how these commands can be used, you’ll walk through a
common workplace scenario. In this scenario, you are responsible for managing
a project through file management tasks and use of commands. You, the project
manager, decide to create the appropriate directories and files to store the project.
In some cases, those files will need to be copied, moved, or renamed. Once the
project concludes, the files will be removed from the system. Throughout this
section, observe how file management commands are used to facilitate the project
management requirements.

What Directories Currently Exist?


You will store project files in your home directory. Before creating a directory
structure to store the files, you want to see what directories currently exist. The
command for displaying directory contents is ls (list).
You move to your home directory and then type ls. If no argument is included with
ls, it displays the contents of the current directory. However, you can display the
contents of the /etc directory by specifying the path to it.
For example, to display the contents of /etc, type:
# ls /etc
Options commonly used with ls include:

Option for the ls Command Purpose


-a Lists all contents, including hidden
resources.

-l Lists contents in long format, most


useful for displaying permissions.

-d Limits the output to directories but not


files.

-R Lists the contents of subdirectories.

-s Displays the file sizes.


Two of the most useful options are -a and -l. The two can be combined, such that
ls -al ~ displays all contents of the home directory in long format (showing
permissions for all files, including hidden ones).

Files where the first character is a dot (".") are hidden by Bash. This isn't a security
feature, but rather a way of keeping some files out of the user's way. Profile files are
often hidden. Use ls -a to display all files, including hidden files.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 95 25/05/22 6:43 PM


96 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Create a Directory Structure


Now that you, the project manager, understand what directories currently exist, it’s
time to create a directory structure to hold the files and subdirectories associated
with the project. The mkdir command creates directories along the specified path.
The syntax for mkdir is mkdir {new-directory-name}
You decide to create a single project directory, and inside that project directory you
create three subdirectories:
• $ mkdir project
• $ mkdir project/drafts
• $ mkdir project/final
• $ mkdir project/resources
You’ll use the ls or tree commands to display these directories.

Commands used to create a project directory with three subdirectories, and use of the ls
command to display the directories.

Create Project Files


Files can be created using multiple methods, including text editors and copy
commands. To create a simple empty file, use the touch command. The original
purpose of touch is to update a file’s timestamp (useful for backup programs), but
one effect of the command is if the specified file doesn’t already exist, it then gets
created.
The syntax for touch is touch {filename}
You’re now ready to create project files. First, the user types the cd project
command to move into the project directory. Next, project files are created with
touch by typing:
  
# touch newprojects.txt completedprojects.txt
timeline.txt

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 96 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 97

File Management Scenario: Working the Project


As project manager in our scenario, you now work through the tasks and
deliverables involved in the project, having established your directories and
project files.

Copy and Move Project Files


The files created in the previous section now exist in the project’s directory, but they
aren’t well organized. The cp (copy) and mv (move) commands allow users to place
files in the directory structure.
Duplicating files allows multiple copies of the same file. A common use for copying
a file is as a backup. For example, before making a configuration change to a service
such as SSH, it is prudent to copy the original configuration file. Doing so provides
the opportunity to return the service to its original configuration if necessary.
The syntax for cp is cp {sourcefile} {newfile}

It is a common practice to copy or back up a configuration file before making


significant changes to it. Doing so allows the sysadmin to return the system to an
earlier configuration. For example, before making major configuration changes to the
SSH service, the sysadmin might use the cp command to copy the /etc/ssh/
sshd_config file to /root/sshd_config.old. The .old file extension is
a common way of identifying such files.

While copying a file creates a new file (a duplicate of the original), moving a file
typically places the file elsewhere in the filesystem. While the file itself may not
move from its location on the hard drive, pointers to the file will be updated with a
new location.
The mv command moves one or more files from one location to another. Like cp,
the mv syntax is to specify the source location first and the destination location
second.
The syntax for the mv command when moving a file is mv {source-
location} {destination-location}
For example, to move a fileA from your home directory to the Projects directory in
your home folder type:
$ mv fileA Projects
However, the mv command has a second function. It also serves as the rename
command in Bash. The syntax is the same, but the terms shift to original-filename
and new-filename. The syntax for the mv command when renaming a file is mv
{original-name} {new-name}
For example, to rename an existing file named “sales-project.txt“ to “marketing-
project.txt“, type:
$ mv sales-project.txt marketing-project.txt
In the project management scenario, the cp and mv commands are very useful for
organizing files.
First, you’ll copy the timeline.txt file to the resources directory:
$ cp timeline.txt resources/
Next, you move the newprojects.txt file to the drafts subdirectory:
$ mv newprojects.txt drafts/

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 97 25/05/22 6:43 PM


98 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Finally, the completedprojects.txt file is renamed to oldprojects.txt:


$ mv completedprojects.txt oldprojects.txt
Display Project File Contents
The cat command (short for concatenate) is used to combine file contents from
multiple sources into one. It’s much more common, however, to use the command
to display file contents. This is especially useful for content that consumes less than
one screen’s worth of space.
The syntax for the cat command is cat {filename}
You’ll use the echo command and a redirector to add some text to a file:
$ echo "Q1 goals" > drafts/newprojects.txt
Confirm the text exists in the newprojects.txt file by using the cat command:
$ cat drafts/newprojects.txt

Using the cat command to confirm the newly created text exists in the newprojects text file.

Redirectors such as > are covered later in this Topic.

There are many ways to display file contents besides using cat. A text or
configuration file may be opened with a text editor such as Vim or Nano, or
database resources may be accessed via database programs such as MariaDB.

File Management Scenario: Closing the Project


The final step in the life cycle of data is to dispose of the files and directories. Once
a project is completed it may no longer be necessary to retain the files. The rm and
rmdir commands delete files and directories.
Remove Directories and Files
At this point you wish to delete one of the directories. The directory delete
command is rmdir with the directory name as the argument: rmdir
{dir-name}.
If the final directory is empty, you type:
$ rmdir final
The rm command deletes files. Many Linux distributions are preconfigured to ask
for confirmation before deleting a file (there is no undo for the rm command!).

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 98 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 99

You may be prompted to enter Y or N to complete the deletion process. Common


options for the rm command include:

Option for the rm Command Purpose


-f Never prompt for confirmation (this is
a dangerous course of action).

-i Interactive mode, prompt for


confirmation before deleting (this is
usually set by default with an alias).

-R Recursively removes a non-empty


directory and its contents.
To delete the file, you type rm timeline.txt, and a ls of the project
directory shows the file is now gone.
The rmdir command works on empty directories but fails with directories that
contain files. The rm command, however, may be used to remove non-empty
directories. To remove the newprojects directory and the files in it, type:
$ rm -fR newprojects

Observe that to delete an empty directory, the command is rmdir, but to remove a
non-empty directory, the rm command is combined with the -R (recursive) option.

If the user is in their home directory, the entire project directory structure can be
deleted by using the rm command and the -R option. Again, be very certain about
what’s being deleted before running this command:
$ rm -fR project
Use the ls command to confirm the project directory and its contents are gone.

Files are not recovered from the CLI. There is no concept of a trash can from which to
recover deleted files. Be careful before using the rm and rmdir commands!

Summarizing the File Management Scenario


In this scenario, the project manager creates a hierarchical directory structure to
store project data. The mkdir command creates the directories. The touch
command creates sample text files to simulate project data. Commands such as
mv and cp allow for file management, while cat provides a look at file contents.
Finally, the rm and rmdir commands delete the resources once the project is
complete.

Display Files with Additional Commands


The cat command is just one of the ways to display file contents. Many other
commands both display the contents and permit more focus on exactly which
data you wish to see. Commands such as less and more allow paging through
text, while head and tail show just the beginning or end of files. The grep
command allows for keyword searching within files or other output.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 99 25/05/22 6:43 PM


100 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Display File Contents with less and more

Helpdesk Ticket #01991


Submitted by: Department: Assigned to: Date Opened:
Kai Garcia Engineering you 2024-05-04

Subject can’t view reports


Ticket Detail I’m pulling up a report that covers 3 years of projects, and
it’s impossible to read. How can I shorten the display?

Date last updated 2024-05-06

Not all file contents fit on the display. When using cat to display a long file, only
the contents at the bottom of the file may fit on the monitor. The remainder scrolls
upward, off the screen. The less command breaks the output into pages that fit
on the screen and can be cycled through.
There are two ways of using less. The first is directly, as a primary command to
display file contents. An example is less long-file.txt. The second way to
use less is to better organize the output of other commands. For example, the
/etc directory has many subdirectories and files—too many to display on the screen
simultaneously. The output of a ls command can be redirected into less, which
allows pagination through the output of ls.
The syntax for this example is ls /etc | less

The pipe character | is discussed later in this Topic in the redirectors section.

The more command is similar to less. The primary difference between the two
commands is that with less, you can paginate up and down, while with more you
can only paginate downward.

Display File Contents with head and tail


Sometimes it’s useful to see only the beginning or the end of a particular file. As a
general rule, configuration files have comments and instructions at the beginning
or top of a file. These comments may provide guidance, version information, and
examples for the file. The head command displays the first 10 lines of a file, giving
administrators valuable information about the file.
The syntax for the head command is head {filename}
Few options exist to modify the head command. The most common option is to
change the number of lines displayed from the default of 10. For example, typing
head -n 15 {filename} will display the first 15 lines of the file.
Log files, however, have the newest information appended at the end of the file.
Hence, if an administrator wishes to see the most recent log file entries, the bottom
of the file must be displayed. The tail command, by default, shows the last 10
lines of a file. This is incredibly helpful for troubleshooting.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 100 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 101

The tail command also has some very practical options. Like head, the tail
command accepts the -n option to modify the number of displayed lines. In
addition, the -f (or follow) option updates the output whenever the bottom of the
file changes. This is useful for following log files, as the display will update whenever
the log file changes.
The basic syntax for the tail command is tail {filename}
To display the last 15 lines of the file, type tail -n 15 {filename}. However,
to follow a log file and see updated output whenever the log file changes, type
tail -f {filename}.

Display Strings with grep


You’ve received a helpdesk ticket from a user who requests a keyword search of a
report. Your solution in this case is to teach them grep.

Helpdesk Ticket #01992


Submitted by: Department: Assigned to: Date Opened:
Joseph Deng Engineering you 2024-05-05

Subject Engineering project report - search?


Ticket Detail I need some help in searching this report by a few key
terms, can you help?
Date last updated 2024-05-06

Commands such as less and tail display the specified file contents, regardless
of whether it contains the data administrators or users need. These commands
don’t search for particular information within the file, they simply display its existing
content.
The grep command is a pattern matcher, which is a complex way of saying it
searches for strings of characters within a data stream. For text files, grep is a find
utility that displays the specified string or search term in the output.

The grep Command


The grep command can be used directly on a file. For example, the command
grep error /var/log/messages searches the messages log file for the
combination of characters that spell “error.“ Any lines of the file containing that
combination of characters in that order are displayed.
Note that grep is case-sensitive, so in the above example, it would match the
string “error,“ but it would fail to display the string with a capital E “Error.“ The -i
option makes grep case insensitive. Modifying the above example to grep -i
error /var/log/messages would display both “error“ and “Error“ if those
strings exist in the file. It would also match any other combination of uppercase and
lowercase characters in that string.
The grep command provides even more functionality when combined with other
commands. Many commands produce a significant amount of output, which users
then have to browse through to find what they need.
The pipe character | takes the output of one command and makes it the input of
another. One of the most common uses of pipe is in combination with grep.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 101 25/05/22 6:43 PM


102 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The syntax for these combinations can take on several different forms.
To list all files in the /etc directory that contain the string “net“ in either uppercase
or lowercase:

To list all files in the /home/student directory that contain the string “.txt“:

To check for the string “jdeng“ in the /etc/passwd file:

To check for the string “localhost“ in the /etc/hosts file:

The pipe (|) character is covered in more detail in the next section of this lesson. The
ps command is also covered later in the course.

The egrep command is a modified version of grep and functions similarly from
the user perspective, but this utility is deprecated in favor of grep -E.

Redirectors
All of this management and manipulation of files is useful for more than just
looking at the results in a terminal. When you use the terminal, or log out entirely,
you’ll want to ensure that crucial information is stored in a file for later retrieval
and analysis. In addition, you’ll benefit from combining multiple commands in
conjunction, making your administrative duties more efficient and powerful.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 102 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 103

Understand Text Streams


A text stream is a sequence of one or more lines of text that applications can
leverage to read from or write to a particular device or system component. This
enables the application to interface with components such as the CLI, files, network
sockets, and more while hiding those components’ details from the application. In
most Linux shells, there are three stream types: standard input, standard output,
and standard error.
Standard input, or stdin, is a text stream that acts as the source for command
input. Standard input for the Linux command-line is usually generated from the
keyboard. In the case of the GUI, the standard input can also come from the mouse.
Standard output, or stdout, is a text stream that acts as the destination for
command output. By default, standard output from a Linux command is directed to
the CLI.
Standard error, or stderr, is a text stream that is used as the destination for error
messages. By default, the standard error stream prints error messages at the CLI.
Redirection is the process of accepting input data from a source other than the
keyboard and sending output data to a destination other than the display device.
In other words, you can use redirection to bypass the default devices when working
with input/output (I/O). Redirection is commonly used to accept input from files or
send output to files using the stdin, stdout, and stderr streams.

Use Redirection Operators


Sysadmins use several operators to redirect input or output.

Redirection
Operator Action Example Results
> Redirect the standard ls > file1.txt The output of the
output to a file. ls command is
redirected to a file
named file1.txt
>> Append the standard ls >> file1.txt The output of the
output to the end of ls command is
the destination file. appended to a file
named file1.txt
2> Redirect the standard ls file3.txt 2> The output will not
error message to a errorfile.txt be displayed on
file. the screen but is
redirected to a file
named errorfile.txt
2>> Append the standard ls file3.txt 2>> The output will not
error message to errorfile.txt be displayed on
the end of the the screen but is
destination file. appended to a file
named errorfile.txt
&> Redirect both the ls file1.txt file3.txt The output will not
standard output and &> errorfile.txt be displayed on
the standard error the screen but is
message to a file. redirected to a file
named errorfile.txt

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 103 25/05/22 6:43 PM


104 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Redirection
Operator Action Example Results
< Read the input from mail user@ The myletter.txt
a file rather than address < file is taken as the
from the keyboard or myletter.txt input and attached
mouse. to the email
message.
<<{string} Provide input data cat <<EOF The cat command
from the current This is a here will use the rest
source, stopping document. of the lines in this
when a line EOF file as input. It will
containing the stop accepting
provided string that input when it
occurs. When placed reaches the string
in a script, this is EOF. This string
called a here can be named
document. anything you want.
The output of the
cat command
would therefore
be: This is a here
document.
Redirection operators, their syntax, and results.

Command Modifiers
Several command modifiers exist that allow users to run combinations of
commands. These commands differ from redirectors in that they manipulate the
command, not the output. Learning to use these effectively makes command-line
administration more efficient.

Background a Command
The single ampersand & causes the command to execute in the background.
Normally, when a command is executed, it consumes the shell until it completes.
Some commands, such as backup scripts, may take a very long time to finish, and
until the script is done, the user cannot type in additional commands or accomplish
additional tasks in that shell instance. If the command runs in the background,
however, it executes while the user continues to work within the shell. Such
commands are referred to as jobs.

Process and job management is covered in a later section.

The syntax is the command, followed by a space, followed by an ampersand:


$ sudo backupscript.sh &
Chain Commands
Many Linux users will simply enter one command at a time. In some cases,
however, it is useful to enter multiple commands at a single command prompt. This
approach is known as “chaining,“ and there are several tools in Bash to help you
with this process.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 104 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 105

Standard interaction with the Bash shell involves typing a command, executing the
command, and then typing another command for execution. Commands can be
written sequentially at a single command prompt to be processed in order. There
are multiple ways of doing this.
Piping is the process of combining the standard I/O streams of commands. It uses
the standard output of one command as the standard input for another command.
The output format of the first command should be compatible with the format that
the second command works with. The pipe operator (|) can be used with most
commands in Linux.
$ ls -l | grep audit
This command, which searches for files named “audit,“ is an example of using a
pipe. The standard output of the ls -l command is fed as standard input into the
grep audit command so that grep searches for the term within the directory
listing.

Chain Operator
Character Common Name Results
; semicolon If the semi-colon character is
placed between commands,
they are run one after another,
regardless of whether the
previous command completed
successfully.
&& logical AND If the logical AND is placed
between commands, the
following command is only run
after the previous command
completed successfully. Useful
for commands that rely on
each other’s success.
|| logical OR If the logical OR is placed
between commands, the
following command is only run
if the previous command fails.
! bang If the bang is placed in a
command expression, it
negates the expression. Used
as a way of stating “except
this.“

Many of these command chains and redirectors are used in scripts. Scripts are covered
in a later section.

These command modifiers do not use a typical or regular syntax. Instead, they are
used between commands to modify certain portions of the command expressions.
To run a series of commands one after another:
$ backupscript.sh;rmdir /projects;mkdir holidays.txt
To run a series of commands that rely on the success of the previous command:
$ backupscript.sh && rmdir /projects

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 105 25/05/22 6:43 PM


106 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

To run a second command only if the first command fails:


$ backupscript.sh || cp projects /tmp
The tee Command
The tee command reads the standard input, sends the output to the default
output device (the CLI), and also copies the output to each specified file. This
command enables you to verify the output of a command immediately as well
as store that output in a file for later reference. It accepts input from another
command using the pipe operator. When used with the -a option, tee appends the
output to each output file instead of overwriting it.
The general syntax of the tee command is command
[options]
[arguments] | tee [options] {file names}
Let’s say you want to check the contents of a directory and also output those contents
to a file to process later. You could issue separate commands to do this, or you can
use the tee command in the following manner: ls -l | tee listing.txt

The xargs Command


The xargs command reads from standard input and executes a command for
each argument provided. Each argument must be separated by spaces. The pipe
operator is used to make the output of the first command the input for the second
command. The xargs command is commonly used with the find command to
operate on each result that is found within the file or directory search.
The general syntax of the xargs command is command [options]
[arguments] | xargs [options] {command}
Let’s say you want to delete all of the files in the /projects directory that have a
.pdf extension. You can use xargs to automate the process: find /projects
-type f -name "*.pdf" | xargs rm. The find command searches
for all files in /projects that have a .pdf extension, then pipes the result to
the xargs command. Because the results are delimited by a space, the xargs
command will execute the rm command for each file in the results— removing all
PDF files in the directory.
The xargs command has several common options.

Option for the xargs Command Purpose


-I {replacement string} Consider each line in the standard input
as a single argument.

-L {number of lines} Read a specified number of lines from


the standard input, and concatenate
them into one long string.

-p Prompt the user before each command.

-n {number of arguments} Read the maximum number of arguments


from the standard input, and insert them
at the end of the command template.

-E {end of string} Represent the end of the standard input.

-t Write each command to the standard error


output before executing the command.

-s {max size} Set the maximum allowable size of an


argument list to a specified number of
characters.

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 106 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 107

Review Activity:
File Management Commands
5

Answer the following questions:

1. You have been assigned a helpdesk ticket to answer a user question. The
user is attempting to rename files but cannot find the rename command.
What command do you teach the user?

2. A user asks how to delete a directory named /projects containing 100


directories. The user does not want to delete the files individually and
does not want to be prompted to confirm the deletion of each file. What
is the appropriate command expression, and why?

3. A user complains that they redirected the output from several


commands into a text file, but the only content that appears in the file
is the output from the most recent command. How would you explain to
the user what happened and how to correct the problem?

Lesson 4: Implementing File Management | Topic 4B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 107 25/05/22 6:43 PM


108 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 4C
Find File Locations
4

EXAM OBJECTIVES COVERED


3.1 Given a scenario, create simple shell scripts to automate common tasks.

Users and sysadmins may struggle to find older files managed by the system and
applications. The find command permits users to search for files based on specific
parameters such as name, ownership, permissions, and more. Users can use
commands such as which to discover where files were executed. Finally, many
file manipulation commands, such as sed, awk, wc, echo, and others, help
sysadmins find data available within files.

Search Commands
Even though the Linux filesystem is fairly well organized by the Filesystem Hierarchy
Standard, and users have file management options with mkdir, mv, and grep
commands, sometimes files are lost or their location is unknown. The primary
command for searching for files using parameters is the find command. The
locate command is an alternative that may make searching easier in a very large
filesystem. Finally, the which command displays where a command executable file
is stored.

The find Command

Helpdesk Ticket #01993


Submitted by: Department: Assigned to: Date Opened:
Joseph Deng Engineering you 2024-05-10

Subject lost file - help!


Ticket Detail I cannot find my file NICspecs.txt, it’s just gone. How can I
get it back?

Response Hi Joseph, you can search by the file name or by the file
owner using the find command.
Date last updated 2024-05-10

The find command searches the filesystem for files that match the given parame-
ters. These parameters might be file size, modification date, owner, or even permissions.
The find command is a powerful tool for managing files.
The syntax for find is more complicated than some other commands. The general
syntax is:
# find {where to search} {search criteria}

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 108 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 109

For example, to search for a file named “business-plan.txt“ in the projects directory
within your home directory, type:
# find -name business-plan.txt /home/USERNAME/
projects
The -name option specifies to search by name.

Option for the find Command Purpose


-name Search by name.

-type f Search by resource type file.

-type d Search by resource type directory.

-perm Search by permissions level.


For example, to search for any files in the /etc directory with the rwx permissions
for ugo, type:
# find /etc -perm 777
Though this example uses absolute mode, find is capable of interpreting symbolic
mode as well.

A search by permissions of the /home/student directory returns only those files with the
664 access level.

The locate and updatedb Commands


The find command is not the only search option for the filesystem. The locate
command can also search for files and directories along a specified path. Locate
relies on an index database for its search. While locate may be quicker due to this
index, it’s only accurate when the index is current.
The syntax for the locate command is locate [options] {string}
Sometimes the search you’re doing should ignore uppercase and lowercase
characters. The -i option disables case sensitivity.
For example, to search for a file named “reports.txt“ in the current directory, type:
# locate reports.txt.

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 109 25/05/22 6:43 PM


110 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The updatedb command is used to both build and update a database of files
based on the /etc/updatedb.conf file. The database itself is located at
/var/lib/mlocate/mlocate.db. The configuration file can be set to
exclude particular directories that should not be indexed by the utility.

Comparing find and locate Commands


The locate command searches a database and retrieves information on files
present on the system. However, failure to keep this database updated may
produce outdated results. The find command, on the other hand, performs
a live search of the filesystem and may concentrate on a specific location.
The find command may take more time to complete a search than the locate
command.

The which Command


The which command displays the complete path of a specified command by
searching the directories assigned to the PATH variable. For example, upon entering
which cat, the following output is displayed: /bin/cat.
The which command can help you locate where a program has been installed.
It can also help identify which version of a command you’re using if there are
multiple binaries of the command stored in different locations. By identifying
where a command is running, you can troubleshoot unexpected behavior more
easily.
The syntax for the which command is which {command}

Using the which command to display the complete path of a command.

File Manipulation Commands


Various commands are available to manipulate existing files or to display file
information. These commands might append text to files, conduct find-and-replace
operations, count words or characters in a file, sort file contents, or compare the
contents of two files.

The echo Command


The echo command is used to display a line of text on the terminal. You can also
use the echo command to write text to a file by providing the string after the
echo command and redirecting to the file.
The syntax of the echo command is echo {string}

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 110 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 111

The printf Command


The printf command is similar to echo but provides the user with much more
control over how the output is formatted. You can supply various format characters
within the text you want to output, using a backslash (\) to indicate when they are
being used. For example,
$ printf "Hello.\nWhat's your name?"
will print:
Hello.
What's your name?
This is because \n is the newline format character, and it automatically adds a new
line wherever it is placed.
The printf command also supports conversion characters, which use a percent
sign (%) to indicate when they are being used. Conversion characters are typically
used in scripts to change the output of a variable, like dictating the number of
decimal places to print after a precise calculation.

The tr Command
The tr command is used to translate a string of characters. It is predominantly
used to change the case of letters in a file. This command acts only on a stream of
characters and does not accept file names as arguments. You must use redirection
to actually change a file.
The syntax of the tr command is tr {character 1} {character 2}
where {character 1} is the character to be replaced.

The wc Command
The word count (wc) command is used to count the number of lines, words, and
characters in a text file. If multiple files are specified, then the command displays
the counts for each file and the total count for all files.
The syntax of the wc command is wc [options] {file-names}
The wc command provides various options that enable you to specify the nature of
the output.

Option for the wc Command Purpose


-c Display the byte count.

-m Display the character count.

-l Display the newline count.

-w Display the word count.

Here is an example of combining the find command with wc to display how


many files in the /sales directory match the search parameters of 775
permissions:
$ find /sales -perm 775 | wc -l

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 111 25/05/22 6:43 PM


112 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The sort Command


The sort command arranges the lines within a file. Some of the most common
sort command options are in this table.
Option for the sort Command Purpose
-k{column numbers] Specify field values. For example, -k2
indicates the second field.
-n Compare and sort lines based on the
string numerical value.
-r Sort fields in descending order. By
default, the fields are sorted in
ascending order.
-t{delimiter} Separate one field from another.

The syntax of the sort command is sort [options] {file-names}

The cut Command


The cut command extracts the specified lines of text from a file using any of the
common options found in this table.

Option for the cut Command Purpose


-c Specify the number of the character
to cut from each line.
-d{delimiter} Separate one field from another.

-f{field numbers} Specify the field numbers to cut, as


separated by the delimiter. For example,
-f2 indicates the field between the first
and second instances of the delimiter.
-s Suppress a line if the delimiter is not
found.

The syntax of the cut command is cut [options] {file-names}


The paste Command
The paste command is used to merge lines from text files horizontally. Each line
of an initial file is a row in the first column; using paste, you specify a second file,
and every line of the second file becomes a row in a newly created second column.
By default, the paste command uses a tab space delimiter to separate each
column. You can use the -d option to specify a different delimiter.
For example, you have a file named cities that contains the city names New
York, Tokyo, London, and Lima. You have a second file named countries that
lists the four corresponding countries United States, Japan, United Kingdom, and
Peru. The output of paste -d , cities countries merges the two:
• New York,United States

• Tokyo,Japan

• London,United Kingdom

• Lima,Peru

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 112 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 113

The diff Command


The diff command is used to compare text files. The command displays the two
files and the differences between them. Using various symbols, the output suggests
how you can change one file to make it identical to the other. Each symbol has a
special meaning. The less-than symbol (<) with a line after it means that line should
be removed from the first file because it doesn’t appear in the second. The greater-
than symbol (>) with a line after it means that line should be added from the second
file. In addition, the diff command also denotes the line numbers for each file
that would be affected by deletion, addition, and change operations.
The syntax of the diff command is diff {file-name 1} {file-name 2}
You can specify the nature of the output with these options:

Option for the diff Command Purpose


-b Ignore spacing differences.

-i Ignore case differences.

-t Expand tab characters in output lines.

-w Ignore spacing differences and tabs.

-c Display a list of differences with three


lines of context.

-u Output results in unified mode, which


presents a more streamlined format.

The awk Command


The awk command performs pattern matching on files. It is based on the AWK
programming language. The awk keyword is followed by the pattern, the action to
be performed, and the file name. The action to be performed is given within curly
braces. The pattern and the action to be performed should be specified within
single quotes. If the pattern is not specified, the action is performed on all input
data. Similarly, if the action is not specified, the entire line is printed.
The awk command can be executed from the command-line or from within an AWK
script file. The awk command can be used to process text files in a variety of ways,
such as extracting text matching a certain pattern, deleting text matching a certain
pattern, adding text matching a certain pattern, and many more.
The syntax of the awk command is awk [options] ['patterns
{actions}'] {file-names}
In awk scripts, you can provide patterns along with blocks of code. If a pattern
matches any line in the input file, the code block in the script will be executed.
For example, the following awk query retrieves all records in the example.txt
file beginning with “a“, “b“, or “c“:
$ awk '/[abc]/' example.txt
To retrieve all records whose first field contains the value “abc“ from the
example.txt file, type awk awk "abc" example.txt

The sed Command


The sed or stream editor command is a program that you can use to modify text
files according to various parameters. The sed command can also be used for
global search and replace actions.

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 113 25/05/22 6:43 PM


114 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Some of the more common options for sed are:

Options for the sed Command Purpose


d Delete the lines that match a specific
pattern or line number.

-n,p Print only the lines that contain the


pattern.

s Substitute the first occurrence of the


string in the file.

s,g Globally substitute the original string


with the replacement string for each
occurrence in the file.

The general syntax of the sed command is sed {'option/address/


action'} {file-names}
Addresses tell sed to act only on certain lines or to act only on text that matches
a given regular expression pattern. They are optional. Addresses are followed by
the action to be performed when a match is found. The last argument is the name
of the input file. The option, address, and action parameters are typically enclosed
within single quotation marks.

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 114 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 115

Review Activity:
File Location
5

Answer the following questions:

1. You are conducting a security audit and need to document user access
to log files—specifically whether any files are world-readable or whether
any allow rwx access to all users. How can the find command be used in
such a project, and what specific command might you use?

2. A coworker on the helpdesk team is troubleshooting an issue where a


user is attempting to run a command, but the command is not executing.
Your coworker needs to discover where the command executes from as
part of the troubleshooting process. What command(s) can you suggest?

3. A senior sysadmin suggests that commands such as sed, awk, and sort
are just as useful in automation as at the command-line. How might
commands such as these be used in automation?

Lesson 4: Implementing File Management | Topic 4C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 115 25/05/22 6:43 PM


116 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Lesson 4
Summary
4

Data stored on a Linux system is organized using directories. Because there


are many different Linux distributions, directories are standardized into
the Filesystem Hierarchy Standard to allow compatibility for both users
and applications. Linux users must understand their current location in the
filesystem and how to interpret paths to other locations. These skills are directly
related to file operations and management, which involves the creation and
deletion of files and directories. Often, users will search the filesystem for
resources needed.

Guidelines
These best practices and guidelines are provided for your use as revision tools or as
quick references in your job role.
• Recognize file management commands

• Display all file contents by using cat

• Display the end of file contents by using tail

• Display file contents in a paginated format by using less

• Use redirectors to place command output into files.

• Use redirectors to send command output as the input for additional


commands

Command Reference Table


This list of commands and their associated syntax can also be found in
Appendix B.

Command Syntax Purpose Covered in


stat stat {file-name} Display file metadata in Lesson 4,
a relatively user-friendly Topic A
structure.
file file {file-name} Display file information Lesson 4,
based on the file type. Topic A
ln ln [options] Create links, either hard Lesson 4,
{target-name} or symbolic. Topic A
{link-name}
cd cd {path} Move your present Lesson 4,
working directory to Topic B
another directory.

Lesson 4: Implementing File Management

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 116 25/05/22 6:43 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 117

Command Syntax Purpose Covered in


tree tree {directory- Display the filesystem in Lesson 4,
name} a hierarchical structure, Topic B
perhaps making it
easier to understand
a directory’s location
relative to other
directories.
mkdir mkdir {new- Create directories along Lesson 4,
directory-name} the specified path. Topic B

cp cp {source-file} Copy a file into a new Lesson 4,


{new-file} location while retaining Topic B
the source file in its
original location.
mv mv {source- Place the file elsewhere Lesson 4,
location} in the filesystem. Topic B
{destination-
location}
mv mv {original- The rename command Lesson 4,
filename} in Bash. Topic B
{new-filename}
rmdir rmdir Remove (delete) a Lesson 4,
{directory- directory with no files Topic B
name} in it.

rm rm [options] Remove (delete) a file or Lesson 4,


{file-name} a non-empty directory. Topic B

head head {file-name} Display the first 10 lines Lesson 4,


of a file. Topic B
tail tail {file-name} Display the last 10 lines Lesson 4,
of a file. Topic B
grep grep {character- Search for strings of Lesson 4,
string] characters within a data Topic B
stream. Grep is case-
sensitive unless the -i
option is used.
xargs command Read from standard Lesson 4,
[options] input and executes a Topic B
[arguments] | command for each
xargs [options] argument provided.
{command}
tee command Read the standard input, Lesson 4,
[options] sends the output to the Topic B
[arguments] | default output device
tee [options] (the CLI), and also copies
{file names} the output to each
specified file.

Lesson 4: Implementing File Management

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 117 25/05/22 6:43 PM


118 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Command Syntax Purpose Covered in


find find {where to Search the filesystem for Lesson 4,
search} {search files that match the given Topic C
criteria} parameters.

locate locate [options] Search for files and Lesson 4,


{string} directories along a Topic C
specified path.
updatedb updatedb Build and update a Lesson 4,
database of files based Topic C
on the /etc/updatedb.
conf file.
which which {command} Display complete path of Lesson 4,
a specified command. Topic C

Practice Questions: Additional practice questions are available on the CompTIA


Learning Center.

Lesson 4: Implementing File Management

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson04_pp083-118.indd 118 25/05/22 6:43 PM


Lesson 5
Authoring Text Files
1

LESSON INTRODUCTION
Linux users edit text files in day-to-day activities and when making system
configuration changes. Because a graphical user interface (GUI) is not always
available, visual menus are not always possible; text editing in Linux is very different
from text editing in other platforms. Text editors rely on various modes and
metakeys to enable functions such as save and copy/paste. It’s also essential to
ensure that files are backed up, protected, and that their integrity is guaranteed.
This Lesson focuses on Linux text editors such as Vim and archiving tools such
as tar.

Lesson Objectives
In this lesson, you will:
• Edit text files.

• Manage text files.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 119 25/05/22 10:01 AM


120 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 5A
Edit Text Files
2

EXAM OBJECTIVES COVERED


1.2 Given a scenario, manage files and directories.

Text file editing is a basic but essential skill for Linux users. In Linux the graphical
user interface is optional, making text editing unique in Linux compared to other
operating systems. If the Linux system does not have a GUI, editors that rely on
mouse-driven menu options cannot be used. Sysadmins must use the keyboard
only to access all text editor program functions in this case. This Topic covers the
common Linux text editors that all users should be familiar with. It is critical to be
able to open, edit, save, and close files with any Linux editor.

Configuration File Concepts


Most Linux configurations are held in text files. Settings such as network addresses,
video and display options, device initialization, and even user profiles are stored in
text files. The role of sysadmins is to manage the Linux server’s configuration. To
change system settings, one must often edit these configuration files.
Recall that most Linux servers do not use a graphical user interface (GUI), and
therefore word processing programs with mouse-clickable interfaces are not
commonly available. Instead, text editors controlled entirely from a command-
line interface are used to manipulate these configuration files. There are many text
editors available for Linux, but two of the most common are Vim and Nano.
For example, the SSH (Secure shell) program is frequently used for remote
administration with Linux systems. A text file at /etc/ssh/sshd_config must
be edited to configure who is allowed to remotely connect to the server, what level
of remote access they will have, and to present a warning or instructional message
to the connecting user. The sysadmin must be proficient with text editors to ensure
the server is properly configured for remote administration.

Common Text Editors


GUI-based text editors like gedit are usually self-explanatory and offer familiar
functions. Tasks such as opening files and saving changes are handled via menus.
Text editors that operate at the command-line, such as Vim and Nano, do not have
mouse-driven menu options. Instead, these editors rely on keyboard keystrokes to
manage the file. Nano accomplishes this by using the Ctrl metakey. Vim switches
among different modes. Depending on the mode, the keyboard interacts differently
with the program.

Text Editor Name Description


vi A visual text editor that was originally created for
Unix® and was later cloned into FOSS versions.
Vim The default text editor in most Linux distributions.

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 120 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 121

Text Editor Name Description


Emacs A flexible, powerful, and popular text editor used in
Linux and Unix.
gVim The graphical version of the Vim editor.
gedit A simple yet powerful GUI-based text editor used in
the GNOME desktop environment.
GNU nano A small, user-friendly text editor.

Vim
The “Vi Improved,” or Vim editor, is installed on most distributions. It is extremely
powerful and a little complex, but the general functionality is straightforward. Vim
has three modes. When switching modes, the keyboard will react differently. For
example, pressing the w key in one mode inserts the “w” character in the text of the
file. In a different mode, however, the w key writes or saves changes to the file.

The older version of Vim is named vi (pronounced “vee-eye”), and it is not often used
on modern Linux systems. Frequently, when a user types vi to invoke the editor, the
Vim editor is automatically invoked instead. The vi editor is more limited, but its basic
functionality is the same as that of Vim.

The opening page of Vim.

To make working with Vim easier, begin by memorizing what the three primary
modes do and how to switch among them.
Both Command Mode and Execute Mode manipulate the file by doing an action
such as creating or saving a file, while Insert Mode actually manages the text in a
file (writing or deleting words). The default mode you see upon opening Vim is the
Command mode.

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 121 25/05/22 10:01 AM


122 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

There is a fourth Vim mode named Visual, which allows the user to select or highlight
text for copying, deleting, and other tasks. Visual mode is not covered in this course.

Users switch between modes by using the following keystrokes:


• ESC -- Enter Command mode.
• : -- Enter Execute mode.
• i -- Enter Insert mode (I, o, and O are also used).

Command Mode Keystrokes


Command mode provides several features for working with files. Options include
jumping to the top or bottom of a file, jumping to a specific line number, and using
keystrokes to make editing the files more efficient.
To move to the top, bottom, or specified line of the file:
• gg -- Move to the top of the file.
• G -- Move to the bottom of the file.
• 42G -- Move to line 42 of the file.
To move the cursor around the text:
• h -- Move the cursor left.
• j -- Move the cursor down.
• k -- Move the cursor up.
• l -- Move the cursor right.
To delete a word, a line, or a specified number of lines of text:
• d -- Delete word at cursor’s position.
• dd -- Delete line at cursor’s position.
• 3dd -- Delete three lines.
To copy and paste lines of text:
• yy -- Cut the line at the cursor’s position (yank).
• p -- Put the yanked line at the cursor’s new position (put).
To save and close the file:
• ZZ -- Write the file to disk and exit Vim.

There are many additional commands in Command mode, but for the purpose of
learning the editor, only some commands have been documented here.

Execute Mode Commands


Execute mode provides a command prompt. Several commands are available, but
the most common are commands that save the file and exit the program.

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 122 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 123

Execute Mode Command Purpose


:w Write the file to disk (save).

:w newfilename Write the file to disk with a new name.

:q Quit Vim.

:wq Write the file, then quit Vim.

:q! Quit Vim without writing changes.

Observe that ZZ in Command mode and :wq in Execute mode do the same thing.

Insert Mode Commands


Insert mode is the common interface most users envision when thinking of a text
editor. This is the mode where text is edited by adding or removing characters.
Using the keyboard in this mode enables the traditional functionality of typing
information into the file.
There are several ways of leaving Command mode and entering Insert mode.
The primary difference in these methods is where the cursor appears for adding
new text. The simplest way of entering Insert mode is by typing the lowercase i
and then using arrow keys to position the cursor. However, other Insert mode
commands may make editing more efficient.
Other ways of entering Insert mode:
• i -- Insert text before the cursor (standard entry method).
• I -- Insert text at the beginning of the selected line.
• a -- Insert text after the cursor.
• A -- Insert text at the end of the selected line.
• o -- Insert text on a new line below the selected line.
• O -- Insert text on a new line above the selected line.
Using these Command mode keystrokes switches Vim to Insert mode and adds text
at the specified position.

Multiple Windows in Vim


Another powerful Vim feature is split-screen. Vim’s interface can be split into
windows vertically, horizontally, or both. Each window may focus on the same
file, or different files can be open side by side. All split windows contain the full
functionality of Vim.
Sysadmins might choose a horizontal split for a configuration file. Configuration
files often contain examples and explanations at the top of the file, yet the actual
lines to be configured may be much closer to the bottom of the file. One window
may be open displaying the top of the file while another window displays a lower
section of the file. The sysadmin can reference the top of the file while editing the
bottom.
The key combination Ctrl+w provides the most split-screen functionality. To split
Vim into two or more horizontal windows, type Ctrl+w and then type s.

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 123 25/05/22 10:01 AM


124 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Vim screens split horizontally.

Users may find it useful to compare two files or may need to transfer content
between the files. In this case, it’s useful to have the files open side-by-side (vertical
split). The user can glance back and forth between the two file versions, making
whatever edits are desired.
Split Vim into two or more vertical windows by typing Ctrl+w and then v.

Vim screens split vertically.

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 124 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 125

To cycle from one window to the next, type Ctrl+w and then w. You can also use
Ctrl+w with the four normal directional keys mapped in Vim.

nano
Nano is a simpler (but less powerful) text editor than Vim. As such, many users
and administrators prefer nano for basic editing functions. Nano does not use the
concept of modes. Instead, pressing the Ctrl key on the keyboard along with
various character keys issues commands to the program.
The nano command invokes the editor. If an existing file is specified, the editor
opens it. If no file is specified, nano creates a new file for editing.

Note that the name of the text editor is “nano," with no capitalization.

Shortcuts in nano
When nano opens a new or existing file, no further action is needed to begin editing.
Simply pressing keys on the keyboard begins the process of entering text. You can
move the cursor through the file using the arrow keys. Most commands are issued
to nano by using the Ctrl key; however, other keys, such as Alt and Tab, may
be used for some functions.

The Ctrl key is represented by the ^ (“caret") character in some documentation.


Hence, ^X represents Ctrl+X.

Common nano Shortcut Purpose


Ctrl + A Move to the start of the line.

Ctrl + E Move to the end of the line.

Ctrl + N Move down one line.

Ctrl + P Move up one line.

Alt + \ Move to the top of the file.

Alt + / Move to the bottom of the file.

Ctrl + S Save the file.

Ctrl + O Write out the file (save as).

Ctrl + X Exit Nano.

Menu showing the nano commands.

Nano is quite powerful and contains many keystroke shortcuts in addition to those
mentioned here. Use the arrow keys, Page Up, Page Down, and Home keys to
navigate within a document.

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 125 25/05/22 10:01 AM


126 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Copying parts of text on a line requires you to “mark” the text you want to copy with
the Ctrl+^ shortcut. You then navigate your cursor to highlight the text you want
to copy. Pressing Alt+^ copies the marked/highlighted text, and Ctrl+U pastes
it. You can cut the current line by using Ctrl+K.

Gedit
The gedit text editor is the default text editor used in GNOME desktop
environments and is a member of the GNU Project. Unlike Vim and nano, gedit
has a GUI with a typical menu-based design that makes it easy to work with. It also
has features such as syntax highlighting and spell checking and can be customized
through plugins. While not as powerful as Vim, gedit may still be useful in systems
that have a desktop environment installed.
Although you can launch gedit from the desktop, you can also use the CLI with the
gedit command. The syntax is similar to vim and nano—typing the editor name
with no argument opens a new file, whereas providing a file name as an argument
either opens an existing file or creates a new one with that name.

The gedit file menu.

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 126 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 127

Review Activity:
Text Files
3

Answer the following questions:

1. A user contacts you and wants an easier text editor to use than Vim.
There is no GUI installed on the system in question. What text editor do
you suggest and why?

2. Explain how the keyboard responds depending on which mode Vim is


currently in. How do modes add to Vim’s functionality?

3. Why are text editors more important on Linux systems than on other
systems?

Lesson 5: Authoring Text Files | Topic 5A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 127 25/05/22 10:01 AM


128 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 5B
Manage Text Files
4

EXAM OBJECTIVES COVERED


1.2 Given a scenario, manage files and directories.

Both user and system files must be protected. It is common to back up user files
in case of hard disk failure. It is also common to back up system configuration files
before making major changes. Doing so offers the ability to restore the original
configuration file if something goes wrong with new changes. The tar utility is
often used to back up or compress files. In addition, applications or other data
files available on the web are commonly bundled with tar for ease of access. After
downloading such files, verify their integrity to ensure the files are legitimate,
complete, and uncorrupted.

Archive and Extract with tar


Users and sysadmins alike need to backup, bundle, and compress files and
directories. Bundling and compressing files makes them easier to download, copy,
or work with. While the primary tool for this work is tar, both cpio and dd may
be used in some cases.
Downloading or copying many files simultaneously may be both inconvenient and
inefficient. If the files are assembled into a single bundle, then only the bundle
needs to be managed with download or copy functions. Many files can be handled
as one, and they can be unbundled after the transfer is complete. In this way, tape
archiver, or “tar,” offers quite a lot of flexibility.

Helpdesk Ticket #01994


Submitted by: Department: Assigned to: Date Opened:
Ali Selassi Marketing you 2024-05-14

Subject Archiving contact files


Ticket Detail I’m having a hard time archiving a whole bunch of files, can
you assist?

Thanks,
Ali S
Date last updated 2024-05-14

When using tar to work with a group of files, the primary phases are:
1. Create a tarball (bundle).

2. Add files to the tarball.

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 128 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 129

3. Transfer the tarball to a different location (usually with the cp or


mv commands).

4. Extract the files from the tarball.

The syntax for the tar command is tar [options] {file1, file2,
file3...}
Some common options for tar are:

Option for the tar Command Purpose


-c Create a tarball.
-x Extract files from a tarball.
-t Test (or list) files in a tarball.
-v Specify a verbose output.
-r Append files to an existing archive.
-f Specify the tarball filename.

Helpdesk Ticket #01994-r

Submitted by: Department: Assigned to: Date Opened:


Ali Selassi Marketing you 2024-05-14

Subject Archiving contact files


Ticket Detail I’m having a hard time archiving a whole bunch of files, can
you assist?

Thanks,
Ali S
Response Sure thing, Ali. Please take a look at the attached walkthrough
using the -c and -x options with tar

Date last updated 2024-05-15

Using the example in the helpdesk ticket, the following list is a demonstration of the
tar utility. This series of commands will manage user Ali Selassi’s proposed archive
consisting of file1, file2, file3, and file4.
1. Create a new tarball:
tar -cvf filearchive.tar file1 file2 file3
2. Display the files in the archive:
tar -tf filearchive.tar
3. Add a file to the archive:
tar -rf filearchive.tar file4
4. Extract the files from the archive (this is equivalent to a restore process in a
backup/restore scenario).
tar -xf filearchive.tar

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 129 25/05/22 10:01 AM


130 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The full CLI output of the different steps of the tar utility.

Keep in mind that as a user, you will frequently interact with tar archives as part
of a download process. Experience with tar makes both file management and
download processes easier.

Copy In and Copy Out with cpio


The cpio tool is found on most Linux distros and is similar to tar. The name
describes its function: it will copy data in and out of an archive, hence cpio (copy
in out).
When using cpio to back up files, the function is “copy out” of the filesystem into
an archive by using the -o option. The related restore process is to “copy in” to the
filesystem from the archive by using the -i option. The cpio tool typically relies on
redirectors as part of these processes.

Option for the cpio Command Purpose


-o Copy out of the filesystem (backup).
-i Copy in to the filesystem (restore).
-v Specify the verbose mode.
To copy files out of the current directory and into an archive as part of a backup
procedure, type:
ls | cpio -ov > /tmp/archive.cpio
To copy files in to the filesystem, thereby restoring the files, type:
cpio -iv /tmp/archive.cpio

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 130 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 131

There is quite a bit of cross-functionality possible, as cpio is capable of creating


tar files.

Copy and Convert with dd


The dd command copies and converts files to enable them to be transferred from
one type of media to another. The dd command has various operands, or actions,
to perform.
The syntax of the dd command is dd [options] [operands]
You can use dd to perform a full backup of a storage partition. The following
example copies data from /dev/sda1 to /dev/sdb2:
dd if=/dev/sda of=/dev/sdb
Using dd, you can also create an image of a drive and then clone a second drive
with it:
dd if=/dev/sda of=drive_image.iso
dd if=drive_image.iso of=/dev/sdb
Operand for the dd Command Purpose
if={file name} Specify the file from which data will
be read.

of={file name} Specify the file to which data will be


written.

bs={bytes} Specify the total block size to read and


write, in bytes. Bytes can also be formatted
in a more human-friendly way, such as 50M
to specify 50 megabytes and 10G to specify
10 gigabytes.

count={count} Specify the number of blocks to be written


to the output file from the input file.

status={level} Specify the level of information to print to


standard error:
• none to suppress everything except
error messages.

• noxfer to suppress total transfer


statistics.

• progress to display transfer statistics


periodically.

Compress Files
Compression is a procedure in which data is encoded to reduce the amount of
bits that are used to represent that data. The compression process can significantly
reduce the size of a file or collection of files in order to make the storage and
transfer of data more efficient. Although the file takes up less space, it still contains
the requisite information so that only redundant data is removed (lossless
compression) or so that only noncritical data is lost (lossy compression).

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 131 25/05/22 10:01 AM


132 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Compression is commonly used to reduce the storage and transmission burden


involved with creating, maintaining, and recovering from backups. Rather than
backing up data one-to-one, you can compress that data and then store it.

Compressing with gzip


GNU zip (gzip) is a compression utility that reduces the size of selected files. Files
compressed with gzip frequently have the .gz file extension. The gzip command
has several options.

Option for the gzip Command Purpose


-d Reverse file compression (decompression).

-f Force compression or decompression of a


file even if it has multiple links or if the file
exists.
-n Omit saving the original file name and
timestamp.
-N Save the original file name and timestamp.

-q Suppress all warnings.

-r Enable directory recursion during


compression or decompression.
-v Display the name and percentage reduction
of the compressed or decompressed file.
-t Perform an integrity check on the
compressed file.
The syntax of the gzip command is gzip [options] [file names]
The gunzip command is equivalent to issuing gzip -d at the command-line.

Compressing with xz
The xz command is a data compression utility, similar to gzip, that reduces the
size of selected files and manages files in the .xz file format. The xz command has
several options.

Option for the xz Command Purpose


-d Decompress a file.

-f Force compression or decompression of a


file even if it has multiple links or if the file
exists.

-q Suppress all warnings.

-v Display the name and percentage reduction


of the compressed or decompressed file.

-t Perform an integrity check on the


compressed file.
The syntax of the xz command is xz [options] [file names]

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 132 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 133

Compressing with bzip2


The bzip2 command and its related commands manage file compression. Files
compressed with bzip2 frequently have the .bz2 file extension. The bzip2-related
commands are described in the following table.

bzip2 Related Command Purpose

bzip2 Compress a file.

bunzip2 Decompress a file.

bzcat Decompress a file to standard output.

bzip2recover Run the diff command on compressed


files. Recover data from damaged .bz2 files.

bzless Run the less command on compressed


files.

bzmore Run the more command on compressed


files.
The syntax of the bzip2 command is bzip2 [options] {file names}
For example, to compress files file1 and file2, type:
bzip2 file1 file2
Compressing with zip
The zip command is another compression utility that (unlike gzip, xz, and
bzip2) also features file archiving functionality. In fact, zip is a combination of
an older compression utility, called compress, and the tar archive command. Files
compressed with zip frequently have the .zip file extension. The zip command
has several options.

Option for the zip Command Purpose


-d Delete entries in a .zip archive.
-e Encrypt the contents of an archive.
-F Fix a corrupted .zip archive.
-r Enable recursion.
-T Perform an integrity check on the
archive file.
The syntax of the zip command is zip [options] [file names]
Which Compression Method Should You Choose?
Which compression tool to use will often depend on your own particular needs,
but some generalities can be made about each. The most important factors are the
speed/time of compression and decompression, and the compression ratio, which
is the size of the uncompressed file divided by the size of the compressed file (e.g.,
a 5 MB uncompressed file that becomes 1 MB when compressed has a ratio of 5:1).

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 133 25/05/22 10:01 AM


134 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

For compression speed, tests tend to show that gzip is slightly faster than bzip2,
and both are significantly faster than xz when the applied compression level
increases. For decompression speed, gzip tends to be the fastest again, with xz and
bzip2 as second and third fastest, respectively. When it comes to compression ratio,
xz tends to perform the best, followed by bzip2, with gzip having the worst ratio.
Ultimately, consider using:
• gzip—if you just care about compressing and decompressing files as fast as
possible and are less concerned with storage space.

• xz—if storage space is at a premium, and time is not as much of a factor.


• bzip2—to strike a balance and for data that rarely needs to be decompressed.

Use Compression with tar


Frequently it’s useful to bundle files with tar and compress them with a tool such as
gzip. While this can be accomplished in two separate steps, it’s easier to integrate
the compression process into the tar process. The tar command recognizes
compression utilities such as gzip and bzip2. Simply add -z to compress with
gzip, or -j to compress with bzip2, to the regular tar command. Add the .gz
or .bz2 file extension name to the bundle.

Helpdesk Ticket #01995-r


Submitted by: Department: Assigned to: Date Opened:
Ali Selassi Marketing you 2024-05-26

Subject Archiving contact files - follow up


Ticket Detail Thanks for your help before, the tar command is really help-
ful. I’m trying to download files now and I need a way to make
that process easier. Can you help?

Thanks,
Ali S
Response Yes, you can combine the tar utility with a compression tool
like gzip or bzip2. I’ve sent over a tutorial on how to use it.

Date last updated 2024-05-27

To combine tar and gzip, type:


tar -czvf myfiles.tar.gz *.txt
To combine tar and bzip2, type:
tar -cjvf myfiles..tar.bz2 *.txt
The same options are used with tar’s file extraction option, -x. Place a z or j
option in the command with -x to decompress and extract the files.

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 134 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 135

Confirm File Integrity


Integrity checking is the process of verifying that data has not been modified,
whether intentionally or unintentionally, in any way. In other words, an integrity
check can validate the security goal of integrity. It is good practice to perform
integrity checking after you finish compressing and archiving a backup file to
confirm that the data has not changed. This will help you avoid storing corrupted
and inaccurate archives for future recovery, only to find out too late that the data
was not properly backed up.
Several methods enable you to check data integrity, each of which may vary
based on its security requirements or goals. One of the most common and secure
methods of checking data integrity is hashing. By calculating the hash of a file like a
backup archive, you can compare that hash to past values. If both are the same, you
can be reasonably sure that the data has not changed in the meantime.

You'll use the md5sum command to check file integrity in Lesson 12.

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 135 25/05/22 10:01 AM


136 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Text File Management
5

Answer the following questions:

1. Why is it a good practice to back up a configuration file before making


changes?

2. Why should the integrity of a file downloaded from the Internet be


checked by tools such as SHA or MD5?

Lesson 5: Authoring Text Files | Topic 5B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 136 25/05/22 10:01 AM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 137

Lesson 5
Summary
3

Linux users must be able to open, edit, save, and close text files using various text
editors, especially Vim and Nano. Not only is user data held in text files, but system
settings are also stored in these files and must be edited to make configuration
changes. Furthermore, user data should be backed up or may need to be available
for transfer to other systems. Archiving tools like tar play an important role in file
management. The text editing skills covered in this Lesson are critical to all facets of
Linux system use.

Guidelines
These best practices and guidelines are provided for your use as revision tools or as
quick references in your job role.
• Make a copy of configuration files before making changes.

• Understand the text editors.

• Know how to move between the three Vim modes.

• Be able to use Vim to open, edit, save, and exit files.

• Be able to use nano to open, edit, save, and exit files.

• Be aware that various distributions may offer one or the other (or both)
editors.

• Use tar to bundle files.

• Use compression to make files easier to manage.

• Combine tar and compression into a single command for efficiency.

• Recognize that tar is used with backup/restore processes and file downloads.

• Use hashing to verify file integrity.

Lesson 5: Authoring Text Files

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 137 25/05/22 10:01 AM


138 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Command Reference Table


This list of commands and their associated syntax can also be found in Appendix B.

Command Syntax Purpose Covered in


tar tar Bundle files for Lesson 5, Topic B
[options] easier transfer.
{file1,
file2 ...}
gzip gzip Reduce size of Lesson 5, Topic B
[options] files.
[file-names]
xz xz [options] Reduce size of Lesson 5, Topic B
[file-names] files.
bzip2 bzip2 Manage file Lesson 5, Topic B
[options] compression.
{file-names}
zip zip Reduce size of Lesson 5, Topic B
[options] files with archiving
[file-names] functionality.

Practice Questions: Additional practice questions are available on the CompTIA


Learning Center.

Lesson 5: Authoring Text Files

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson05_pp119-138.indd 138 25/05/22 10:01 AM


Lesson 6
Managing Software
1

LESSON INTRODUCTION
Maintaining software on Linux systems is usually accomplished with package
managers. Package managers deploy, update, remove, and report on applications.
However, due to the open-source nature of the Linux environment, software
applications are often compiled from source code—something that is not common
with other operating systems.
Because there are many different Linux distributions available, there are many
package managers. As a general rule, most distributions either originated with Red
Hat Linux (and therefore use the Red Hat package managers) or Debian Linux (and
therefore use the Debian package managers).
This Lesson covers several common package managers, the process of acquiring
and compiling software, and running software in a sandbox for security.

Lesson Objectives
In this lesson, you will:
• Understand software management.

• Manage Red Hat–derived software packages and repositories.

• Manage Debian-derived software packages and repositories.

• Compile from source code.

• Acquire software.

• Run software in a sandbox.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 139 25/05/22 12:25 PM


140 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 6A
Understand Software Management
2

EXAM OBJECTIVES COVERED


1.6 Given a scenario, build and install software.

Linux software is usually distributed either as source code to be compiled or


pre-compiled software packages. The packages are maintained using package
managers, which are applications designed to manage packages throughout the
software’s lifecycle (install, update, remove). Several different package managers
exist. Applications delivered as source code must first be compiled before installing.
Compiling the software offers the opportunity to customize it.
This Topic covers the concepts of packages, package managers, and software
compiling.

Red Hat, Debian, and Compiling Source Code


There are thousands of Linux distributions. With the open-source nature of Linux,
anyone can create their own distribution, and many individuals and organizations
do. Within the family of Linux distributions, however, there is a general split in how
software applications are managed.
Broadly speaking, there are two common ways to manage software: Red Hat–based
processes and Debian Linux-based processes. Most Linux distributions are derived
from one or the other of these two major distributions, though there are also
several other methods that are less widespread.
When downloading and using a particular Linux distribution, it is very likely it
uses one of these two package-management suites. Red Hat and Debian package
managers are both covered in this section, with a few references to other package
managers.

Distinguish Package Management from Compiling Software


Software packages are precompiled. Compiling software converts the code from
a human-readable programming language to a machine language. With closed-
source software—such as proprietary, paid applications—the source code is
not available to consumers or outside developers to view or alter. Open-source
software, however, is available for both viewing and altering. If a developer alters
an open-source application’s source code, the updated code must be recompiled to
run on a Linux system.
It is much more common for Linux users, especially developers and administrators,
to compile software than it is for Windows or macOS users.

Lesson 6: Managing Software | Topic 6A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 140 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 141

Compiling software offers several advantages:


• Software is optimized for your system’s hardware, including special features.

• Software is optimized for your Linux distribution and kernel.

• You may be able to enable experimental or beta features.

• You can select specific options.

• You can learn how the software is constructed, discover bugs, and contribute
improvements.

To effectively use Linux systems, users must be capable of both managing software
packages and compiling software from source code.

Software Packages
Linux software is often distributed in packages that contain everything needed
to run the software—executables, configuration files, supporting resources, and
documentation. Therefore, the process of installing, maintaining, and removing
software is referred to as package management, and the tools required to maintain
software are package managers.
One critical component of package managers is the ability to report software
information. Package managers track software installation information in a
database that can be queried. Such queries might include a list of all installed
software, a list of software versions, or specific information on a single software
package. The ability to query the package manager’s installation database provides
sysadmins with essential information on the system and its applications.

Querying a package manager. In step 1, a user at a terminal uses the # apt show nmap
command to find out more information about nmap. The package manager calls out to the nmap
package (step 2), which provides information back (step 3). Finally, the package manager displays
the nmap details at the terminal (step 4). (Images © 123RF.com.)

A second critical part of package management is the source from which package
managers pull the software. A storage location for software packages is referred
to as a repository. Sysadmins control what repositories are available to package
managers.
Lesson 6: Managing Software | Topic 6A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 141 25/05/22 12:25 PM


142 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Repositories can be located in a few key areas:


• An internal server containing only authorized packages

• A distribution vendor, such as Red Hat or Ubuntu

• A public package repository

Sysadmins carefully control available repositories to ensure only authorized


software and software versions are available for installation. Doing so helps ensure
the security and stability of the system by allowing only legitimate software to be
available.

Compare Red Hat and Debian Package Managers


The Red Hat and Debian package managers handle the software lifecycle in much
the same way. Each approach has a method for installing, updating, removing, and
reporting software on the system. Package managers track versions, the location of
installed files, and place documentation files in standard locations.

In an earlier lesson, the Filesystem Hierarchy Standard (FHS) was noted as being a
consistent way of organizing Linux directories. Such organization allows package
managers to exist. Package managers place configuration files in /etc, log files in
/var/log, documentation in /usr/share, and so on because those locations
are standardized across distributions.

Each package manager has its own related commands, and those commands cover
the three major parts of the software lifecycle (installation, maintenance,
and removal). Some basic examples are:
• $ rpm -i {software-package}
• $ rpm -U {software-package}
• $ rpm -e {software-package}
• $ apt install {software-package}
• $ apt upgrade {software-package}
• $ apt remove {software-package}

The -U option for rpm upgrades the specified software package.

Red Hat Package Managers Debian Package Managers


Red Hat Package Manager (RPM) dpkg package manager
Yellow Dog Update Manager (YUM) Advanced Packaging Tool (APT)
Dandified YUM (DNF) package manager

When discussing package managers, note that the name of the package manager is
usually shown in uppercase letters as an acronym. The associated commands are
displayed in lowercase letters because they would be typed at the command prompt.
So the RPM package manager includes the rpm command (to install .rpm files).

Lesson 6: Managing Software | Topic 6A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 142 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 143

The commands for these specific package managers are covered in detail later in
this Lesson.

The SUSE ZYpp Package Manager


SUSE Linux uses its own package manager for software maintenance: ZYpp. The
ZYpp package manager is the basis for the GUI tool YaST (Yet another Setup Tool)
and the command-line zypper utility. The general concept for package management
with zypper is the same as with the rpm and apt commands. Options exist for
installing, updating, reporting, and removing software packages on the system.
Some examples of those options are:
• $ zypper install {software-package}
• $ zypper update {software-package}
• $ zypper remove {software-package}

Software Dependencies
Package managers make software maintenance much more straightforward. One
challenging part of handling Linux software, however, is dependencies. Some
software packages rely on other packages to function. If the software an application
depends on is not installed, it will either fail entirely or not work as intended.
Early package managers required administrators to manually provide the
dependent applications before installing the primary package. Modern package
managers such as YUM, DNF, and APT install supporting applications automatically,
ensuring that a single installation command provides the user with everything
needed to run the program.
Periodically, package dependency issues still arise, so recognize the problem
(failed dependency) and the solution (install the packages required for the primary
application to run).

Lesson 6: Managing Software | Topic 6A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 143 25/05/22 12:25 PM


144 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Software Management
3

Answer the following questions:

1. What are the software-management phases?

2. Why should administrators control software repository locations?

3. Why is compiling software more common with Linux systems than with
other operating systems?

Lesson 6: Managing Software | Topic 6A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 144 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 145

Topic 6B
Manage RPM Software Packages and
Repositories
4

EXAM OBJECTIVES COVERED


1.6 Given a scenario, build and install software.
1.7 Given a scenario, manage software configurations.

Many common Linux distributions are derived from Red Hat Linux. Common
components of most of these distributions are package management and software
package format. Packages for Red Hat–derived distributions use the .rpm file
extension. There are three common package managers: RPM, YUM, and DNF.
Common examples of Red Hat–derived distributions include Red Hat Enterprise
Linux and Fedora.

Red Hat Package Managers


The Red Hat Package Manager (RPM) is the oldest of the package managers
discussed here. It provides good basic functionality with a simple syntax and a lot
of flexibility. It maintains a software database for package queries. One of its main
drawbacks is package management, which is not as robust as the following package
managers: YUM and DNF.
Yellow Dog Update Manager (YUM) relies on .rpm packages and also
tracks software in an RPM database. Like RPM, YUM alerts users to software
dependencies. However, it also offers the ability to automatically install
dependencies so that a single YUM command installs the specified software and all
required software for it to function.
Both RPM and YUM are superseded by Dandified Yum (DNF), which includes all
the same functionality as both with additional plugins and features. Typically, any
Linux system that uses .rpm software packages recognizes RPM, YUM, and DNF
commands.

RPM Commands
The use of Red Hat package managers is primarily focused on installing, updating,
upgrading, and uninstalling software packages. These packages have a .rpm
file extension. RPM files are pre-compiled and usually include all supporting
documentation and configuration files. The idea is that a single package contains
the entire application.

Observe that in this Lesson, “Red Hat” usually refers to that Linux distribution in the
context of a parent distro from which many other Linux distros are derived. RPM-
oriented package managers are not necessarily developed or maintained by Red Hat
itself.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 145 25/05/22 12:25 PM


146 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Using RPM Commands


The syntax for the rpm command is rpm [options] {package-name}
Like many other Linux commands, the -v option provides verbose or detailed
output, and it is common to include -v when manually running the command.
Options for the rpm command include:

Option for the rpm Command Purpose


-i Install a software package.
-U Upgrade a package to a newer version and
install it if it is not already present.
-F Freshen a package to a newer version but do
not install it if it is not already present.
-e Erase or uninstall a software package.
-h Display hash marks or progress bar.
-v Specify a verbose or detailed output.

Querying the vim package with the rpm command.

Querying software is covered later in this section.

Here is an example of using RPM to manage a software package that installs the Z
shell (assume the zsh.rpm package has been downloaded to the system, and the
present working directory is the download location).
This command installs the software in verbose mode and provides a progress bar
to track the installation process:
$ rpm -ivh zsh.rpm

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 146 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 147

This command does two things. It will update the package on a system that already
has the package installed. It will also install the package on a system that does not
currently have it. To accomplish either of these, type:
$ rpm -Uvh zsh.rpm
This command will update an existing package, if installed, but it will not install the
package if it is not already present:
$ rpm -Fvh zsh.rpm
The importance of upgrade (-U) versus freshen (-F) may be difficult to visualize
when thinking of a single system. On a single computer, you’re likely to know
whether the specific software package is present. However, the real importance of
these two options is clear when the rpm command is used in scripts that maintain
software on many systems. A single script may be used to manage software on
20 systems, some of which are supposed to have the software and some of which
are not.
Removing the zsh.rpm package is just as simple. The progress bar and verbose
options may be used to track the removal process as well:
$ rpm -evh zsh.rpm

Removing the tree utility with the rpm command.

The actual zsh.rpm package name will, in reality, be much longer and include
information about the version and architecture for which the package is designed. The
package name used here has been shortened for these examples.

RPM stores package information in a database. An important use of the RPM


database is software verification. The database not only tracks what packages
are installed, but it also tracks where all their components reside (configuration
files, documentation, and so on). If a piece of software is not functioning correctly,
package managers can check to confirm whether all the components exist in the
proper places.
The syntax to verify software with the rpm command is:
$ rpm -V {package-name}

YUM Commands
The yum command works with .rpm packages and is the next evolution of the
RPM package manager. It features a more intuitive syntax and the ability to handle
software dependencies more elegantly.
The syntax for the yum command is yum [options] [subcommand]
{package-name}
There are many common subcommands for the yum command, but the key
examples are presented in the table below.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 147 25/05/22 12:25 PM


148 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Subcommand for the yum Command Purpose


install Install the software package.
remove Uninstall the software package.
update Update the software package.
For example, to install the zsh.rpm package, type:
$ yum install zsh
Recall that some packages require other packages to be installed to function
correctly. These dependencies are difficult to manage manually. However, the yum
command can automatically install a package and any other software it depends
on. The software simply has to be available in the repository along with the primary
package.
By adding the -y option to yum, you automatically answer “yes” to any YUM
questions about whether to also install required dependencies for the package. The
addition of the -y option turns the command into “install the zsh.rpm package and
any necessary packages for it to run.”
The following command installs the zsh package and automatically installs any
packages it depends on:
$ yum -y install zsh
Use the deplist option to display any dependencies for a given package without
installing. This allows sysadmins to ensure any required packages are included in
the software repository.
The YUM package manager allows sysadmins to discover what package contains
a particular file, script, or command. The provides subcommand displays the
contents of a given package. Here’s an example:
$ yum provides {software-package}

Output from the yum provides command for Bash.

Update Packages with YUM


Both YUM and DNF can update installed packages. The process is much the same as
for the rpm command.
An example with a YUM package:
$ yum update zsh.rpm
The YUM package manager can also display or report available updates without
installing them. This is useful for seeing what is available without making any
changes.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 148 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 149

The command to check for updates for all installed packages is:
$ yum check-update
This may generate a lot of output. If there is a specific package that you want to
check for updates, add the package name as an argument:
$ yum check-update {package-name}
To remove software by using YUM, type:
$ yum remove {package-name}

The yum update command, with no arguments, updates all software packages on
the system.

DNF Commands
The DNF package manager is the most advanced of the three software-
management solutions and includes many practical features and updates. It is the
assumed package manager on modern Red Hat–derived distributions, though YUM
and RPM may also be available on those systems.

Subcommand for the dnf Command Purpose

install Install the software package.

remove Uninstall the software package.

upgrade Upgrade the software package.

To install the zsh package by using the dnf command, type:


$ dnf install zsh
Like yum, the dnf command recognizes the -y option as an “assume yes” for
dependency queries, making the installation process far more streamlined. It also
means that any script used to automate software installations can also install any
necessary packages.
The dnf list installed command displays installed software on the
system.
The upgrade subcommand checks the configured repositories for updated
software and installs the newer versions. For example, to upgrade all software on
the system, type:
$ dnf upgrade
Use the remove subcommand to uninstall a software package:
$ dnf remove zsh
The autoremove subcommand removes the software package but also
uninstalls any dependencies that were installed with the package and are no longer
necessary. By using autoremove, sysadmins can help keep systems from being
cluttered with software that is no longer necessary.
The autoremove feature can also be configured with the YUM package manager.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 149 25/05/22 12:25 PM


150 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The DNF package manager recognizes package groups. Package groups are logical
collections of related packages. If an administrator wanted to install all software
for managing virtual machines, each individual package could be identified,
downloaded, and installed. However, virtualization software is collected into a single
package group to be installed as a unit:
$ dnf group install virtualization

It is also possible to identify the group by using the @ symbol in the following command:
dnf install @virtualization. Note that this example uses the
standard dnf install syntax.

Which to Use?
When working with Red Hat–derived distributions, assume the use of the dnf
command to manage packages. Sometimes the rpm command is useful for a single
quick installation when no dependencies are involved. While DNF is the standard,
YUM is still very common.

It’s a good idea to be able to administer basic package management by using all three
commands.

To see a history of DNF package management, type:


$ dnf history

The dnf history command displays recent package-management tasks.

Query Packages on Red Hat Systems


Because RPM-based package managers track software in a database, sysadmins
can query the database and discover important information about the packages.
This information includes the installation date, release date, version, and a brief
discussion of the package’s function. Such information allows administrators to
make informed choices about whether software should be installed, maintained,
or even removed from the system.
The rpm command has two useful query options. The first provides information
on all software on the system, and the second shows details about the specified
package.
The syntax to display all installed software is:
$ rpm -qa > softwarelist.txt

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 150 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 151

The output from the rpm -qa command is likely to be immense, so it may be a
good idea to redirect the results into a text file.
The syntax to display information about a specified package is:
$ rpm - qi {package-name}

Results of the rpm -qi command showing information about the nano package.

The YUM and DNF package managers provide the same functionality.
There may be instances when a user, administrator, security auditor, or other
individual needs to know exactly what software is installed on a specified Linux server.

Helpdesk Ticket #01996


Submitted by: Department: Assigned to: Date Opened:
Kai Garcia Engineering you 2024-04-11

Subject Security audit in progress


Ticket Detail Hi, can you please provide a list of all the software installed
on Server 02A. I appreciate your help, we need this as soon
as possible.

Thanks,
KG
Date last updated 2024-04-11

The yum command to display installed software is:


$ yum list installed
Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 151 25/05/22 12:25 PM


152 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The command to display information on a specified package using YUM is:


$ yum info {package-name}

It’s likely that the output of these commands will be redirected into a text file to be
provided to the requesting user.

The related DNF commands to satisfy such a query are:


$ dnf list installed
$ dnf info {package-name}

Output from the dnf info command.

Observe that the syntax for YUM and DNF is very similar.

Why Repositories?
Repositories, often called “repos,” are software storage locations that package
managers can check when installing or updating software. Many repositories exist,
and not all are trusted. In some cases, malware might be present, but there are
other reasons that repositories may not be trusted.
Possible reasons for sysadmins to control available repositories include:
• Software version control: Some repositories may release beta or unapproved
software that production servers should not use.

• Application installation control: Some repositories may contain unapproved


software, such as games, that production systems should not have access to.

• Vendor control: Some repositories are oriented on specific vendors.

• Bandwidth control: Local repositories may be favored over Internet


repositories for maintaining bandwidth efficiency.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 152 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 153

Administrators use configuration files to inform package managers about what


repositories are allowed and where they can be found on the local network or the
Internet.

Manage Configuration Files for RPM repositories


When the rpm, yum, or dnf commands are issued to install a package, the
commands must know where to look for the software. If a package has been
downloaded to a specific file, the package manager can be directed to that file
with the absolute path. However, locally downloaded and stored software is not
recommended. Version control is difficult, as is enforcing standard applications.
Therefore, administrators should define centralized repositories of packages and
configure the YUM and DNF package managers to use those repositories when
installing or updating software.
Sysadmins often prefer to maintain an internal repository on a local server that is
referenced by all other Linux systems. This provides complete control over software
availability and versions. Package manager configuration files define where these
repositories can be found.
The three types of software repositories are categorized by their locations, and
some are more commonly used than others.
• Local repositories: These repositories are stored on the system’s local
storage drive. Installation is easy, but version control is difficult because of the
decentralized nature of local repositories. If you manage 20 Linux servers, each
would have its own repository to be maintained.

• Centralized internal repositories: These repositories are stored on one or


more systems within the internal LAN and managed by the Linux administrator.
This centralized approach makes version control much simpler. If you manage
20 Linux servers, one could host the repository and the other 19 could download
their packages from it.

• Vendor repositories: These repositories are maintained on the Internet, often


by the distribution vendor. Version control is very difficult because the vendor
decides what package versions are made available.

Use YUM and DNF to Configure Repositories


Administrators can designate a specific location as a YUM repository by using the
createrepo command. The command updates the XML files that are used to
reference the repository location. The repository might be on the local storage drive
(a local repository), or available from an Apache webserver (centralized internal
repository).
After running the createrepo command, the administrator must create a
.repo configuration file that provides additional information about the repository.
The .repo files are stored in the /etc/yum.repos.d/ directory. Some of the
components of the .repo file include:
• [repo-name] —The repository name.
• name=Repository Name —The human-friendly name of the repo.
• baseurl= —The path to the repo. May be a file (file:///) or http:// path.
• enabled=1 —Enables the repo.
• gpgcheck=0 —Disables GPG checking.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 153 25/05/22 12:25 PM


154 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The fedora-repo configuration.

The yum command includes some additional subcommands for viewing and using
repositories:
• repolist —Used to see all available repositories.
• makecache —Used to locally cache information about available repositories.
• clean all —Used to clear out-of-date cache information.

yum lists the configured repositories.

Global settings, such as where to find repository configuration files, log file
locations, and cache information, are stored in the /etc/yum.conf file. The
difference between this file and the repository configuration files is that this file
defines how the YUM package manager works, while the repository files define
where the package manager searches for packages.
The DNF package manager uses a configuration file stored at /etc/dnf/dnf.
conf to define its global settings. These are the same types of global settings
as defined for YUM. DNF also looks to the /etc/yum.repos.d directory for
repository reference files.

Updating Configuration Files


One serious concern for sysadmins is managing configuration files when updating
software via package managers. Many service configuration files are highly
modified by administrators to ensure the software meets the organization’s needs,
and sysadmins need to ensure these files are not overwritten.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 154 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 155

Two options help manage this situation: RPMNEW and RPMSAVE.


The RPMNEW file is created when an .rpm file is installed and a customized
configuration file is found. The .rpmnew file contains the new configuration
settings suggested by the vendor. The administrator can then compare the new
configuration file to the modified file and adjust the settings as desired.
The RPMSAVE file takes the opposite approach. It saves a copy of the
administrator’s modified configuration file with a .rpmsave file extension and
implements the new configuration file with the vendor-suggested settings. The
administrator still has the opportunity to compare the two files and define any
settings needed.
Typically, sysadmins use the RPMNEW file because it maintains the customized
settings and therefore does not change the configuration of production services.
The two files can be compared using the diff command.

Services are covered later, but recall that for configuration file changes to be
implemented, the sysadmin must restart services.

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 155 25/05/22 12:25 PM


156 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
RPM Software Packages and
Repositories
5

Answer the following questions:

1. What information might sysadmins query the RPM database to retrieve?

2. Why might sysadmins restrict certain software repositories?

3. Why are .rpmnew files important during an upgrade?

Lesson 6: Managing Software | Topic 6B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 156 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 157

Topic 6C
Manage Debian-based Software
Packages and Repositories
4

EXAM OBJECTIVES COVERED


1.6 Given a scenario, build and install software.
1.7 Given a scenario, manage software configurations.

While the previous section covered the Red Hat approach to package management
and this section covers the Debian package-management system, it’s worth noting
that package management concepts remain constant. Both approaches manage the
software through its entire lifecycle, from installation, to update, to removal.
Many Linux distributions trace their lineage back to Debian, one of the oldest
distros. The most widely used distros include Debian, Ubuntu, Linux Mint, and Kali
Linux, though there are many other examples. Debian’s common dpkg package-
management system has been replaced by the apt command.

Debian Package Managers


Debian package managers store software inventory information in a database. The
database can be queried to display information on software version, installation
date, source, description, and more. The apt command is the more robust, and
preferred, of the two package managers.

Using apt Commands


Although dpkg is the original installer for Debian-derived distributions, today .deb
packages are more commonly managed using Advanced Package Tool (APT). APT
is a front-end manager to the dpkg system, much like YUM is a front-end manager
to the RPM system.
Until recently, the common software-management tools were implemented as a
mix of the apt-get and the apt-cache commands, along with several other
variations on the apt-* format. Many Debian-derived distributions now use the
more streamlined package manager simply named APT.
The syntax for the apt command is apt [subcommands] {package-
name}
Common apt options include:

Option for the apt Command Purpose


install Install the package.
remove Uninstall the package.
purge Uninstall the package, and remove its
configuration files.

Lesson 6: Managing Software | Topic 6C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 157 25/05/22 12:25 PM


158 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Option for the apt Command Purpose


show Display package information.
version Display package version.
upgrade Upgrade the specified package
(or all packages).
The apt commands for installing and removing software are:
$ apt install {software-package}
$ apt remove {software-package}
Subcommands such as show and version display specific information about
the package, allowing administrators to see version, installation information, and
source for the package.
$ apt show {software-package}
$ apt version {software package}
Sometimes security auditors or sysadmins need to create a comprehensive list of
installed software. The apt list command displays such results. For example,
to see all installed software on a system, type:
$ apt list --installed
One interesting package for Debian-based distributions is build-essential.
This package contains the packages required for building deb packages. It’s
particularly important to those developers distributing software in the .deb file
format.
$ apt install build-essential
Manage Dependencies with APT
Like the RPM package managers, APT can automatically install all necessary
dependencies for a given package. This option is -f (force), and the syntax is:
$ apt -f install {software-package}

Update Packages
As part of software life-cycle management, APT can update installed software.
Software updates are usually a two-step process with APT. The first step is for APT
to discover updated packages in the configured repositories. The second step is to
actually install the updates.

APT repositories are discussed more in the next section.

First, update APT with information about newer versions of available software
as compared to the packages already installed. This does not update the actual
software. The command is:
$ apt update
Once APT is aware of available software, it checks that software against the current
installations. By using the upgrade subcommand, administrators can upgrade
any or all packages to current versions. The apt command for upgrading is:
$ apt upgrade {package-name}
Lesson 6: Managing Software | Topic 6C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 158 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 159

If no argument is specified with apt upgrade, then all packages are upgraded
to the latest version.

Use dpkg Commands


The dpkg command is sometimes used to manage software, especially on older
systems. The command includes the options to install and remove software, as well
as update the application query for software information.
Some common dpkg options include:

Option for the dpkg Command Purpose

-i Install the package.

-r Remove the package.

-l List package information.

-s Report the package’s installation


status.
The syntax of the dpkg command is dpkg [options] {package-name}
Installing software with dpkg uses a syntax similar to other package manager
commands:
$ dpkg -i {package-name}
Removing the software likewise has a similar look:
$ dpkg -r {package-name}

The dpkg package manager has mostly been replaced by APT in much the same way
that the RPM manager has been replaced by YUM and DNF.

Query Packages on Debian Systems


Users and sysadmins alike need to understand what versions of certain software
are installed on the system. Unauthorized software should not be installed.
The apt command provides a mechanism for displaying and understanding
information about the software, including version numbers. The show
subcommand is particularly useful:
$ sudo apt show {package-name}

Output of the sudo apt show command displaying details of the nmap package.

Sometimes a piece of software is unfamiliar to the user, and the ability to see
the vendor, the install date, and the description of the software makes it easier
to understand why the software is installed (and potentially whether it can be
removed).

Lesson 6: Managing Software | Topic 6C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 159 25/05/22 12:25 PM


160 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Manage APT Repository Configuration Files


Like other package managers, APT recognizes software storage repositories from
which it can install or upgrade software. Sysadmins customize which repositories
APT accesses. Repositories are exposed to APT in the /etc/apt/sources.
list file and in the /etc/apt/sources.list.d/ directory. Like YUM
repositories, APT repositories may also be on the local system, on the local network,
or hosted on the Internet.
Entries in the /etc/apt/sources.list include the following fields,
separated by a space:
deb URL distro-name components
Be sure to let APT know about new repositories after editing the /etc/apt/
sources.list file by running the apt update command.
Understanding /etc/apt.conf
The apt.conf configuration file is a method for managing the configuration of
the APT suite of tools. The file contains settings that are loaded when APT starts
and controls installation priorities, proxies, and other settings. Depending on the
distribution, the configuration file may be found at /etc/apt.conf, /etc/
apt/apt.conf, or along other paths.

Lesson 6: Managing Software | Topic 6C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 160 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 161

Review Activity:
Debian Software Packages and
Repositories
5

Answer the following questions:

1. What are the two steps for upgrading software with apt?

2. Explain the difference between the two steps in upgrading software


with apt.

Lesson 6: Managing Software | Topic 6C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 161 25/05/22 12:25 PM


162 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 6D
Compile from Source Code
3

EXAM OBJECTIVES COVERED


1.1 Summarize Linux fundamentals.

Package managers are efficient and convenient forms of acquiring and installing
software. However, there may be times when you want to build software from
source code—after all, most Linux software is open source.

Why Compile Software?


Software that is packaged as an .rpm or a .deb is pre-compiled by the vendor.
Usually, this packaged software is configured with generic settings and options. A
Linux user may want to modify the software, for example, to optimize it for their
specific hardware. This may result in maximum performance. Packaged software
is most common in Linux, but compiling your own software is a normal Linux task.
The same is not true for Windows and macOS, where nearly all software is pre-
compiled (because you don’t typically have access to the open-source code).

What Is the GCC?


Compiling software manually does not use a management tool as packaged
software does. To compile software, there must be a compiler installed. Compilers
translate source code written in a human-friendly programming language, such as C
or C++, into machine-readable binaries.
A common compiler for Linux is the GNU Compiler Collection (GCC), implemented
as the gcc utility. There are often other supporting libraries that must also be in
place.
The required libraries vary by the software being compiled. Typically, software
developers will provide a list of these necessary libraries with the application source
code. These may be header files (.h file extension) or library files (.a file extension).

The Compile Software Commands


Compiling software is a three-step process. First, the system must be checked, and
compile instructions must be created. Second, the source code is compiled into
machine language. Finally, the new software is installed.
The first step uses a configure script to ensure the necessary dependencies and
compilers are available. The configure script creates a makefile containing the
instructions for compiling the software.
The command is:
$ ./configure

Lesson 6: Managing Software | Topic 6D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 162 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 163

The Bash shell only checks for executable files such as programs and scripts in specific
locations. Usually, a user’s home directory is not one of these locations (nor should it
be, for security reasons). However, it’s as if the software the user is compiling has been
downloaded to the home directory. The ./ instruction tells Bash to “check here” at the
present location for the specified executable file.

The second step is the actual compile process. In most cases, once the makefile is
created, simply issuing the make command without arguments will compile the
application. The make command automatically looks for the makefile in the current
directory. You can, however, issue make with various options.
A makefile is a file that contains instructions used by a compiler to build a
program from source code. These instructions typically define the resources that
the program depends on in order to function properly, as well as any additional
directives as defined by the developer.
Once the compile process completes, it’s time to install the software. This is the final
step in the process. The make install command installs the program, placing
the appropriate files in the appropriate locations (configuration files, log files, and
so on). The software is now available and ready to run.

Compile Software
When an administrator downloads software, there is a common process to build
the executable file called software compilation.
1. Unpack the download, typically using tar and/or gzip commands.

2. Change into the directory that gets created as part of the unpacking process.

3. Run the ./configure command to gather system information needed by


the application. This information is stored in the makefile, which is referenced
during the next step.

4. Use the make command to compile the application using the information
stored in the makefile. Note that this usually requires root privileges.

5. Use the make install command to install the resulting binaries (the
application).

Many developers will provide instructions and options that may modify this process
somewhat. Specifically, there may be options or modifications that can be made
to the makefile before the make command is run to optimize the software for
the system or the user’s needs. It is important to review any README or other
instruction files that are downloaded as part of the software.

Remove Compiled Software


If you need to remove the software you compiled, the process can be a bit tricky.
The makefile includes all directories and files created during the installation
process. Examine this file, and remove each file and directory specified in the
makefile. While this may be time-consuming, it ensures all traces of the application
are gone.
To be able to remove the software components, you must save the makefile so that
you can use it as a reference.

Lesson 6: Managing Software | Topic 6D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 163 25/05/22 12:25 PM


164 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Source Code
4

Answer the following questions:

1. What is the effect of using ./ before an executable file?

2. Why is it more common to compile software with Linux than with other
operating systems?

Lesson 6: Managing Software | Topic 6D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 164 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 165

Topic 6E
Acquire Software
3

EXAM OBJECTIVES COVERED


1.5 Given a scenario, use the appropriate networking tools or configuration files.

Repositories are not the only way to download and install software. Several other
tools are used in this topic to enable you to acquire the files necessary to use
software. These tools provide alternate ways of downloading files from web servers
and managing compression.

Review Download Sites


Because of the open-source nature of Linux software, it is very common to be able
to freely download applications directly from the application vendor. There are
also many websites that centralize information about available software and about
Linux distributions.
You can search the Internet for Linux software. Here are a few examples of Linux
applications that are available for download:
• Audacity®, a music production application

• Atom, a powerful text editor

• GIMP, a powerful image editorNmap, a very useful network mapping utility

You can also search open-source hosting sites, such as GitHub®, for software.

wget And curl Commands


Most of us are familiar with accessing websites using a web browser such as
Firefox. It is also possible to access websites from the command line. This is
especially useful when downloading a file for which you already know the URL. The
wget and curl commands can be written into scripts, automating the process of
downloading package files.
The following is an example of using wget to download a file from the Samba
website:
$ wget http://download.samba.org/pub/samba/samba-
latest.tar.gz
Here is an example of using curl to download a file from the Nmap website:
$ curl -o nmap-7.70.tar.bz2 https://nmap.org/dist/
nmap-7.70.tar.bz2
The syntax of the wget command is wget [options] {URL}
The curl command uses the same syntax.

Lesson 6: Managing Software | Topic 6E

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 165 25/05/22 12:25 PM


166 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The common options for wget include:

Option for the wget Command Purpose

-P Download to a different directory from


the current one.

-b Download in the background.

While there are many options for the curl command, common examples include:

Option for the curl Command Purpose

--progress-bar Display a progress bar during the


download.

--verbose Display additional download information.

For example, to download a file to the ~/projects directory instead of the


current directory, type:
wget -P /home/USER/projects {URL}
Comparing wget and curl
While wget and curl perform the same basic function, there are some key
differences:
• wget is a command line utility only, whereas curl is implemented using the
cross-platform libcurl library and is therefore more easily ported to other
systems.

• wget can download files recursively, whereas curl cannot.


• curl supports many more network protocols than does wget, which only
supports HTTP/S and FTP.

• wget is better suited for straightforward downloading of files from a web


server, whereas curl is better suited to building and managing more complex
requests and responses from webservers.

Use tar to Manage Source Code


Linux often uses two particular utilities to help manage files. The first utility is tape
archiver or tar. The second is a compression utility, such as gzip. The purpose of
tar is to bundle together multiple files into a single tarball with a .tar extension.
This makes downloads much easier since there is only one download necessary
to acquire multiple files. The server administrator creates the bundle of files, and
whoever downloads the bundle extracts the files from it.
To extract the files bundled with tar, use the -x option with tar:
$ tar -xf archive.tar
If the tarball archive is compressed, use the -z option along with the -x extract
option to uncompress the file.

Recall that tar was covered in an earlier lesson. It is covered here only in the context
of downloading software or source code from the Internet.

Lesson 6: Managing Software | Topic 6E

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 166 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 167

Review Activity:
Software Acquisition
4

Answer the following questions:

1. How can wget or curl be used to download files from the Internet in a
way that a web browser can not be used?

2. How might tar be used to distribute an application?

Lesson 6: Managing Software | Topic 6E

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 167 25/05/22 12:25 PM


168 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 6F
Run Software in a Sandbox
3

EXAM OBJECTIVES COVERED


1.6 Given a scenario, build and install software.

Typically, software and the operating system share resources and can affect each
other. This design creates potential security threats where one piece of software
can impact the entire system. Isolating software with sandboxing helps mitigate this
potential vulnerability.

Why Sandbox?
One of today’s greatest cybersecurity threats is ransomware. Malware may enter
a network environment via poorly tested or poorly written software, which then
gains access to user data. One way of mitigating this threat is for end-users to run
software in a sandbox environment.

Sandboxing is also known as “jailing” an application.

A sandbox is a virtual machine or container that isolates the application from the
rest of the system and mediates communication between hardware resources and
the program. Such a design is often more secure than an operating system and
many applications sharing unmediated access to system resources. Developers
testing new software and cybersecurity professionals examining malware code are
among those who benefit from sandbox solutions.
Sandboxing differs from an older practice known as chroot. By using chroot,
administrators told the application that a given directory was the “root” or highest
point in the filesystem. Since the application was unaware of any directories above
this root, it couldn’t access the rest of the system. In some cases, this practice is still
appropriate today.
Sandboxing relies on applications to enforce boundaries, while chroot uses the
filesystem.

Sandbox Software
The following three package managers distribute and run software in a sandboxed
environment: Snaps, Flatpak, and AppImage.

Lesson 6: Managing Software | Topic 6F

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 168 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 169

Snaps
Canonical, the group responsible for Ubuntu Linux, uses the Snap package
manager to deploy and maintain software. The software is distributed as “Snaps”
and managed by the snapd daemon and the snap command. Each Snap is self-
contained with everything necessary to run included in the package. The packages
run in an isolated sandbox environment.
Once Snap is installed, packages can be downloaded from the Snap Store. After
that, application management is similar to that of other package managers:
$ snap install {software-package}
$ snap info {software-package}
$ snap list
$ snap remove {software-package}
Flatpak
Another package manager that runs applications in a sandbox is Flatpak. Using
the flatpak command, users can manage software on a system-wide or per-user
basis. Repositories—called “remotes”—store software distributed as flatpaks.
To install {software-package} from a remote named org.demo.sample,
type:
$ flatpak install {software-package} org.demo.
sample
AppImage
AppImage offers self-contained applications that run consistently on Linux systems
in a sandboxed environment. AppImage applications are distributed and managed
as a single file containing everything needed to run the application. Application
developers decide what distributions to support and then ensure that all needed
dependencies and libraries are included with the AppImage file.
AppImage applications are standalone components, and while they can be installed
in the traditional manner, they do not have to be. They can be accessed and run as
mounted drives.

Drive mounting and access is covered in a later section.

Lesson 6: Managing Software | Topic 6F

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 169 25/05/22 12:25 PM


170 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Software in Sandbox
4

Answer the following questions:

1. What is the advantage of sandboxing?

2. True or False? The original practice, known as chroot, that predates the
current method of sandboxing, is deprecated and no longer used.

Lesson 6: Managing Software | Topic 6F

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 170 25/05/22 12:25 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 171

Lesson 6
Summary
3

Red Hat and Debian package managers handle software maintenance for most
Linux distributions. There are also package managers that run applications in
isolated sandbox environments for ease of maintenance and security. Some
software is acquired in the form of source code, which allows users to customize
the application for specific features or hardware before compiling it. This process is
uncommon on platforms that use proprietary software but is more prevalent with
open-source code.

Guidelines
These best practices and guidelines are provided for your use as revision tools or as
quick references in your job role.
• Recognize which package managers are used by which distributions:

• rpm, yum, and dnf commands are usually used by Red Hat–derived
distributions.

• apt command is usually used by Debian-derived distributions.

• ZYpper is used by SUSE Linux.

• Be able to conduct basic package management with any package manager,


including installing, updating, removing, and inventorying software packages.

• Be prepared to recognize and manage dependencies.

• Be able to install, update, and remove software by using the rpm, yum, dnf,
and apt commands.

• Be able to query packages by using the rpm, yum, dnf, and apt commands.

• Be able to configure software repositories for the RPM, YUM, DNF, and APT
package managers.

Lesson 6: Managing Software

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 171 25/05/22 12:25 PM


172 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Command Reference Table


This list of commands and their associated syntax can also be found in Appendix B.

Command Syntax Purpose Covered in


rpm rpm [options] Package management Lesson 6, Topic B
{package-name} in Red Hat distros.

yum yum [options] Software package Lesson 6, Topic B


[subcommand] management in Red
{package-name} Hat distros.

apt apt Package management Lesson 6, Topic C


[subcommands] in Debian-based
{package-name} distros.

dpkg dpkg [options] Manage software Lesson 6, Topic C


{package-name} packages in older
Debian-based
distros.

wget wget [options] Download package Lesson 6, Topic E


{URL} files housed on web-
sites from the com-
mand line.

curl curl [options] Download package Lesson 6, Topic E


{URL} files housed on web-
sites from the com-
mand line.

Practice Questions: Additional practice questions are available on the CompTIA


Learning Center.

Lesson 6: Managing Software

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson06_pp139-172.indd 172 25/05/22 12:25 PM


Lesson 7
Administering Storage
1

LESSON INTRODUCTION
Storage management involves planning, understanding hardware, and using many
tools to accomplish storage goals. Sysadmins must know what types of hardware
are available and what type will work with the Linux system in question. They must
also know the performance requirements for data stored on any drives. Direct-
attached storage disks are managed as single entities with traditional partitions or
can be combined into logical volumes for more flexible storage space. Network-
based storage, such as NAS, SAN, and cloud technologies, may also be used. Finally,
sysadmins must understand the available Linux tools for troubleshooting and
performance monitoring.

Lesson Objectives
In this lesson, you will:
• Understand storage.

• Deploy storage.

• Manage storage options.

• Troubleshoot storage.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 173 27/05/22 9:20 PM


174 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 7A
Understand Storage
2

EXAM OBJECTIVES COVERED


1.1 Summarize Linux fundamentals.

Managing a Linux server that stores a significant amount of data requires an


understanding of storage technologies. Various storage formats are better
suited to storing specific types of data. In addition, the balance between cost
and performance must be maintained, leading administrators to make particular
choices when it comes to interfaces such as SATA, SCSI, and SAS.

Storage Concepts
Storage capacity for user data, databases, logs, configuration files, operating
system and application executables, and other resources are of major concern to
sysadmins. Capacity is only one part of the issue, however. Related is the ability
to maintain cost-effective, reliable, and secure storage media that is accessible to
users and services.
The storage concepts in this section compare various storage technologies and
configuration options that inform the choices that Linux administrators make for
storage.

Cloud-based storage is a growing online service and has become a critical part of much
storage management. General cloud concepts are covered in a later Lesson.

Some examples of storage media types include:


• Hard disk drive (HDD): Spinning magnetic disks, usually inexpensive, large, and
relatively slow

• Solid-state disk (SSD): Flash memory storage, usually expensive, fast, small, and
shorter -lived

• Universal Serial Bus (USB): Connection protocol for various external devices,
including storage drives

• Thumb drive: Removable storage media, usually connects via USB

• External: Removable storage disk, usually connects via USB

Types of Storage Design


Stored data is usually managed via one of three different designs: file, block, and
object storage. While these don’t tend to impact Linux on a day-to-day basis, it is
important to recognize some basic differences.

Lesson 7: Administering Storage | Topic 7A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 174 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 175

File storage is the common approach to storing data on local drives, with data
organized into discrete files stored in directories. These directories are organized
in a hierarchical structure. Data is easy to retrieve and change, but file storage does
not scale well: it must be scaled out rather than scaled up.
Block storage is a good choice for large quantities of unstructured data
stored across multiple platforms and storage types. Commonly used with SAN
technologies, it is quick, reliable, and efficient.
Object storage is cost-effective and very scalable but best for static data because
it’s difficult to modify data once written. This makes it particularly unsuited for
databases.
A typical Linux server will rely on file storage by using one or more internal drives
that use a standard filesystem to organize and retrieve data.

Traditional Hard Disk Partitioning versus LVM Deployment


The basic process for adding storage to a system is to install the drive, partition
it, add a filesystem, and then mount it. In addition to traditional partitioning,
technologies such as a Logical Volume Manager (LVM) permit the aggregation of
storage space from multiple disks, providing flexibility and scalability options.
Both traditional partitions and LVM are covered in Topic 7B.

Storage Interfaces
Internal storage devices use different protocols and interfaces to communicate
with the rest of the system. These designs vary by speed, communication type, and
scalability. Various solid-state drives, hard disk drives, and flash storage use these
interfaces.
Serial Advanced Technology Attachment (SATA) is a common inexpensive
storage media that uses a serial connection to communicate with the motherboard.
This is the slowest of the three options discussed here but the least expensive. It is
a good all-around solution for most systems.
Small Computer Systems Interface (SCSI) tends to be expensive with less capacity
than most SATA drives but makes up for this by being very fast. For servers, RPMs
of 10,000 and 15,000 are common, while desktop and laptop drives might spin
at 7,200 or 5,400 RPMs. Multiple SCSI drives can be attached to the same chain,
making their scalability far more flexible than SATA.
Serial Attached SCSI (SAS) is an upgraded SCSI design with larger capacities, faster
transfer speeds, and greater flexibility. However, these benefits come with a higher
cost. The cost may be well worth it for mission-critical servers.
Linux administrators must balance speed, capacity, and cost when deciding which
of the standards is appropriate for a new Linux workstation or server.

Types of Partitions
Storage drives are divided into partitions for more efficient and organized use.
On a Linux server, these partitions may store different types of operating systems,
applications, or data files. There are two ways of tracking these divisions of the
drive: a Master Boot Record (MBR) or a GUID Partition Table (GPT). These two
entries identify where on the physical drive the partition divisions are located.
The MBR is the traditional choice, but it is limited. Many server administrators use
the GPT because it recognizes more partitions (divisions) of the drive, which is
important for larger-capacity storage devices.

Lesson 7: Administering Storage | Topic 7A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 175 27/05/22 9:20 PM


176 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Creating partitions is covered in a later section.

The master boot record (MBR) is the first physical sector on a storage drive and a
type of partition structure. The MBR boot sector contains the boot loader that loads
the operating system into memory. It also contains the partition table of the storage
drive. MBR determines what sectors are available to each partition, as well as which
partitions are bootable and which are not.
For many years, MBR was the dominant partition structure used in Linux and other
operating systems. However, it has three major disadvantages:
• The maximum storage space of an MBR-partitioned drive is two terabytes.

• MBR-partitioned drives can have a maximum of four primary partitions.

• The boot data is stored all in one sector, which increases the risk of corruption.

The GUID Partition Table (GPT) is a successor to MBR that makes up for the latter’s
shortcomings. Like MBR, it is a partition structure, but it employs a more modern
design and is part of the UEFI standard. Every partition on a drive is assigned a
globally unique identifier—a GUID—to distinguish it from every other partition on
(theoretically) every drive.
The storage space and partition number maximums are so large that they are not
currently achievable, and any limitations are going to be imposed by the file system
type or operating system kernel, rather than GPT itself. GPT also has the advantage
of storing its boot data in multiple locations on a drive to enhance redundancy.
If the primary location is corrupted, GPT can leverage one of the other copies to
restore the boot data.
Whenever possible, partitioning a drive with GPT is preferable to MBR.

Filesystem in Userspace (FUSE)


Linux is one of several common operating systems that supports the Filesystem in
Userspace (FUSE) kernel module. This feature provides support for many virtual
filesystems. Filesystems are created in userspace by non-privileged users, without
kernel modifications, and FUSE provides a kernel connection.

The use of FUSE is not inherent in Linux administration. The key factor here is that Linux
is capable of this feature, which provides a great deal of flexibility.

RAID Arrays
A standalone storage disk is a single point of failure. When the disk fails, the data on
it is likely to become inaccessible. In addition, individual disks have limited transfer
speeds and storage capacity.
Storage disks may be organized into RAID arrays to mitigate the limitations of
standalone drives. A Redundant Array of Inexpensive Disks (RAID) combines
storage disks together. Depending on the configuration, the result may be greater
capacity, greater fault tolerance, and increased speed.
Two different designs manage RAID arrays: hardware and software. Hardware RAID
uses a dedicated controller attached to the motherboard. This is usually faster,
more flexible, and more expensive. Software RAID relies on the operating system

Lesson 7: Administering Storage | Topic 7A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 176 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 177

to manage the storage, which is usually slower, less flexible, and less expensive
(because no special hardware is required).
In a server, hardware RAID is almost always preferred.
Various RAID standards exist and are primarily identified by number, but three
of the most common are RAID 0, RAID 1, and RAID 5. Each has advantages and
disadvantages to consider.

RAID details are covered in Topic 7C.

Set Disk Quotas


A storage quota is the storage space allotted to a user for file storage on a
computer. Storage quotas are configured on a per-user basis. File systems that
implement storage quotas can have a soft limit, a grace period, and a hard limit.
Once a user exceeds the soft limit, they will be placed in the grace period, the
default setting for which is seven days. The user is allowed to exceed this soft limit
within this grace period but cannot exceed the hard limit maximum. If the user
returns below the soft limit, the timer resets. If the user still exceeds the soft limit
when the timer expires, the soft limit becomes a hard limit, and the user will be
unable to use any additional storage.
Storage quotas are a good measure to prevent or respond to issues that arise due
to excessive storage use. You can use these quotas to ensure that users are not
consuming all of a drive’s space and leaving none for other users or the system.
Quota management is the effective allotment and monitoring of quotas for all
users. Linux has various commands that help ease the job of quota management
for the system administrator.
Before you can use these commands, you must activate user and/or group quotas
on the file system. You can do this by editing the /etc/fstab file to add the
options usrquota and grpquota to the relevant file system.
Quota reports are created by the system so you can view storage space usage by
each user. These reports enable you to check which user is taking up maximum
disk space. They can also help you troubleshoot issues with quotas themselves—for
example, quotas that are either too restrictive or too permissive.
A quota report contains the following details:
• The name of the user/group.

• The total number of blocks (in kilobytes) that are being used by the user/group
on a file system.

• The user’s/group’s storage soft limit.

• The user’s/group’s storage hard limit.

• The grace period.

• The total number of inodes that have been used on a file system by the
user/group.

• The soft limit on inodes.

• The hard limit on inodes.

Lesson 7: Administering Storage | Topic 7A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 177 27/05/22 9:20 PM


178 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
3

Storage Concepts
Answer the following questions:

1. Explain the key differences between MBR and GPT partition tables.

2. How might quotas help sysadmins manage storage capacity on a server?

3. Do all RAID array designs provide fault tolerance?

Lesson 7: Administering Storage | Topic 7A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 178 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 179

Topic 7B
Deploy Storage
4

EXAM OBJECTIVES COVERED


1.3 Given a scenario, manage files and directories.

Consider a scenario requiring an administrator to deploy additional storage on an


existing Linux server. The drive must be installed, detected, partitioned, formatted,
and mounted to be available to users. There are many tools and commands to
display drive information and manipulate storage space. This section steps through
such a scenario and explains the utilities needed to manage server storage.

Deploy a Traditional Hard Disk Drive


As a Linux administrator you’ll commonly be asked to manage storage, which
almost always translates into making more storage capacity available. Assume that
you’ve selected the appropriate drive based on interface requirements (SATA, SCSI,
or SAS) and that performance requirements such as speed and capacity have been
satisfied.
Once the drive is physically installed, confirm that Linux is aware of the new device.
Depending on the type of drive and the information needed, several commands
are available that display device information. Use these commands to view device
information.

The hwinfo Command


The hwinfo command displays details about system components. The command
can provide information on any or all components. In the case of storage, the
--storage flag is added to display storage controllers, while the --block flag
displays information on storage disks and partitions. Because at this point in the
installation no partitions have been created yet, confirm controllers by typing:
hwinfo --short --storage

Note that these flags are preceded by two dash characters: ( -- ).

To confirm the proper disk type is installed and compatibility with the storage
controllers, type:
# hwinfo --short --storage

Add the --short option to focus on general information about the specified device.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 179 27/05/22 9:20 PM


180 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The hwinfo tool is also used to gather CPU, memory, Bluetooth, and network device
data. It is covered in more detail in the next Lesson.

The lsblk Command


The lsblk command displays information on storage devices the system is
aware of. This information includes the device name, capacity, and mount point (if
configured). Mount points are covered in a later section.
The lsblk command displays more information than most sysadmins require for
this scenario. The specific data to look for is /dev/sd* content, which shows the
recognized drives and partitions (if any).
Confirm that the new hard disk drive has been recognized. The syntax for the
lsblk command is lsblk {drive-path}
For example, to see all devices recognized, type lsblk with no arguments. To
see information on a specific storage device (such as storage device a), type the
command with the device path:
# lsblk /dev/sda

Output from the lsblk /dev/sda command displaying capacity and partition
information.

The lsscsi Command


If the system uses SCSI devices, the lsscsi command displays information about
each device. Data for each device is displayed on a separate line and includes
the device name, manufacturer, model, etc. If you add the -s option, device size
information is shown.
For example, if the new device is an SCSI disk, type lsscsi -s to see device
details and size output.

The lsscsi command also displays NVMe storage device information.

Disk and Partition References


Storage disk information such as manufacturer, model, and capacity may be
reported by some tools. Most references to the storage media include a path. All
hardware devices are mapped to the /dev directory. Storage disks are displayed
there using the sd string.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 180 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 181

The sd string (which used to stand for “SCSI disk” but now means “storage disk”) is
followed by a letter defining the drive’s location. Any numbers that follow reference
a partition, if any have been created.
So, the first storage disk in the system is displayed as /dev/sda. In this example,
a second disk is added to the system, so it is labeled as /dev/sdb.

Partition information for the first disk (sda).

Partition the Drive


Once you’ve installed the drive and it’s been recognized by Linux, you must divide
the storage capacity into usable space. Creating partitions is the first step in
organizing the storage space. Considerations such as MBR vs. GPT must be taken
into account, and then you’ll partition the space using fdisk or parted. After
creating the partitions, update the system with partprobe and confirm the
partitions in the /proc/partitions directory.
Recall that the Master Boot Record (MBR) or GUID Partition Table (GPT) is used to
define the location of partitions on the disk. The MBR is limited by drive size (2 TB
maximum) and the number of partitions (four). These limitations must be taken into
account when deciding on a partition method.

Partition Design
It is common to dedicate specific partitions to certain FHS directories. For example,
it may be useful to place the /boot directory on its own partition. In addition, the
/home and /var directories may also be mounted to dedicated partitions. The
reason these two directories are often attached to dedicated partitions is that they
are particularly at risk for filling up. Users may create or download a great many
files to their home directories, or log files stored at /var/log may suddenly
increase in size due to failing applications or services. If the partition where the root
of the filesystem (/) resides fills, the system will crash. To prevent this, directories
such as /home and /var, which are at risk for filling, are placed on separate
partitions from /.
Linux also commonly dedicates a partition to virtual memory. Using a process called
“swapping,” Linux moves data between memory and the hard drive if the memory is
in danger of being fully consumed. A dedicated swap partition is often set aside that
is 1.5 times the quantity of the total RAM.

Memory management and swapping are discussed in detail in Topic 8D.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 181 27/05/22 9:20 PM


182 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The fdisk Utility


The fdisk utility is a menu-driven program that is used to create, modify, or delete
partitions on a storage drive. Using fdisk, you can create a new partition table or
modify existing entries on the partition table. The fdisk tool understands the DOS
and Linux type partition tables. The fdisk utility also enables you to specify the size
of partitions.

The fdisk command menu.

The syntax of the fdisk utility is fdisk [options] {device name}

Option for fdisk Purpose


n Create a new partition. The sub-options enable you
to specify the partition type and partition size.
d Remove a partition.

p Print (list) the existing partitions.

w Write the changes to the drive, and exit the utility.

q Quit the changes to the drive, and exit the utility.

To create partitions on the newly installed storage disk by using fdisk, use the
following steps:

1. Type fdisk /dev/sdb to edit the partition table for the second (new)
disk.

2. Type m to display the menu of fdisk features.

3. Type n to create a new partition.

4. Type p to create a new primary partition, or type l to create a logical partition.

5. Select Enter to start the partition at the first available sector.

6. Type a value such as +10G to create a 10 GB partition.

7. Type p to display the new partition information (note that no changes have
been made at this point).

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 182 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 183

8. Type w to write (save) the changes to the partition table and exit fdisk.

9. Type fdisk -l /dev/sdb to confirm the partition information.


Once one or more partitions are created, use fdisk -l /dev/sdb2 to display
the partition information.

Output from the fdisk -l /dev/sda command displaying partition information.

The Parted Utility


The GNU Parted utility is also used to manage partitions. It is particularly useful
when creating partitions on new storage drives. It can be used to create, destroy,
and resize partitions. The parted command runs the GNU Parted utility. Like
fdisk, Parted includes a menu-driven interactive mode where you can input various
options.
The syntax of the parted command is parted [options] {device
name}

Option for parted Purpose


select Choose which device or partition to modify.

mkpart Create a partition with a specified file system type.

print List the partition table.

resizepart Modify the end position of a partition.

rm Delete a partition.

quit Write changes and exit the GNU Parted utility.

To create partitions on the newly installed storage disk by using parted (and only
if you haven’t done so via fdisk), follow this process:

1. Type parted /dev/sdb to edit the partition table for the second (new)
disk.

2. Type mklabel gpt to create a GPT table.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 183 27/05/22 9:20 PM


184 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

3. Type mkpart primary ext4 1MB 2000MB to create a new primary


partition of the specified size.

4. Type print to display the new partition information.

5. Type quit to write changes to the partition table and exit parted.

GNU Parted is a critical tool for any sysadmin. The utility recognizes and can resize
New Technology Filing System (NTFS) partitions, which are commonly found on
Windows Servers.

The partprobe Command and the /proc/partitions Directory


Whether you used fdisk or parted to create partitions on the new disk, the
next step is to update Linux with the new information. The partprobe command
causes the system to redetect the storage disks and any partition changes. Run this
command to confirm the new partitions exist as expected.
Partition information is stored in a file named /proc/partitions, which
is recreated each time the system boots or the partprobe command is run.
The dynamic nature of this file means that it reflects changes to the system’s
configuration (changes that are detected during system startup or via the
partprobe command).
Because Linux treats /proc/partitions as a file, display its contents by using
the cat command:
# cat /proc/partitions
When viewing the output from /proc/partitions, recall that sd stands for
storage disk and that letter designations such as a and b represent specific drives.
Any numbers in the output represent partitions on that drive. Therefore, /dev/
sdb3 is the third partition storage device b.

The output of the cat /proc/partitions command displaying partitions recognized


by the system.

The blkid Command


Another useful utility for displaying partition information is the blkid command.
The command displays known information on the partitions. One particularly useful
piece of information is the UUID of the partition. The Universally Unique ID value
is a more reliable identifier for the partition than the path /dev/sdb2 since the
path is possibly changeable.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 184 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 185

The output of the blkid command displaying the UUID for the /dev/sda1 partition.

Add a Filesystem to a Partition


After creating the partitions on a new drive, you must add a filesystem to organize
the storage of the actual data. Different filesystems have different benefits, and
there are many of them. In general, most Linux distributions use either the ext4 or
XFS filesystems. Many maintenance tools exist for these filesystems that allow for
repair, resizing, and identifying filesystem information.

The ext4 Filesystem


The ext4 filesystem is the older of the two options. It provides journaling and is
recognized by most distributions.

The ext toolset enables a variety of administrative tasks to manage the filesystem. These
tasks are covered in a later section.

To format the new partitions, use the mkfs command. The command expects to
know the desired filesystem and a target partition.
To place the ext4 filesystem on the second partition on the new disk, type:
# mkfs.ext4 /dev/sdb2
The mkfs also recognizes a slightly different syntax. The following command
achieves the same result as the example command above:
mkfs -t ext4 /dev/sdb2

The mkfs command overwrites existing data on the partition, making that data
difficult or impossible to recover. Use it carefully!

The XFS Filesystem


While the ext4 filesystem has been the default for many Linux distributions, it is
very common to find newer systems relying on XFS instead. XFS has many modern
advantages over ext4 and relatively few disadvantages.
• XFS recognizes a larger partition size.

• XFS recognizes a larger file size.

• XFS avoids inode exhaustion.

To format the second partition on the new disk with the XFS filesystem, use the
mkfs command but with a different option:
# mkfs.xfs /dev/sdb2

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 185 27/05/22 9:20 PM


186 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

XFS Tools are available to help manage the filesystem. Management tasks include
resizing the filesystem and gathering information. The tools are covered in a later
section.

The Btrfs Filesystem


An additional filesystem choice is Btrfs. This filesystem is very scalable, provides
easy management features, and is reliable. It is the default for modern Linux
distributions such as SUSE Linux Enterprise Server 15 and Fedora 35, though it has
been removed from RHEL 8 support, which prefers XFS.
The syntax to add the Btrfs to a partition is the same as for XFS and ext4. To add
this filesystem to the second partition on the second drive, type:
# mkfs.btrfs /dev/sdb2
Like XFS and ext4, Btrfs has a toolset to provide detailed information and
troubleshooting utilities. The toolset may already be installed on the system, or it
may need to be downloaded. In some cases, you will be required to compile the
toolset. The package is named btrfs-tools.
Information about a Btrfs-formatted partition is displayed with the following
command:
# btrfs filesystem show
The btrfs-tools package can also resize filesystems, much like XFS and ext4.
Whichever filesystem is selected for the new partition, the mkfs command is used
to install it. Each filesystem also has its own management and troubleshooting
tools.

Manually Test Mount


Now that you have installed the drive, created the partitions, and placed the
filesystem, the storage capacity is ready for use. Plan to test the storage space to
ensure it’s accessible to users. Storage capacity is added to the FHS by a process
called mounting. Capacity can be manually attached by using the mount command
and detached by using the umount command.

The mount and umount Commands


A new disk has been installed, partitioned, and provided with a filesystem. It is
now ready to be attached to a directory in the FHS. Attaching the storage area to a
directory makes the storage area accessible to users.
The term for attaching storage to the FHS is referred to as “mounting,” and the
command is mount. The logical reverse of this is to detach or unmount the storage
area, and the related command is umount.

Observe that umount is a slightly confusing way of unmounting. The command and
the concept are not spelled the same.

To mount the partition, first create a directory. The directory is referred to as a


mount point. Suppose the new storage capacity will be used to manage project
data. At the root of the filesystem, create a new directory named projects, and
then issue the mount command:
# mkdir /projects
# mount /dev/sdb2 /projects

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 186 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 187

Note that the syntax is similar to the mv or cp commands—from here to there. The
command could be interpreted as “attach the partition found at /dev/sdb2 to the
directory found at /projects.”
To test that the storage area is attached and usable, use the du and df commands.
External storage devices such as USB drives are mounted similarly. The path to the
device is specified along with the desired mount point. For removable drives, this
mount point is often a subdirectory of the /mount directory.
Assuming the USB drive is identified as sdc, use the following command to mount
the USB storage device:
$ mount /dev/sdc /media/usb

Sometimes there is confusion with the use of the word “filesystem.” One use involves
the format of a partition used to store data, such as ext4 or XFS. Another useinvolves
the organization of directories in a logical tree, such as the Linux Filesystem Hierarchy
Standard.

Test the Storage


You have partitioned the storage disk and formatted it with a filesystem. It’s
identified as /dev/sdb2, and it has been manually mounted to a directory
named /projects. The next step is to test whether the storage space is
available.
There are two approaches to testing: use reporting tools and actually storing data
in the new space. The df and du commands report storage information about
specified partitions or directories. Commands such as touch, mv, and cp place
data in the new storage location.

The du and df Commands


The df and du commands facilitate storage-space tracking. The df command
(“disk free”) enables you to view the device’s free space, file system, total size, space
used, percentage value of space used, and mount point. The du command (“disk
usage”) displays how a device is used, including the size of directory trees and files
within it. It also enables you to track space hogs, which are directories and files that
consume large amounts of space on the storage drive. These are go-to commands
to confirm excessive storage-space consumption that might be causing system
issues.
First, verify the disk usage of /projects. The command is: du -h
/projects

Output from the du -h /boot command displaying the size of each file in the directory.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 187 27/05/22 9:20 PM


188 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The result shows files and directories consuming space in the /projects
directory. Add the -h option to display the capacity in a human-friendly format;
otherwise, the output will display in bytes, which may be difficult to translate.
Next, check the storage space in use by using the df command. The syntax is the
same as for du, with the command being: df -h /projects

Output from the df -h /dev/sda1 command displaying the size of the partition.

To see a summary of space in use on all disks, type df without any arguments.
Both utilities are important to troubleshooting, testing, and capacity planning.

Move Data to the New Storage


Finally, to prove that storage space is available, copy an existing file to the
/projects directory (or use the touch command to create an empty file in
/projects). The command ls /projects should show the file.

Automatically Mount New Storage


Manually mounting the partition is effective for testing purposes, but it’s not
realistic to ask end-users to mount and unmount storage space regularly. Instead,
you need to automate the process to occur during the system’s boot phase so that
the space is immediately available to users.

Use a systemd.mount File


Many modern Linux distributions rely on the systemd system and service
management software suite to configure operating system settings and options.
One aspect of the systemd init process is to manage the automatic mounting of
partitions to the filesystem.
The systemctl command is used to display and change settings within systemd.
To display mounted partition information, type: systemctl -t mount
The following steps configure the system to mount the partition automatically:
1. Get UUID by using the blkid command (covered earlier): blkid /dev/
sdb2
2. Create a systemd unit file by using a text editor.

3. Restart the systemd service daemon: systemctl daemon-reload


4. Start the filesystem: systemctl start projects.mount
5. Enable the filesystem: systemctl enable projects.mount
The following is a sample of a systemd unit file that mounts the /projects
directory to the partition with the specified UUID. Assume the unit file is named
projects.mount.
# This file mounts the /projects directory via
systemd
[Unit]

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 188 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 189

Description=Project Directory (/projects)


DefaultDependencies=no
Conflicts=umount.target
Before=local-fs.target umount.target
After=swap.target
[Mount]
What=/dev/disk/by-uuid/eca1646e-3245-5bf5-faab-
31f6c424c09f
Where=/projects
Type=ext4
Options=defaults
[Install]
WantedBy=multi-user.target

The systemd suite is covered in detail later in the course.

The /etc/fstab File


Some distributions, especially older ones, rely on the /etc/fstab file to mount
partitions. Systems that use systemd still have and reference /etc/fstab, but
they supplement its settings.
The system reads /etc/fstab during startup. Partitions defined are identified
and mounted to the filesystem at the specified locations. The file is edited with a
standard text editor, but you must be careful not to make typographical errors.
The /etc/fstab file is divided into six fields.

/etc/fstab Field Value


Block device Drive and partition
Mount point Where the partition is mounted
Filesystem type The filesystem on the partition (XFS or ext4)
Mount options Read-write or read-only options, others
Dump Whether dump program backs up partition
(1 or 0)
FSCK order Order fsck checks partitions (1 for root, 2 for
all others)
A sample entry in the /etc/fstab file for the /projects directory might look
like this:
/dev/sdb2   /projects      xfs     rw     0    2
During system startup, the kernel reads /etc/fstab and mounts the specified
partitions to the listed mount points.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 189 27/05/22 9:20 PM


190 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Storage Deployment Summary


Because there are many steps necessary to add storage capacity to a Linux system,
it’s useful to see a summary of the process:
1. Physically install the storage device.

2. Confirm that Linux sees the storage device by using tools such as hwinfo,
lsblk, and lsscsi.
3. Partition the drive with fdisk or parted.

4. Add a filesystem such as ext4 or XFS by using the mkfs command.

5. Manually test mount the storage capacity to a mount point by using the
mount command.
6. Ensure the storage space is usable by copying actual data to the location
using cp.

7. Configure automatic mounting so that the capacity is available when the


system boots.

Manage Filesystems
Filesystems such as ext4 and XFS may require periodic maintenance. You may
wish to relabel the filesystem to something more descriptive or configure tunable
performance parameters. The filesystem may need to be expanded or shrunk
when using tools like parted to resize partitions. Here are several ext4 filesystem
management tools.

The fsck Command


A file system’s superblock contains metadata about that file system, including its
size, type, and status. The superblock is critical to the function of the file system,
and if it becomes corrupt, you may be unable to mount and work with the file
system. You can use a tool like fsck to repair the superblock, if necessary.

The e2label Command


File system labels are assigned to file systems for easy identification. The labels may
be up to 16 characters long and can be displayed or changed using the e2label
command for ext# file systems and the xfs_admin command for XFS file
systems.
The syntax for setting ext# file system labels is e2label /dev/{device
name}{partition number} {label name}
The resize2fs Command
The resize2fs command is used to enlarge or shrink an ext2/3/4 file system
on a device. You can enlarge a mounted file system, but you must unmount the file
system before you can shrink it. You can specify the desired size of the file system
in order to either enlarge or shrink it. If you don’t specify a size, the file system will
be resized to the same size as the partition.
It’s important to note that resize2fs does not resize partitions, only the file
system. You must use a command such as fdisk or an LVM tool to first expand
the size of the partition/volume and to then enlarge the file system.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 190 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 191

The syntax of the resize2fs command is resize2fs [options]


{device/file system name} [desired size]
The tune2fs Command
The tune2fs command helps you configure various “tunable” parameters
associated with an ext2/3/4 file system. Tunable parameters enable you to remove
reserved blocks, alter reserved block count, specify the number of mounts between
checks, specify the time interval between checks, and more.
You can also use tune2fs to add a journal to an existing ext2 or ext3 file system
(neither of which includes journaling by default). If the file system is already
mounted, the journal will be visible in the root directory of the file system. If the file
system is not mounted, the journal will be hidden.
The syntax of the tune2fs command is tune2fs [options] {device/
file system name}
The dumpe2fs Command
The dumpe2fs command is used to dump ext2, ext3, and ext4 file system
information. It prints the superblock and block group information for the selected
device. This can be useful when troubleshooting a faulty file system.
The syntax of the dumpe2fs command is dumpe2fs [options]
{device/ file system name}

Option for the dumpe2fs


Command Purpose
-x Print a detailed report about block numbers in
the file system.
-b Print the bad blocks in the file system.
-f Force the utility to display the file system status
irrespective of the file system flags.
-i Display file system data from an image file
created using the e2image command.

XFS Tools
There are many tools that enable you to work with the XFS file system.

XFS Tool Purpose

xfs_info Display details about the XFS file system,


including its block information.

xfs_admin Change the parameters of an XFS file system,


including its label and UUID.

xfs_metadump Copy the superblock metadata of the XFS file


system to a file.

xfs_growfs Expand the XFS file system to fill the drive size.

xfs_copy Copy the contents of the XFS file system to


another location.

xfs_repair Repair and recover a corrupt XFS file system.

xfs_debug Debug the XFS filesystem.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 191 27/05/22 9:20 PM


192 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Logical Volume Manager Storage


It’s common to add a single storage disk to a system to provide additional capacity.
The disk is then partitioned and its capacity used. The Logical Volume Manager
configuration is an alternative to this traditional partitioning scheme. The LVM
configuration is flexible and very scalable, often providing a better storage option
than single storage disks.
In the next section the discussion of LVM replaces the partitioning stage of adding
a disk. Other steps, such as detecting the storage disks and applying a filesystem,
remain the same.
The section begins with LVM concepts and then continues with LVM configurations.

Configure Logical Volume Manager


Logical Volume Manager functions based on three configuration layers for storage.
The first layer is one or more Physical Volumes (PV). PVs are drives or partitions
allocated to LVM. The next layer represents the aggregated storage capacity of any
designated PVs that are added to the Volume Group (VG). The top layer consists of
one or more Logical Volumes (LV), which are treated by the system as if they were
standard partitions. In reality, they are carved space from VGs that may store data
on multiple PVs.

The three levels of the Logical Volume Manager. Physical volumes combine to form the volume
group, which is then divided out in logical volumes to meet storage needs. (Images © 123RF.com.)

LVM provides a great deal of flexibility. Additional storage capacity can be added
to the VG and granted to the LV to provide storage space without interrupting or
reconfiguring user resources.
LVM maps whole physical devices and partitions (e.g., /dev/sda1, /dev/sdb2,
and so on) into one or more virtual structures called volume groups. Within these
volume groups are one or more logical volumes. Ultimately, the logical volumes
become the storage devices that the system, user, and applications work with.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 192 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 193

The /dev/mapper/ directory contains all of the logical volumes on the system
that are managed by LVM. Devices in this directory are typically formatted as:
/dev/mapper/<volume group name>-<logical volume
name>
In some cases, this directory may just include links to the actual logical volume
location.
Many distributions support LVM, and several actually place the root file system on
logical volumes during installation.
Compared to traditional physical partition management, LVM provides the following
benefits:
• Dynamically create, delete, and resize volumes without having to reboot the
system.

• Day-to-day management of volumes is easier once everything is set up.

• Map multiple logical volumes across multiple physical devices.

• A logical volume can exceed the size of any one physical device (as long as it
doesn’t exceed the total size of devices in the volume group).

• Create virtual snapshots of each logical volume so you can quickly and easily
revert a volume to a specific state.

One potential downside to LVM is that the initial setup can be somewhat complex.

LVM Management Tools


LVM divides its volume management tools into three categories based on the three
different components that make up LVM: the physical volume (PV), the volume
group (VG), and logical volume (LV) tools.

Physical Volume Tool Purpose


pvscan Scan for all physical devices that are being
used as physical volumes.
pvcreate Initialize a drive or partition to use as a
physical volume.
pvdisplay List attributes of physical volumes.

pvchange Change attributes of a physical volume.

pvs Display information about physical volumes.

pvck Check the metadata of physical volumes.

pvremove Remove physical volumes.

Volume Group Tool Purpose

vgscan Scan all physical devices for volume groups.

vgcreate Create volume groups.

vgdisplay List attributes of volume groups.

vgchange Change attributes of volume groups.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 193 27/05/22 9:20 PM


194 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Volume Group Tool Purpose

vgs Display information about volume groups.

vgck Check the metadata of volume groups.

vgrename Rename a volume group.

vgreduce Remove physical volumes from a volume


group to reduce its size.

vgextend Add physical volumes to volume groups.

vgmerge Merge two volume groups.

vgsplit Split a volume group into two.

vgremove Remove volume groups.

Logical Volume Tool Purpose


lvscan Scan all physical devices for logical volumes.
lvcreate Create logical volumes in a volume group.
lvdisplay List attributes of logical volumes.
lvchange Change attributes of logical volumes.
lvs Display information about logical volumes.
lvrename Rename logical volumes.
lvreduce Reduce the size of logical volumes.
lvextend Extend the size of logical volumes.
lvresize Resize logical volumes.
lvremove Remove logical volumes.

Deploy a Logical Volume Manager


The previous section covered the deployment of a single storage disk and partition.
However, if the production file server is expected to see significant traffic and
unknown storage requirements, you may decide that using LVM would provide a
more robust storage solution.
Once the disks are partitioned, it’s time to create the LVM structure. First, you’ll
designate the drives as LVM Physical Volumes (PV), then you’ll aggregate them into
a Volume Group (VG), and finally, you’ll allocate Logical Volumes (LV). The Logical
Volumes will be configured with filesystems, just like standard partitions were in
the earlier section.
You’ve installed two disks in the server that will become part of the LVM
configuration. Use the following steps to deploy a new Logical Volume. Display the
results of each command.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 194 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 195

Deploying the LVM


First, designate the two drives as LVM physical volumes by using the pvcreate
command followed by the path to the partitions:
# pvcreate /dev/sdb
# pvcreate /dev/sdc
# pvdisplay
The pvdisplay command allows you to confirm the configuration by displaying
the current settings.
Next, create a volume group named vg_projects containing the two physical
volumes designated above (/dev/sdb and /dev/sdc):
# vgcreate vg_projects /dev/sdb /dev/sdbc
# vgdisplay
Creating a volume group aggregates the storage capacity of one or more physical
volumes. The total capacity can then be managed as a single unit. The syntax for the
vgcreate command is vgcreate [options] new_vg_name PVs_
to_add
Options include the ability to set a maximum number of PVs or LVs associated with
the VG. Use the vgdisplay command to see the VG’s information.
Logical volumes are storage space carved from some or all of the capacity of a
VG. These logical volumes are treated by administrators as if they were standard
storage disks.
The syntax for the lvcreate command is lvcreate [options] new_
lv_name
Create a logical volume named projects consisting of 500G of storage capacity
within the vg_projects volume group:
# lvcreate --name projects --size 500G vg_projects
# lvdisplay
The lvdisplay command shows the current configuration of the logical
volumes.
The remaining deployment steps are the same as with traditional partitioning. You
will add a filesystem to the Logical Volume by using the mkfs command. Then
you’ll create a mount point, and the LVM storage space is mounted. The storage
capacity is now ready for users.

Resize LVM Storage


Using the pvcreate command enables you to add more storage space to an LVM
configuration by designating the new space as a physical volume and then adding
the physical volume to an existing volume group. This automatically increases
the capacity of the volume group. The logical volume is then extended with the
additional capacity.
Note that once the space is added to the logical volume, the filesystem must be
resized to format and take advantage of the increased capacity. The XFS tools or
ext4 utilities are used to resize the filesystem.

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 195 27/05/22 9:20 PM


196 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Storage Deployment
5

Answer the following questions:

1. What does /dev/sdc3 specify?

2. What role does the partprobe command play in the process of adding
storage?

3. What command adds the XFS filesystem to /dev/sdb2?

4. What is a mount point?

5. What are the three layers of an LVM deployment?

Lesson 7: Administering Storage | Topic 7B

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 196 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 197

Topic 7C
Manage Other Storage Options
6

EXAM OBJECTIVES COVERED


1.3 Given a scenario, manage files and directories

In some cases, direct-attached storage, such as internal drives, will not be sufficient
for the reliability, performance, or scalability requirements of a project. In such
cases, larger storage solutions, such as RAID, NAS, and SAN storage, may be
required. For security reasons, disk contents may need encryption.

Linux Unified Key Setup


Data stored on a disk is vulnerable to security breaches. One way of mitigating
this risk is to encrypt the data before it is written onto the disk. Linux Unified
Key Setup (LUKS) is a platform-independent full-drive encryption solution that is
commonly used to encrypt storage devices in a Linux environment. On Linux, LUKS
uses the dm-crypt subsystem incorporated in the Linux kernel around version
2.6. This subsystem creates a mapping between an encrypted device and a virtual
device name that the user space software can use. LUKS offers a high degree of
compatibility with various software because it standardizes the format of encrypted
devices.
The cryptsetup command is used as the front-end to LUKS and dm-crypt. The
LUKS extensions to cryptsetup support various actions, including those listed
in the table below.
The syntax of the cryptsetup command is cryptsetup [options]
{action} [action arguments]
In this syntax, various LUKS commands are substituted for the {action} field.

LUKS Action Purpose

luksFormat Format a storage device using the LUKS


encryption standard.

isLuks Identify whether a given device is a LUKS


device.

luksOpen Open a LUKS storage device and set it up for


mapping, assuming the provided key material
is accurate.

luksClose Remove a LUKS storage device from mapping.

luksAddKey Associate new key material with a LUKS


device.

luksDelKey Remove key material from a LUKS device.

Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 197 27/05/22 9:20 PM


198 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Before encrypting a device, it’s a good idea to overwrite its contents with random data
or all zeros. This ensures that no sensitive data from past use remains on the device.
The shred command can be used to securely wipe a storage device in this manner.
The syntax is shred [options] {file-name}

Redundant Array of Independent Disks


As identified earlier, individual storage disks are a single point of failure, putting
data at risk of being lost or unavailable. One way of mitigating this risk is to use
redundant arrays of independent disks (RAID) or combinations of two or more disks
to store data. However, not all RAID standards mitigate the risk of lost data; some
forms only provide performance benefits.

RAID Standards
Three common RAID standards are RAID 0 (disk striping), RAID 1 (disk mirroring),
and RAID 5 (disk striping with parity).
Disk striping (RAID 0) relies on at least two disks. The disk partitions are divided
into sections called stripes and data is written sequentially through the stripes.
Because RAID 0 provides no fault tolerance, it is mainly used for performance
benefits with application data that does not need to be preserved (such as caching).

RAID 0 disk striping. (Images © 123RF.com)

Disk mirroring (RAID 1) duplicates data on two storage disks. This provides
complete redundancy (100% of the data resides on each disk) but is a relatively
inefficient use of storage capacity. RAID 1 usually results in faster reads than a
single standalone disk.

Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 198 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 199

RAID 1 disk mirroring. (Images © 123RF.com)

Disk striping with parity (RAID 5) is a modification of RAID 0 that provides


fault tolerance. Like RAID 0, stripes are created on the storage media, and data
is distributed across the stripes. In addition to regular data, parity information is
added to each disk. This parity information is used to recreate the missing data
from any one failed storage drive. RAID 5 is particularly useful for file servers.

RAID 5 Disk striping with parity. (Images © 123RF.com)

Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 199 27/05/22 9:20 PM


200 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

RAID 0 Traits RAID 1 Traits RAID 5 Traits


Speed increase - less Speed increase for Speed increase - much
data written to each reads - either disk like with RAID 0
drive, and data written services the read call
simultaneously to each
drive
Reduced fault tolerance Increased fault Increased fault
- the failure of any one tolerance - even if one tolerance - data from
drive results in all the disk fails, the other disk any one failed drive is
data being unusable contains everything recreated in memory
needed to continue
Requires at least two Requires two disks Requires at least three
disks disks
While performance benefits are always appreciated, most administrators will select
RAID solutions in an effort to gain fault tolerance.

Software RAID
Most servers contain hardware RAID controller cards. These cards provide a
performance benefit and allow flexible configurations. However, operating systems
such as Linux can configure and manage storage devices like RAID arrays. In Linux,
the mdadm command manages RAID. Think of the mdadm command as “multiple
device administration.”
To display information on a RAID array, use the mdadm command with a series of
flags. The flags set mdadm into different modes, such as Assemble, Monitor, and
Build.

mdadm Flag Purpose

--monitor Monitor changes to the array, such as a


failed drive.

--manage Add or remove storage, designate


spares.

--verbose Provide detailed output.

The mdadm utility also provides a dynamic file that displays messages and status
information related to RAID arrays. To display the contents of this file, type:
cat /proc/mdstat
The output of the cat /proc/mdstat command displays the RAID level the
kernel currently supports and any current RAID configurations. The RAID levels are
referred to as “Personalities” and will exhibit values such as [raid1] or [raid5].
Any configured RAID arrays are identified on an md_d0 line, which consists of the
current RAID configuration and a list of disks that are members of the array. For
example, the output might look like the following:
Personalities : [raid0] [raid1] [raid5]
md_d0 : active raid1 sde1 sdf1

Network-Attached Storage
A network-attached storage (NAS) device is a dedicated network node that
provides inexpensive, scalable, and easy-to-configure storage. The device is
essentially an enclosure of storage drives managed by a minimal open-source
operating system.
Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 200 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 201

The NAS has a network configuration (usually an IP address) that makes it


accessible from any client able to reach that address.

Distinguish Network File Systems for NAS


Files stored on the NAS are made available on the network by using one of two
common network file systems: either Network File System (NFS) or Server
Message Blocks (SMB). SMB is commonly associated with Microsoft Windows
systems, but it is not exclusive to them.

SMB is sometimes referred to as Common Internet File System (CIFS).

A small network segment containing a Network-Attached Storage device. (Images © 123RF.com.)

The SMB protocol provides users with shared access to files and other resources
across a local area network (LAN). SMB clients make requests for resources
to SMB servers, which respond and provide the appropriate level of access. This
protocol is primarily used with Windows computers. However, SMB-compatible
software called Samba helps interface Linux and Windows hosts running network
shares.
Common Internet File System (CIFS) is a specific implementation of SMB.
Microsoft designed it as a successor to SMB version 1, but SMB versions 2 and 3
superseded it. However, Linux still uses the CIFS name in some of its tools, though
these tools support newer versions of SMB.
Network File System offers similar functionality to SMB, but the protocols are not
compatible. NFS is preferred in situations where Linux clients access Linux servers.
In environments that are a mix of Windows and Linux, the SMB protocol is the
better choice.

Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 201 27/05/22 9:20 PM


202 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

NFS configurations are covered in a future section.

Storage-Area Network
A storage-area network (SAN) is a significantly more expensive and complex
option. However, it is usually faster and more scalable. Dedicated storage devices
are managed as a single unit and are controlled by one or more Linux servers.
Network protocols communicate between the management nodes and the storage
devices. Two common protocols are Fibre Channel (FC) and Internet Small
Computers Systems Interface (iSCSI).

iSCSI Attributes Fibre Channel Attributes


Relatively easy to configure More difficult to configure
Standard and common to most IP Performance increase over iSCSI
networks and servers
SCSI commands over a standard IP SCSI commands over a Fibre Channel
network network

In some cases, Fibre Channel devices may be attached to the server. The fcstat
command displays information about existing Fibre Channel adapters. These
adapters are typically found in conjunction with SAN solutions.
The syntax for the fcstat command is fcstat [options] {driver-
name}
For example, to display driver-collected information for the Fibre Channel
connection, type:
fcstat fcs0
The fcstat command also contains subcommands that provide additional detail,
such as link statistics. The syntax for displaying link statistics is:
fcstat link_stats {link-number}

A network segment featuring a SAN using Fibre Channel protocols. (Images © 123RF.com.)

Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 202 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 203

Identify multipathd
One common attribute of SAN implementation is multipathing. This concept refers
to providing multiple connections between a server and its SAN storage devices.
The benefit is fault tolerance (in the event one path becomes unavailable) and
performance (load balancing across paths). In Linux, multipathd is responsible
for checking and displaying information about paths.
The multipathd daemon manages the paths and reconfigures the network map as
needed to react to changes in paths (such as failures).
The multipathd command displays information about the state of paths.
For example, to display the current configuration, type multipathd show
config.
Network File Systems for SAN
Like standard file servers and NAS devices, SAN storage solutions may be
configured with NFS or SMB network filesystems. Users can connect to these shared
resources to access files and directories.
Note that the NFS and SMB protocols provide communication between network
clients and the filesystem. These operate on a higher level than iSCSI and Fibre
Channel, which govern the communication between the hosting server and
connected SAN storage.

Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 203 27/05/22 9:20 PM


204 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Storage Options
7

Answer the following questions:

1. Why is RAID 5 fault tolerant and RAID 0 not?

2. You purchase two 100 GB storage disks to use in a RAID 1 mirror.


Assuming the entire storage capacity of both disks is at your disposal,
what is the maximum amount of data your RAID 1 array can store?

3. What do the Fibre Channel and iSCSI standards provide?

Lesson 7: Administering Storage | Topic 7C

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 204 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 205

Topic 7D
Troubleshoot Storage
4

EXAM OBJECTIVES COVERED


4.1 Given a scenario, analyze and troubleshoot storage issues.

Storage media performance is based on capacity and read/write capabilities. Read/


write tasks are measured based on input and output performance values and
sysadmins want these tasks to be as efficient as possible. Slow disk performance
can significantly impact the overall server performance. Measuring and addressing
I/O issues requires the use of several tools, as noted in this Topic.

Disk Performance
Storage devices read and write data, an action referred to as input/output (IO). Even
with solid-state storage, drive actions may be one of the slowest tasks the server
performs. Factor in many users reading and writing simultaneously, and it’s easy to
see why disk performance is a concern for sysadmins.
NVMe storage disk detection may fail during the initial installation of the drive or
during later boot sequences. Ensure the BIOS settings are correct for the storage
disk type and that the GRUB2 configuration file does not contain typos when
referencing the NVMe drive.
NVMe disks are also prone to failure from heat, so proper cooling is essential, and
frequent backups are recommended.

GRUB2 is discussed in a later section.

High Latency
Latency refers to the time it takes for data to travel across the communications
media. In the case of direct-attached storage (such as local storage disks), the media
is the motherboard, disk controllers, and connecting cables. Latency is any delay
as the data travels the path. Some latency is inevitable; the goal is to ensure the
latency is acceptable within the server’s performance requirements. The goal is for
this number to be as low as possible.
The organization’s individual needs define storage performance. Often these
needs will vary by service. For example, web services have different performance
requirements than database services. Hardware specifications, software, and
specific configurations impact disk IO performance and wait times. These variables
make it difficult to identify ways to decrease latency and improve throughput.

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 205 27/05/22 9:20 PM


206 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Low Throughput
Throughput is a measure of the storage device’s effective bandwidth, or ability
to move data to or from the drive. The goal is for this number to be as high as
possible.
Managing disk performance begins with purchasing a server with the appropriate
storage specifications. These specifications impact the drive’s throughput. Often,
this means SCSI or SAS storage, as SATA may not perform well enough for servers
with many storage devices. The drives themselves are important, too, not just the
control interface. For physical disks, the RPM value should be as high as possible—
often 15,000 RPMs.
Organizing storage into RAID arrays may also provide a performance benefit in
addition to fault tolerance. Hardware RAID controllers are typically preferred.

Measuring IOPS
You can check performance by keeping track of the Input/Output Operations
per Second (IOPS). Identifying throughput to ensure that disk performance is
acceptable on a Linux server involves the iostat and ioping commands.
The iostat utility generates reports on CPU and device usage. For storage, it
provides input and output statistics for block devices and partitions. Using the -d
option to specify device information only, the iostat command lists the following
statistics for each storage device:
• Transfers (I/O requests) per second (tps).

• Number of blocks read per second (kB_read/s).

• Number of blocks written per second (kB_wrtn/s).

• The total number of blocks read (kB_read).

• The total number of blocks written (kB_wrtn).

You can use this report to monitor how a storage drive is being used and to identify
any potential bottlenecks. For example, a faulty drive might have lower reads and/
or writes per second than expected. You can also use the report to help you decide
how to best distribute the I/O load between the available devices.
The syntax of the iostat command is iostat [options] [device
names]
The ioping command generates a report of device I/O latency in real time. It will
continuously “ping” the specified device with requests and print information about
each request at the command line. By default, this information tracks how long it
took an I/O request to finish. Aside from specifying a device to test, you can also
specify a path name to test whatever device is associated with that path.
Consider using ioping to troubleshoot latency issues with storage devices,
especially if you believe your read and/or write speeds are slower than they
should be.

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 206 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 207

The syntax of the ioping command is ioping [options] {file/


directory/device name}. Some of the associated options are listed here:

Options for the ioping Command Purpose

-c {count} Specify the number of I/O requests to


perform before stopping.

-i {time} Set the time (interval) between I/O


requests.

-t {time} Set the minimum valid request time.


Requests faster than this are ignored.

-T {time} Set the maximum valid request time.


Requests slower than this are ignored.

-s {size} Set the size of requests.

Both iostat and ioping are useful for troubleshooting I/O errors that may
occur due to failing drives, performance issues, or storage disk driver problems.

Using I/O Schedulers


I/O scheduling is the process by which the operating system determines the order
of input and output operations of block storage devices. Scheduling is important
because, compared to CPU and memory operations, block storage operations
are relatively slow—especially in disk-based technology like hard disk drives. The
Linux kernel, therefore, doesn’t write or read to a drive in the order that requests
are submitted; instead, it prioritizes certain requests over others to minimize
performance issues that can come with I/O tasks.
Although the kernel handles scheduling automatically, you can configure the
scheduler with different behavior types. Some behaviors are more appropriate than
others in certain situations, and setting a new type may increase read/write speeds.
Sysadmins typically change the scheduler during the troubleshooting process to
finely tune storage performance when every bit of performance matters.
There are a number of different schedulers available to modern Linux kernel
versions. Three of the most commonly used are Deadline, cfq, and noop.

Deadline
The Deadline scheduler performs sorting of I/O operations using three queues: a
standard pending request queue, a read first in first out (FIFO) queue, and a write
FIFO queue; the latter two are sorted by submission time and have expiration values.
When a request is submitted, it is sorted into the standard queue and placed at the end
of its appropriate FIFO queue. When the top request of the FIFO queue becomes older
than the queue’s expiration, the scheduler stops working with the standard queue and
starts servicing requests from the top of the FIFO queue—in other words, it switches to
the oldest requests. This ensures that the scheduler doesn’t “starve” a request for too
long. This makes it ideal for certain workloads like multi-threaded workloads.

CFQ
This refers to the Complete Fair Queuing (CFQ) scheduler. It is the default scheduler
for modern versions of the Linux kernel. In this scheduler, each process is given
its own queue, and each queue has an interval by which it is accessed (its time
slice). The scheduler uses a round-robin system to access each queue and services
requests from these queues until either their time slices or requests are exhausted.

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 207 27/05/22 9:20 PM


208 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

When the queue is empty, the CFQ waits 10 milliseconds for any new requests in
the queue, and if it doesn’t see any, it moves on to another queue. Like the deadline
scheduler, this helps to minimize request starvation. Its advantage is that it services
processes fairly and provides good performance in most workload situations.

Noop
Noop is the simplest scheduler and does not sort I/O requests, but merely
merges them. This can be ideal in situations where the device or its storage
controller performs its sorting operations. It can also benefit devices that don’t
have mechanical components requiring seek time, like SSDs and USB flash drives,
because this scheduler doesn’t expend much effort in reducing seek time. However,
the previous two schedulers are preferred in most other situations.
Set the scheduler on a particular device by modifying the scheduler file located at
/sys/block/<device name>/queue/scheduler.
Setting the scheduler is as simple as echoing the desired option to this file, as in:
echo noop > /sys/block/sda/queue/scheduler
Note that this sets the scheduler for runtime only; the setting will revert upon
reboot. To ensure your changes persist, you must modify the system’s boot loader
configuration.

Capacity Issues
One of the great challenges for sysadmins is managing storage capacity. Storage
space is relatively inexpensive, and there are many storage options, from direct-
attached storage to network storage to cloud storage. Users often see no need to
delete data, and many files are kept just in case they’re needed.

Display Storage
To manage storage, begin by understanding what storage devices exist. Tools such
as blkid and lsblk display information about recognized storage devices. Another
resource is the /proc/partitions file, which delineates the partitions that
Linux is aware of. Display this information with the cat /proc/partitions
command. Finally, both fdisk and parted display drive and partition
information.
If the storage devices are organized using LVM, commands such as pvdisplay,
vgdisplay, and lvdisplay provide information about the configured
volumes.
The mount command displays all attached storage and may be useful for
understanding exactly where particular storage devices reside (they won’t always
be local).

Find Issues
The du and df commands are commonly used to gather specific storage utilization
information. Both tools are flexible and have many options.
Use df to get general information on the mounted storage capacity. Use df with
a specific device path to gather more information about a given partition. For
example:
# df
# df /dev/sda2

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 208 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 209

Output from the df command.

The du command provides utilization information and usually targets a specific


directory. Most sysadmins will immediately use du to target the /home directory
(within which are the home directories of all standard users). Users often consume
a great deal of storage capacity. You might use du in the following ways:
# du /home
# du /var/log

Output from the du command.

Resolve Capacity Issues


What should administrators suggest when the above tools identify storage capacity
challenges? One obvious approach is scaling up (larger capacity drives) or scaling
out (more drives). These suggestions are not free, however. Another option is to
move the data to a different storage location, such as a NAS or SAN. Some data can
also be archived and compressed by using the tar command.
Cloud storage is a viable option for many organizations. Cloud storage may provide
cost-effective, secure, and scalable storage for user data, backups, and company
information. Consider recommending cloud-based Storage as a Service (STaaS).
Whether dealing with direct-attached storage, NAS, SAN, or STaaS, disk quotas help
sysadmins manage storage capacity by forcing users to remove or archive unused
data. Many users do not realize the impact that storing large amounts of data on a
server can have on the server’s cost, maintenance, and performance.

Inode Exhaustion
Each file created on a Linux partition is given an identifier by the filesystem. This
identifier—called an inode—uniquely identifies the file. Filesystems such as ext4
have a limited number of inodes available to allocate. While the available number is
very high, filesystems that store many small files may eventually run out of inodes
to assign. This is referred to as inode exhaustion.
If you receive an error message such as “No space left on drive” or “Cannot create
directory” but there is still storage capacity available on the drive, you’ve likely
encountered an inode exhaustion issue.
You can use the df and du commands again in this case to troubleshoot this issue.
The df -i command displays the percentage of inodes consumed and available
in the IUse% column of the output. If you have available storage space but are
receiving an error message when creating files, check this value.

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 209 27/05/22 9:20 PM


210 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

The --inodes and -d options for du also display information on which


directories are consuming the most inodes. Try the following command:
# du --inodes -d /
Be aware that this command may take some time to complete depending on the
size of the filesystem.
XFS and BtrFS dynamically allocate inodes and are far less likely to run into this
issue. Their available inodes are based on a percentage of the filesystem size.

Filesystem Issues
Filesystem corruption often occurs when Linux servers are not shut down
gracefully. This is more prevalent with non-journaled filesystems (most modern
filesystems, such as XFS and ext4, are journaled).
The fsck utility can be run on disks to detect and attempt to correct issues. Note
that the volume must be unmounted for fsck to be run against it. The fsck
command was discussed in Topic 7B.
Filesystem mismatch errors may be reported, especially after changes to the
filesystem or partition size. This issue may occur when an application (or the
system) attempts to write to the storage disk location where the filesystem
superblock resides. It may also happen if the storage disk itself is damaged or if
there is a misconfiguration of the filesystem or partition table.
You may be able to recover and access data by unmounting the filesystem (in
rescue mode) and using a repair utility such as fsck.

Mount Options Issues


Errors in the /etc/fstab file or in systemd.mount unit files may cause
filesystems not to mount when the system boots. One of the most common issues
is references in the file that point to nonexistent drives or nonexistent mount
points. Another common issue is typographical errors of any sort that direct the
system to mount a filesystem in an invalid manner.
Care must be taken when working with /etc/fstab and systemd.mount
files to not make any errors. If necessary, boot into rescue.target to correct
these files.

Device Issues
There are common troubleshooting steps for storage devices. Begin by ensuring
Linux is aware of the device. Commands such as blkid and lsblk display
storage device information. The hwinfo command can be filtered to show storage
disks, too. If the disk is not detected by Linux, confirm its physical connectivity
by checking the interface and power cable for a tight connection. If the drive is
installed in a motherboard slot, confirm the connection is good.
Once physical connectivity is established, Linux should be able to detect the drive.

The CompTIA troubleshooting methodology was covered in Topic 1D.

Use fdisk or parted to display details on partition information. The /proc/


partitions file displays general partition information that the system is aware
of. Use the partprobe command to refresh this information.

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 210 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 211

If issues with the filesystem are suspected, use the various ext4 or XFS tools to
confirm the status of the filesystem.
Verify the drive can be mounted by using the mount command. First, create
a directory that acts as a mount point, and then attach the storage capacity to
the directory. If the partition is not automatically mounted at boot, check for
typographical errors in /etc/fstab or the systemd.mount file.
Network file servers share directories by using NFS or SMB to make storage capacity
available from across the network. These remote filesystems may also be mounted.
When troubleshooting mount issues with remote filesystems, first ensure network
connectivity is established by using tools such as ping and ip addr. Next, verify
the network file server has made the directories available on the network and that
the user has permission to mount and read/write to the directories.

Network tools such as ping and ip addr are covered in a later Lesson.

Display LVM Settings


Use the various display commands associated with LVM to detect issues. By
thinking of LVM deployments as three layers, it is easier to anticipate where
problems may arise. The lvdisplay command shows Logical Volume settings,
including which Volume Group the storage space is pulled from.
The vgdisplay command shows Volume Group configurations, including which
Physical Volumes are associated with the VG.
Use the pvdisplay command to view Physical Volume information. This
information can be supplemented by using commands such as blkid, lsblk,
and cat /proc/partitions.

Display RAID Settings


Many hardware RAID controllers provide their own software-management suites.
For software RAID implementations, use the mdadm command to display and
manage RAID configuration settings. In addition, the /proc/mdstat file
provides status information.

Both mdadm and /proc/mdstat were covered in an earlier section.

The fstrim Command


Based on how solid-state drives manage data, when users delete files, the files
do not actually get erased. Instead, the space is marked as available, but the
content remains. From the user’s perspective, the data is gone and unavailable.
SSD trimming actually removes the data and frees the space. SSD trimming is an
optional feature that proactively removes data so that the space is ready for new
information to be written.
Linux supports the fstrim command. Both the drive and filesystem must be
compatible with the trim function.

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 211 27/05/22 9:20 PM


212 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Storage Troubleshooting
5

Answer the following questions:

1. What command reports real-time disk latency information?

2. List the commands necessary to show configuration information for


each of the three layers of LVM.

3. When trying to save a file to a storage disk, you receive a message


stating the drive is out of space. The df command indicates there is
plenty of free space. What might be the issue?

4. You have added a partition to an existing disk by using fdisk. The


partition is not displayed by the cat /proc/partitions command. What
other command do you need to run?

Lesson 7: Administering Storage | Topic 7D

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 212 27/05/22 9:20 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 213

Lesson 7
Summary
5

Proper administration of storage directly impacts the server’s performance and the
ability of users to access critical data. System specifications, such as SATA, SCSI, and
SAS play an important role, as do design decisions such as traditional partitioning
versus LVM-based storage. In fact, it may be more efficient to store data on NAS,
SAN, or cloud-based devices rather than on internal storage disks. Monitoring
performance and troubleshooting storage disk issues are common sysadmin tasks.

Guidelines
These best practices and guidelines are provided for your use as revision tools or as
quick references in your job role.
• Understand the process of configuring storage with traditional partitions.

• Understand the process of configuring storage with LVM.

• Compare the benefits of LVM.

Command Reference Table


This list of commands and their associated syntax can also be found in Appendix B.

Command Syntax Purpose Covered in


lsblk lsblk Display Lesson 7, Topic B
{drive-path} information
about storage
devices
recognized by
the system.
lsscsi lsscsi Display Lesson 7, Topic B
[options] information
about SCSI
devices.
fdisk fdisk Create, modify, or Lesson 7, Topic B
[options] delete partitions
{device-name} on a storage
drive.
parted parted Create, destroy, Lesson 7, Topic B
[options] and resize
{device-name} partitions.

mkfs mkfs [options] Format new Lesson 7, Topic B


{filesystem-name} partitions.
{partition-name}
mount mount Attach storage to Lesson 7, Topic B
{filesystem-name} the FHS.
{directory-name}

Lesson 7: Administering Storage

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 213 27/05/22 9:20 PM


214 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Command Syntax Purpose Covered in


umount umount Detach storage Lesson 7, Topic B
{filesystem-name} from the FHS.
{directory-name}
df df [options] Display device Lesson 7, Topic B
{directory-name} storage
information.
du du [options] Display device Lesson 7, Topic B
{directory-name} usage
information.
e2label e2label /dev/ Display or modify Lesson 7, Topic B
{device name} file system labels.
{partition
number} {label
name}
resize2fs resize2fs Change the size Lesson 7, Topic B
[options] of an ext2/3/4
{device/file file system on a
system name} device.
[desired size]
tune2fs tune2fs Configure Lesson 7, Topic B
[options] parameters
{device/ file associated with
system name} an ext2/3/4 file
system.
dumpe2fs dumpe2fs Dump ext2, ext3, Lesson 7, Topic B
[options] and ext4 file
{device/ file system
system name} information.

cryptsetup cryptsetup Encrypt data Lesson 7, Topic C


[options] before it is
{action} written to disk.
[action
arguments]
shred shred [options] Securely wipe a Lesson 7, Topic C
{file-name} storage device
by overwriting
contents with
random data or
all zeros.
iostat iostat Display reports Lesson 7, Topic D
[options] on CPU and
[device names] device
storage.
ioping ioping Generate a Lesson 7, Topic D
[options] report of device
{file/ directory/ I/O latency in real
device name} time.

Practice Questions: Additional practice questions are available on the CompTIA


Learning Center.

Lesson 7: Administering Storage

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson07_pp173-214.indd 214 27/05/22 9:20 PM


Lesson 8
Managing Devices, Processes, Memory,
and the Kernel
1

LESSON INTRODUCTION
Linux sysadmins must identify and configure hardware resources. First, administrators
must be able to find hardware information using a series of commands to identify CPU,
memory, bus, and other hardware devices. Next, sysadmins manipulate processes
consuming hardware resources to optimize and troubleshoot the system. Often the
focus of this optimization is the CPU and memory. Finally, the Linux kernel—the core
of the operating system—may be managed to maintain performance, enable modern
features, and provide compatibility with current hardware.

Lesson Objectives
In this lesson, you will:
• Gather hardware information.

• Manage processes.

• Manage memory.

• Manage the Linux kernel.

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 215 26/05/22 10:57 PM


216 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Topic 8A
Gather Hardware Information
2

EXAM OBJECTIVES COVERED


1.1 Summarize Linux fundamentals.
4.3 Given a scenario, analyze and troubleshoot central processing unit (CPU) and
memory issues.

Identifying recognized hardware on the Linux system is a critical part of device


management. Various commands provide details on the CPU, memory, graphics
cards, network cards, and storage controllers. Linux also recognizes newly installed
devices by using a device manager called udev. Often, device information is
dynamically gathered by Linux during the boot process to ensure that the displayed
information accurately reports recognized hardware.

Use Hardware Information Tools


Several tools exist to report hardware details. These commands may display
manufacturer, model information, and Linux configuration settings. General tools,
such as the hwinfo command, often contain useful options to narrow report
results, allowing you to focus on just the hardware you need.
Hardware information can be used for many sysadmin tasks, including system
upgrades, performance monitoring, troubleshooting, and inventory management.
For example, if you submit a support ticket to a software vendor, you will likely need
to provide details about the system the software runs on.

Use the hwinfo Tool


The hwinfo command displays detailed information on hardware resources Linux
is aware of. These resources include:
• Central processing unit (CPU)

• Storage disk controllers

• USB controllers

• Graphics cards

• Network interface cards (NIC)

• Print devices

One common option used with hwinfo is --short, which returns abbreviated
information on the resources. Using either hwinfo or hwinfo --short
displays information on all detected hardware. However, it’s more likely you’ll want
details for specific devices.

Lesson 8: Managing Devices, Processes, Memory, and the Kernel | Topic 8A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 216 26/05/22 10:57 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 217

Option for the hwinfo Command Purpose


--cpu CPU information

--netcard NIC information

--storage Storage disk controllers information

--block Storage disk information

--usb USB controller information

For example, to display CPU information, type hwinfo --short --cpu

The output of the hwinfo command.

Use the dmidecode Tool


Similar to hwinfo, dmidecode displays system information for current devices.
It also indicates upgrade possibilities by showing maximum processor and memory
upgrades.
Display information for specific devices by using the -t option along with the
device type. For example, type dmidecode -t cpu to display CPU information.

The output from dmidecode may be very long. Use the pipe redirector to display
the information in a pagination utility such as less or more.

Display Bus Information


You can display additional information about devices attached to specific busses
with commands such as lspci and lsusb. Both commands offer various levels
of detail (or verbosity) to display just the information you need.
With either command, try the -tv option to display verbose information in a tree
structure, allowing you to see devices connected to specific controllers.

Output of the lspci command along with the -tv option.

Lesson 8: Managing Devices, Processes, Memory, and the Kernel | Topic 8A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 217 26/05/22 10:57 PM


218 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Devices in the /dev Directory


The udev device manager provides plug-and-play functionality by generating
device files when the system boots for whatever hardware devices it detects.
These device files provide an interface for Linux (and users) to interface with
the devices.
Note that the device files are not the same thing as the device drivers. Device
drivers reside between the device files and the hardware devices, allowing
communication between the two (and therefore between the OS and hardware).

Use the udev Device Manager


The udev device manager detects hardware changes, such as the addition or
removal of a hardware device, on the system. The devices are represented as files
in the /dev directory.

Recall that in the previous section, you displayed storage device information from the
/dev/sda file.

It’s possible to test the udev device manager by using the monitor subcommand.
Run udevadm monitor and then attach a new USB device to the system. You
should see the device is detected and the output shows device details.
Information can be displayed for specific attached devices by using the udevadm
command. For example, type udevadm info /dev/sda to see storage
device information.

The term “storage device” represents traditional magnetic hard disk drives, modern
solid-state drives, USB flash drives, and any other media used to store data.

Identify Block, Character, and Special Devices


If you execute the ls -l command on the /dev directory, the device files are
displayed. You might notice the leftmost field in the permissions string is either
the letter b or c. These characters identify the device as either a block or character
device.

Partial output of the /dev directory.

Lesson 8: Managing Devices, Processes, Memory, and the Kernel | Topic 8A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 218 26/05/22 10:57 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 219

Character devices, such as keyboards, deal with data on a per-byte or character


level. Hard disk drives, however, are examples of block devices. Data is moved
in blocks, and the device can be mounted as a storage area. Information may be
cached, too. Device drivers are developed differently for each of the two device
types.

Device Type I/O Process Method Example


Block device Processes I/O in blocks and can be Storage devices
mounted
Character device Processes I/O on a per-character basis Keyboard, mouse

Three other device files are listed: null, zero, and urandom. These are known
as the special device files.
The /dev/null special file is a writeable location that is used as a target for
generated data that should be discarded. This data may be error messages that are
redirected to /dev/null by using the 2> redirector.
The /dev/zero file is a way of filling storage capacity. For example, using the
dd command, a sysadmin can create a file of a specified size as part of testing. For
example, to create a one MiB file named foo.txt, run the following command:
# dd if=/dev/zero of=foo.txt count=1024 bs=1024
This command uses /dev/zero as the source of data that fills the file to its
specified size.
The /dev/urandom file can create is a source of random characters for
tasks such as creating completely randomized passwords. Take care of how this
command runs on low-performing systems at the risk of consuming all available
resources.

Display CPU Information


The utilities hwinfo and dmidecode are not the only commands that can
display processor information. Two other CPU-specific display commands are
lscpu and cat /proc/cpuinfo.
Sysadmins may need details on the CPU(s) as part of performance monitoring,
hardware inventory, when considering processor upgrades, and when building a
virtualization host.
The lscpu command gathers information on the CPU. The entire output can be
displayed or specific columns selected. Information on each CPU includes cores,
sockets, caches, family, and model. The output isn’t well-formatted by default, so
add the -e option to display the results in columns:
$ lscpu -e
The /proc/cpuinfo file is dynamically created when the system boots,
providing current configuration information about the CPU. This information
includes the processor’s specifications but also details on a per-core basis. You can
read the file by using commands such as cat.

Lesson 8: Managing Devices, Processes, Memory, and the Kernel | Topic 8A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 219 26/05/22 10:57 PM


220 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

A portion of the output from the head /proc/cpuinfo command.

Display Memory Information


Troubleshooting and managing system memory is just as important as monitoring
the CPU. Linux reports the memory configuration of the system in several places.

This section covers installed memory, not how that memory is being utilized. Memory
utilization is covered in a future section.

Memory Tools
Use the lsmem command to display memory blocks, including their size and state
(online, offline).

The output of the lsmem command.

Much like the /proc/cpuinfo file, the /proc/meminfo file displays


statistics and details about currently recognized memory on the system. The file
can be read using the cat command.

Lesson 8: Managing Devices, Processes, Memory, and the Kernel | Topic 8A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 220 26/05/22 10:57 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 221

A portion of the output from the head /proc/meminfo command.

File contents might be useful when troubleshooting memory. For example, if you
believe the system has 64 GB of RAM installed, but only 32 GB are reported, you
can use this file to see what memory Linux recognizes. Doing so may help identify
which sticks of RAM are not recognized (and therefore, may not be seated in the
motherboard correctly).

Lesson 8: Managing Devices, Processes, Memory, and the Kernel | Topic 8A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 221 26/05/22 10:57 PM


222 | The Official CompTIA Linux+ Student Guide (Exam XK0-005)

Review Activity:
Hardware Information
3

Answer the following questions:

1. What two commands display information on motherboard busses?

2. When is the /dev directory populated?

3. How might /dev/zero be used to help create a file of a given size?

4. What file has the make, model, number of cores, and other details
about the CPU?

Lesson 8: Managing Devices, Processes, Memory, and the Kernel | Topic 8A

LICENSED FOR USE ONLY BY: PRANAV KAMBLE · 31662591 · OCT 10 2022

Linux+_XK0-005_Lesson08_pp215-250.indd 222 26/05/22 10:57 PM


The Official CompTIA Linux+ Student Guide (Exam XK0-005) | 223

Topic 8B
Manage Processes
5

EXAM OBJECTIVES COVERED


1.4 Given a scenario, configure and use the appropriate processes and services.
4.3 Given a scenario, analyze and troubleshoot central processing unit (CPU) and
memory issues.

Processes are instances of running code. These may be parts of the OS, services,
applications, or scripts. Some processes are executed as part of the system, while
others are initiated and managed by users. Each process is assigned a unique
process identification number (called a PID), and this number is used to manage
the process throughout its life cycle. This section covers process management,
troubleshooting, and optimization.

Processes Concepts
Process management is an essential part of performance monitoring and
troubleshooting on Linux systems. Sysadmins manage processes with tools that
indicate their resource consumption, status, and priority levels.</