
ISBN: 9781775062103 (Paperback Edition) ASIN: B076BYDB84 (eBook Edition)
The focus of this book is to present the basics of Linux in an easy-to-understand manner while covering the objectives and preparing the readers for the certification exams. In order to study the nitty-gritties of Linux while preparing for the exams at the same time, I have provided guidance in chapter 1 on how to set up a lab environment. I have used CentOS 7.3, Ubuntu 14.04.5, and CentOS 5.11 for examples, demonstrations, and exercises throughout this book. I have chosen CentOS 7.3 to explain new concepts and additions, such as systemd and journald, introduced in the latest release of the official exam objectives; Ubuntu 14.04.5 to present Debian-specific tasks, such as APT package management system; and CentOS 5.11 to cover older stuff such as SysVinit and GRUB Legacy.
The book is organized in two parts. Each part covers the objectives for one exam. There are 15 chapters altogether that are organized to learn Linux in a progressive manner.
Part ONE (chapters 1 to 8) covers topics that will help readers learn Linux essentials and build certain system administration skills while preparing for exam LX0-103/101-400. Material presented includes CentOS and Ubuntu installations; general Linux concepts and basic commands; compression and archiving; online help; file system hierarchy concepts, and file and directory operations; file types, access permissions, and ownership; file linking, searching, and special permissions; text file editing and data manipulation with filter programs; regular expressions; Bash shell features and process manipulation; shared libraries, and Debian and rpm package administration; system boot and initialization; hardware management and kernel modules; disk partitioning and file system build and repair; and quota and swap administration.
Part TWO (chapters 9 to 15) covers additional topics on system administration and prepares readers for exam LX0-104/102-400. Material presented includes automation with shell scripts; SQL database management and query; users, groups, password aging, and shell startup files; networking fundamentals and network interface configuration; routing and Internet services; network connection testing and troubleshooting; Linux support for internationalization and localization; time synchronization and hostname resolution; X Window, desktops, and accessibility options; printer and print queue administration; task scheduling and local and remote message logging; TCP Wrappers and email; secure shell and GnuPG management; and miscellaneous topics on file searching for auditing, in-use file identification, and PID identification using a specific file.
Each chapter begins with highlights of major topics and relevant exam objectives covered and ends with a summary followed by an at-a-glance chapter review. Throughout the book, figures, tables, and screenshots have been furnished to support explanation. This book includes more or less 400 practice questions and answers for each exam in the appendices.

Certification

The CompTIA Linux+ Powered by LPI certification exams (LX0-103 and LX0-104) [also referred to as LPIC-1 exams 101-400 and 102-400] test a candidate’s foundational knowledge of the Linux system. Each exam is 90 minutes in length and there is a mix of 60 single-response, multiple-response, and fill-in-the-blank type questions. During the exams, candidates do not have access to the Internet, a running Linux system, an electronic gadget, or to printed and electronic documentation, and they are not allowed to talk to other candidates taking the exam. Visit https://certification.comptia.org/certifications/linux or http://www.lpi.org/our-certifications/lpic-1-overview for up-to-date and in-depth information and exam policies. The official exam objectives are grouped in 10 major categories (or topics)—4 for LX0-103/101-400 and 6 for LX0-104/102-400. Each major topic also indicates a percentage of its coverage. These 10 major topics and their percentages are: LX0-103/101-400Topic 101: System architecture 14% LX0-104/102-400Topic 105: Shells, Scripting, and Data Management 17% Each major topic is divided into multiple sub-topics (or exam objectives). There are a total of 86 objectives for LX0-103/101-400 and 75 for LX0-104/102-400. Each objective provides a description, lists the knowledge areas, and highlights the files, key terms, and commands that are included in it. Each objective has a “weight” associated with it, which designates the number of questions to expect on the exam from that objective. For instance, objective 101.1 with weight 2 implies that you expect to see 2 questions on the exam covering knowledge areas 1 to 8 and the listed files, terms, and utilities. Based on the above explanation, here is the number of questions from each topic that you should expect to see on the certification exams: LX0-103/101-400, # of QuestionsTopic 101: System architecture, 8 LX0-104/102-400, # of QuestionsTopic 105: Shells, Scripting, and Data Management, 10Topic 106: User Interfaces and Desktops, 4 Topic 107: Administrative Tasks, 12 Topic 108: Essential System Services, 11 Topic 109: Networking Fundamentals, 14 Topic 110: Security, 9 Total: 60 For convenience, I have enumerated “key knowledge areas” under exam objectives and highlighted the chapter(s) where you can find them. I have also provided a description alongside each objective for assistance in locating them in the book. If an objective spans multiple chapters, apposite references are furnished. This information is furnished at the beginning of each chapter as well. I have also summarized the exam objectives, chapters you can find them, associated weights, the number of questions to expect on the exam, and other useful information in a tabular format under “Summary of Exam Objectives and Relevant Details” following the detailed list of the exam objectives. This summary contains most of the information that I have already described here; however, the intent is to provide a quick and convenient reference. LX0-103/101-400 Exam ObjectivesTopic 101: System Architecture (14%)101.1 Determine and configure hardware settings (weight 2) Candidates should be able to determine and configure fundamental system hardware. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /sys, /proc, /dev, modprobe, lsmod, lspci, lsusb 101.2 Boot the system (weight 3) Candidates should be able to guide the system through the booting process. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: dmesg, BIOS, bootloader, kernel, initramfs, init, SysVinit, system 101.3 Change runlevels / boot targets and shutdown or reboot system (weight 3) Candidates should be able to manage the SysVinit runlevel or systemd boot target of the system. This objective includes changing to single user mode, shutdown or rebooting the system. Candidates should be able to alert users before switching runlevels / boot targets and properly terminate processes. This objective also includes setting the default SysVinit runlevel or systemd boot target. It also includes awareness of Upstart as an alternative to SysVinit or systemd. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/inittab, shutdown, init, /etc/init.d, telinit, system, systemctl, /etc/systemd/, /usr/lib/system/, wall Topic 102: Linux Installation and Package Management (18%) 102.1 Design hard disk layout (weight 2) Candidates should be able to design a disk partitioning scheme for a Linux system. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /(root) filesystem, /var filesystem, /home filesystem, /boot filesystem, swap space, mount points, partitions 102.2 Install a boot manager (weight 2) Candidates should be able to select, install and configure a boot manager. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: menu.lst, grub.cfg and grub.conf; grub-install, grub-mkconfig, MBR 102.3 Manage shared libraries (weight 1) Candidates should be able to determine the shared libraries that executable programs depend on and install them when necessary. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: ldd, ldconfig, /etc/ld.so.conf, LD_LIBRARY_PATH 102.4 Use Debian package management (weight 3) Candidates should be able to perform package management using the Debian package tools. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/apt/sources.list, dpkg, dpkg-reconfigure, apt-get, apt-cache, aptitude 102.5 Use RPM and YUM package management (weight 3) Candidates should be able to perform package management using RPM and YUM tools. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: rpm, rpm2cpio, /etc/yum.conf, /etc/yum.repos.d/, yum, yumdownloader Topic 103: GNU and Unix Commands (43%) 103.1 Work on the command line (weight 4) Candidates should be able to interact with shells and commands using the command line. The objective assumes the Bash shell. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 1: pwd, man, and uname], [chapter 4: bash, echo, env, export, set, unset, history, and .bash_history] 103.2 Process text streams using filters (weight 3) Candidates should be able to apply filters to text streams. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 2: head, tail, and less], [chapter 3: cat, cut, expand, fmt, od, join, nl, paste, pr, sed, sort, split, tr, unexpand, uniq, and wc] 103.3 Perform basic file management (weight 4) Candidates should be able to use the basic Linux commands to manage files and directories. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 1: tar, cpio, gzip, gunzip, bzip2, xz], [chapter 2: cp, find, mkdir, mv, ls, rm, rmdir, touch, file], [chapter 4: file globbing], [chapter 8: dd] 103.4 Use streams, pipes and redirects (weight 4) Candidates should be able to redirect streams and connect them in order to efficiently process textual data. Tasks include redirecting standard input, standard output and standard error, piping the output of one command to the input of another command, using the output of one command as arguments to another command and sending output to both stdout and a file. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 2: xargs] and [chapter 4: tee] 103.5 Create, monitor and kill processes (weight 4) Candidates should be able to perform basic process management. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 1: uptime], [chapter 4: &, bg, fg, jobs, kill, nohup, ps, top, pgrep, pkill, killall, screen], and [chapter 8: free] 103.6 Modify process execution priorities (weight 2) Candidates should be able to manage process execution priorities. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: nice, ps, renice, top 103.7 Search text files using regular expressions (weight 2) Candidates should be able to manipulate files and text data using regular expressions. This objective includes creating simple regular expressions containing several notational elements. It also includes using regular expression tools to perform searches through a filesystem or file content. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: grep, egrep, fgrep, sed, regex(7) 103.8 Perform basic file editing operations using vi (weight 3) Candidates should be able to edit text files using vi. This objective includes vi navigation, basic vi modes, inserting, editing, deleting, copying and finding text. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: vi, /, ?, h, j, k, l, i, o, a, c, d, p, y, dd, yy, ZZ, :w!, :q!, :e! Topic 104: Devices, Linux Filesystems, Filesystem Hierarchy Standard (25%) 104.1 Create partitions and filesystems (weight 2) Candidates should be able to configure disk partitions and then create filesystems on media such as hard disks. This includes the handling of swap partitions. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: fdisk, gdisk, parted, mkfs, mkswap 104.2 Maintain the integrity of filesystems (weight 2) Candidates should be able to maintain a standard filesystem, as well as the extra data associated with a journaling filesystem. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: du, df, fsck, e2fsck, mke2fs, debugfs, dumpe2fs, tune2fs, xfs tools (such as xfs_metadump and xfs_info) 104.3 Control mounting and unmounting of filesystems (weight 3) Candidates should be able to configure the mounting of a filesystem. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/fstab, /media, mount, umount 104.4 Manage disk quotas (weight 1) Candidates should be able to manage disk quotas for users. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: quota, edquota, repquota, quotaon 104.5 Manage file permissions and ownership (weight 3) Candidates should be able to control file access through the proper use of permissions and ownerships. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: chmod, umask, chown, chgrp 104.6 Create and change hard and symbolic links (weight 2) Candidates should be able to create and manage hard and symbolic links to a file. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: ln, ls 104.7 Find system files and place files in the correct location (weight 2) Candidates should be thoroughly familiar with the Filesystem Hierarchy Standard (FHS), including typical file locations and directory classifications. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: find, locate, updated, whereis, which, type, /etc/updated.conf LX0-104/102-400 Exam ObjectivesTopic 105: Shells, Scripting and Data Management (17%) 105.1 Customize and use the shell environment (weight 4) Candidates should be able to customize shell environments to meet users’ needs. Candidates should be able to modify global and user profiles. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 10: source, /etc/bash.bashrc, /etc/profile, ~/.bash_profile, ~/.bash_login, ~/.profile, ~/.bashrc, ~/.bash_logout], [chapter 4: env, export, set, and unset, alias, and lists], and [chapter 9: function] 105.2 Customize or write simple scripts (weight 4) Candidates should be able to customize existing scripts, or write simple new Bash scripts. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 9: for, while, test, if, read, seq, exec] 105.3 SQL data management (weight 2) Candidates should be able to query databases and manipulate data using basic SQL commands. This objective includes performing queries involving joining of 2 tables and/or subselects. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: insert, update, select, delete, from, where, group by, order by, join Topic 106: User Interfaces and Desktops (8%) 106.1 Install and configure X11 (weight 2) Candidates should be able to install and configure X11. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/X11/xorg/xorg.conf, xhost, DISPLAY, xwininfo, xdpyinfo, X 106.2 Setup a display manager (weight 1) Candidates should be able to describe the basic features and configuration of the LightDM display manager. This objective covers awareness of the display managers XDM (X Display Manger), GDM (Gnome Display Manager) and KDM (KDE Display Manager). Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: lightdm, /etc/lightdm 106.3 Accessibility (weight 1) Demonstrate knowledge and awareness of accessibility technologies. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: Sticky/repeat keys, mouse keys, high contrast/large print desktop themes, screen reader, braille display, screen magnifier, on-screen keyboard, gestures (used at login, for example gdm), orca, GOK, emacspeak Topic 107: Administrative Tasks (20%) 107.1 Manage user and group accounts and related system files (weight 5) Candidates should be able to add, remove, suspend and change user accounts. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/passwd, /etc/shadow, /etc/group, /etc/skel, chage, getent, groupadd, groupdel, groupmod, passwd, useradd, userdel, usermod 107.2 Automate system administration tasks by scheduling jobs (weight 4) Candidates should be able to use cron or anacron to run jobs at regular intervals and to use at to run jobs at a specific time. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/cron.{d,daily,hourly,monthly,weekly}, /etc/at.deny, /etc/at.allow, /etc/crontab, /etc/cron.allow, /etc/cron.deny, /var/spool/cron/*, crontab, at, atq, atrm, anacron, /etc/anacrontab 107.3 Localisation and internationalization (weight 3) Candidates should be able to localize a system in a different language than English. As well, an understanding of why LANG=C is useful when scripting. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/timezone, /etc/localtime, /usr/share/zoneinfo, environment variables (LC_*, LC_ALL, LANG, TZ), /usr/bin/locale, tzselect, tzconfig, date, iconv, UTF-8, ISO-8859, ASCII, unicode Topic 108: Essential System Services (17%) 108.1 Maintain system time (weight 3) Candidates should be able to properly maintain the system time and synchronize the clock via NTP. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /usr/share/zoneinfo, /etc/timezone, /etc/localtime, /etc/ntp.conf, date, hwclock, ntpd, ntpdate, pool.ntp.org 108.2 System logging (weight 3) Candidates should be able to configure the syslog daemon. This objective also includes configuring the logging daemon to send log output to a central log server or accept log output as a central log server. Use of the systemd journal subsystem is covered. Also, awareness of rsyslog and syslog-ng as alternative logging systems is included. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: syslog.conf, syslogd, klogd, /var/log/, logger, logrotate, /etc/logrotate.conf, /etc/logrotate.d/, journalctl, /etc/systemd/journald.conf, /var/log/journal 108.3 Mail Transfer Agent (MTA) basics (weight 3) Candidates should be aware of the commonly available MTA programs and be able to perform basic forward and alias configuration on a client host. Other configuration files are not covered. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: ~/.forward, sendmail emulation layer commands, newaliases, mail, mailq, postfix, sendmail, exim, qmail 108.4 Manage printers and printing (weight 2) Candidates should be able to manage print queues and user print jobs using CUPS and the LPD compatibility interface. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: CUPS configuration files, tools and utilities; /etc/cups, lpd legacy interface (lpr, lprm, lpq) Topic 109: Networking Fundamentals (23%) 109.1 Fundamentals of internet protocols (weight 4) Candidates should demonstrate a proper understanding of TCP/IP network fundamentals. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/services, IPv4, IPv6, subnetting, TCP, UDP, ICMP 109.2 Basic network configuration (weight 4) Candidates should be able to view, change and verify configuration settings on client hosts. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 11: /etc/hostname, /etc/hosts, ifconfig, ifup, ifdown, ip, route, ping] and [chapter 12: /etc/nsswitch.conf] 109.3 Basic network troubleshooting (weight 4) Candidates should be able to troubleshoot networking issues on client hosts. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 11: ifconfig, ip, ifup, ifdown, route, hostname, netstat, ping, ping6, traceroute, traceroute6, tracepath, tracepath6, netcat] and [chapter 12: host, dig] 109.4 Configure client side DNS (weight 2) Candidates should be able to configure DNS on a client host. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: /etc/hosts, /etc/resolv.conf, /etc/nsswitch.conf, host, dig, getent Topic 110: Security (15%) 110.1 Perform security administration tasks (weight 3) Candidates should know how to review system configuration to ensure host security in accordance with local security policies. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: [chapter 10: passwd, chage, sudo, /etc/sudoers, su, usermod, ulimit, who, w, and last], [chapter 11: nmap, netstat], and [chapter 15: find, fuser, and lsof] 110.2 Setup host security (weight 3) Candidates should know how to set up a basic level of host security. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: , [chapter 6: /etc/inittab, /etc/init.d/*], [chapter 10: /etc/nologin, /etc/passwd, /etc/shadow], [chapter 14: /etc/hosts.allow, /etc/hosts.deny], and [chapter 11: /etc/xinetd.d/*, /etc/xinetd.conf, /etc/inetd.d/*, /etc/inetd.conf] 110.3 Securing data with encryption (weight 3) The candidate should be able to use public key techniques to secure data and communication. Key Knowledge Areas:
The following is a partial list of the used files, terms and utilities: ssh, ssh-keygen, ssh-agent, ssh-add, ~/.ssh/id_rsa and id_rsa.pub, ~/.ssh/id_dsa and id_dsa.pub, /etc/ssh/ssh_host_rsa_key and ssh_host_rsa_key.pub, /etc/ssh/ssh_host_dsa_key and ssh_host_dsa_key.pub, ~/.ssh/authorized_keys, /etc/ssh_known_hosts, gpg, and ~/.gnupg/* |

A Sample from Chapter 02 "Working with Files and File Permissions"
Linux files are organized logically for ease of administration, and they are stored in hundreds of directories located in larger containers called file systems. Mainline Linux distributions follow the Filesystem Hierarchy Standard (FHS) for file organization, which describes names, locations, and permissions for many file types and directories. File systems are primarily of two types and they are used to retain permanent and runtime data.
There are a number of maintenance operations that can be performed on files and directories in addition to viewing their contents. Linux supports a variety of types of files, and the file type is based on the kind of data they store.
Permissions are set on files and directories to restrict their access to authorized users only. Users are grouped into three distinct categories. Each user category is then assigned required permissions. Permissions can be modified using one of two available methods. The user mask may be defined for individual users so that any new files and directories that are created always get preset permissions.
Every file in Linux has an owner and a group associated with it. There are tools available in the operating system that help in linking files and directories and in searching them using varying criteria. The OS offers three additional permission bits to control user access to certain executable files and shared directories.
Filesystem Hierarchy Standard (FHS)
Linux uses the conventional hierarchical directory structure based on the Filesystem Hierarchy Standard (FHS) document that outlines the specifics for the layout of the directories, the type of information they should store, and whether they should be shared. This standard helps store related information together in a logical fashion. Per the FHS, directories may contain both files and sub-directories. Sub-directories may further hold more files and sub-directories. A sub-directory, also referred to as a child directory, is a directory located under a parent directory. That parent directory is a sub-directory of some other higher-level directory. In other words, the Linux directory structure is similar to an inverted tree where the top of the tree is the root of the directory, and the branches and leaves are sub-directories and files, respectively. The root of the directory is represented by the forward slash (/) character, and this is the point where the entire structure is ultimately connected. The forward slash character is also used as a directory separator in a path, such as /etc/rc.d/init.d/network. See Figure 2-1 (next page).
In the /etc/rc.d/init.d/network path, the etc sub-directory is located under /, making root the parent of etc (which is a child). rc.d (child) is located under etc (parent), init.d (child) is located under rc.d (parent), and at the very bottom, network (leaf) is located under init.d (parent).
Each directory has a parent directory and a child directory, with the exception of the root and the lowest level directories. The root directory has no parent, and the lowest level sub-directory has no child. The term sub-directory is used for a directory that has a parent directory.
Static vs. Dynamic and Shareable vs. Non-Shareable
Some of the directories, such as /usr, /boot, and /opt, hold static data. These directories contain user commands, administrative commands, help files, and library files, as well as kernel and boot files. Static data is not usually modified. Other directories, such as /var, /etc, /tmp, and /home, contain dynamic (or variable) information. These directories hold log and spool files, configuration files, temporary files, and personal user files, respectively, that are modified and updated as required. Moreover, there are a few virtual file systems—/dev, /proc, and /sys—that hold runtime system information. They are created, maintained, and destroyed automatically by the kernel. These file systems are explained in Chapter 7 “Understanding and Configuring Hardware and Kernel Modules.”
In addition to identifying which directories are supposed to hold static and dynamic data, FHS also describes which directories can or cannot be shared over the network based on the type of information they store. For this, there are four categories outlined in FHS: (1) static and shareable (e.g. /opt and /usr), (2) static and unshareable (e.g. /boot and /etc), (3) variable and shareable (e.g. /var/mail and /var/opt), and (4) variable and unshareable (e.g. /var/lock and /run).
Common Directories Under /
The root directory contains higher-level directories that hold specific information. This structure may vary among Linux distributions and among versions of the same distribution. For instance, the structure in CentOS version 7 is slightly different from the previous versions and from Debian as well. Some of the key directories are:
- /etc (etcetera) to hold system configuration files
- /root as the default home directory for the root user
- /media (or /run/media) to automatically mount removable media such as floppy, CD/DVD, and USB
- /mnt to mount a file system temporarily
- /bin and /usr/bin to maintain user-level commands
- /sbin and /usr/sbin to store administrative commands, and
- /lib, /usr/lib, /lib64, and /usr/lib64 to store 32- and 64-bit library routines that are needed by various commands and programs for successful execution.
On CentOS 7, /bin, /lib, /lib64, and /sbin are simply pointers (soft links) to the actual directories under /usr; whereas, in CentOS 6 and earlier and in Debian, these directories exist directly under the top of the root file system as well as under /usr. They have more files in /usr/bin and /usr/sbin as compared to /bin and /sbin. Run ls -ld and ls -l | wc on all these directories to explore them. Replace with actual directory names.
File and Directory Operations
This section elaborates on various management operations that can be performed on files and directories. These operations include creating, listing, displaying contents of, copying, moving, renaming, and deleting files and directories. These common operations can be performed on files and directories by normal users who own or have appropriate permissions. The root user can perform these operations on any file or directory on the system, as it doesn’t matter who owns it. In case of lack of user permissions, an error message is generated.
Creating Files and Directories
Files can be created in multiple ways using different commands as required; however, there is only one command to create directories. Let’s look at them at the commands below.
Creating Empty Files Using the touch Command
The touch command creates an empty file and sets the modification and access times on the file to the time of its creation. If the file already exists, the touch command simply updates the timestamp on the file to match the current system date and time. Execute the following to create file1 and then run ll to verify:
[user1@centos73 ~]$ touch file1
[user1@centos73 ~]$ ll file1
-rw-rw-r--. 1 user1 user1 0 Jan 4 08:03 file1
As expected, the fifth field (the size field) in the output is 0, meaning that file1 is created with zero bytes in size. Now, if you re-run the touch command on this file after a minute or so, a new timestamp is placed on it:
[user1@centos73 ~]$ touch file1
[user1@centos73 ~]$ ll file1
-rw-rw-r--. 1 user1 user1 0 Jan 4 08:05 file1
The touch command has a few interesting options. The -d and -t options set a specific date and time on a file; the -a and -m options enable you to change only the access or the modification time on a file to the current system time; and the -r option sets the modification time on a file to that of the specified reference file’s.
Creating Short Files Using the cat Command
The cat command allows you to create short text files. The ending angle bracket “>”, as shown below, must be used to redirect the output to the specified file:
[user1@centos73 ~]$ cat > catfile1
Nothing is displayed when you execute the above, as the system is waiting for something to be input. Type some text. Press the Enter key to open a new line and continue typing. When you are done, press Ctrl+d to save the text in catfile1 and return to the shell prompt. You can verify the file creation with the ll command.
Creating Files Using the vi (vim) Editor
You can use the vi editor to create and modify text files of any size. Refer to Chapter 3 “Editing Text Files, Exploring Filters, and Using Regular Expression” on how to use this tool.
Making Directories Using the mkdir Command
The mkdir command is used to make directories. This command shows an output if it is run with the -v option. The following example demonstrates the creation of a directory called dir1:
[user1@centos73 ~]$ mkdir dir1 -v
mkdir: created directory ‘dir1’
You can create a hierarchy of sub-directories by specifying the -p option with mkdir. In the following example, mkdir is used to create the hierarchy dir2/perl/perl5. The -v option is added for prolixity.
[user1@centos73 ~]$ mkdir dir2/perl/perl5 -vp
mkdir: created directory ‘dir2’
mkdir: created directory ‘dir2/perl’
mkdir: created directory ‘dir2/perl/perl5’
Listing Files and Directories
In chapter 1 “Installing Linux and Using Basic Commands,” we looked at the ls command and how to use it with a number of common options to list files as desired. This is probably the most used command in Linux. The ll is the shortcut to ls -l, which is pre-defined on most Linux distributions. This command shows the details for each listed file in nine columns as depicted below:
-rw-rw-r--. 1 user1 user1 0 Jan 4 08:05 file1
drwxrwxr-x. 2 user1 user1 6 Jan 4 08:22 dir1
Each column in the output furnishes a unique piece of information about the file or directory:
Column 1: The first character (hyphen or d) divulges the file type and the next nine characters (rw-rw-r--) indicate permissions.
Column 2: Displays the number of links (links are explained later in this chapter).
Column 3: Shows the owner name.
Column 4: Displays the owning group name.
Column 5: Identifies the file size in bytes. For directories, this number reflects the number of blocks being used by the directory to hold information about its contents.
Columns 6, 7, and 8: Displays the month, day of the month, and time of creation or last modification.
Column 9: Indicates the name of the file or directory.
A grasp of the usage of this command and the output it produces is important. We will be using the shortcut ll throughout this book rather than the actual ls -l for brevity and convenience unless there is a specific need to use the actual.
Displaying File Contents
Linux offers a variety of tools for showing file contents. Directory contents are simply the files and sub-directories that it contains. Use ll as explained in Chapter 1 “Installing Linux and Using Basic Commands” to view directory contents.
For file viewing, you can use the cat, less, more, head, and tail commands. These tools are explained below.
Using the cat Command
cat displays the contents of a text file. It is typically used to view short files. It shows the entire file contents on the screen. In the example below, the .bash_profile file in user1’s home directory is displayed with the cat command:
[user1@centos73 ~]$ cat .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/.local/bin:$HOME/bin
export PATH
You can add the -n option to the cat command to view line numbers as well.
Using the less and more Commands
Both less and more are text filters that are used for viewing long text files one page at a time, starting at the beginning. The less command is more capable than the more command, and it should be treated as a replacement for more going forward. less does not need to read the entire file before it starts to display its contents, thus making it faster. The more command is limited to forward text searching only, whereas, its counterpart is able to perform both forward and backward searches. Run less /usr/bin/znew and more /usr/bin/znew and use the keys from Table 2-1 to navigate.
Key |
Purpose |
---|---|
Spacebar / f |
Scrolls forward one screen |
Enter |
Scrolls forward one line |
b |
Scrolls backward one screen |
d |
Scrolls forward half a screen |
h |
Displays help |
q |
Quits and returns to the command prompt |
/string |
Searches forward for a string |
?string |
Searches backward for a string; only applies to the less command |
n |
Finds the next occurrence of a string |
N |
Finds the previous occurrence of a string; only applies to the less command |
Table 2-1 Navigating with less or more
If /usr/bin/znew file is unavailable, use /etc/profile instead.
Using the head and tail Commands
head displays the starting few lines from the specified text file. By default, it shows the first ten lines. Run head /etc/profile and see the result. The output would include a few empty lines as well.
You can pass a numeral to the command as an argument to limit the output to that many lines. For example, run head -3 /etc/profile to view the first three lines only.
tail displays the ending ten lines from the specified file by default unless a numeral is passed as an argument to alter its behavior. Issue tail /etc/services and then tail -3 /etc/services to see the difference.
The tail command proves to be very useful when viewing a log file while it is being updated. The -f (follow) option enables this function. The following example shows how to view the system log file /var/log/messages in real time. First, switch the user ID from user1 to root, as user1 will not have the permission to view this file being it is a normal user. Enter the root user password when prompted.
[user1@centos73 ~]$ su -
Password:
[root@centos73 ~]# tail -f /var/log/messages
You may have to wait for some time before you see an update. Press Ctrl+c to quit when you are done. Type the exit command to exit out of the root user account and return to user1.
Copying Files and Directories
The copy operation duplicates a file or directory. Linux provides the cp command for this purpose. This command has a variety of options available that may be used to get the desired results.
Copying Files
The cp command copies one or more files within a directory or to another directory. To duplicate a file in the same directory, you must give a different name to the target file. However, you may assign the same or a different file name if the copy is being made to a different directory. Consider the following examples:
To copy file1 as newfile1 in the same directory:
[user1@centos73 ~]$ cp file1 newfile1
To copy file1 by the same name to an existing directory dir1:
[user1@centos73 ~]$ cp file1 dir1
By default, the copy operation overwrites the destination file if it exists without presenting a warning. To alter this behavior, use the -i (interactive) option to instruct cp to prompt for confirmation before overwriting:
[user1@centos73 ~]$ cp -i file1 dir1
cp: overwrite `dir1/file1'?
Press the Enter key after typing a “y” for yes or an “n” for no to proceed.
Some Linux systems, such as CentOS, has a pre-defined alias set for the root user to always use the -i option with the cp command.
You may add the -f option to cp to force it to overwrite a read-only destination file.
Copying Directories
The cp command with the -r or -R (recursive) option copies an entire directory tree to another location. In the following example, dir1 is copied to dir2 and then the directory contents of dir2 are listed for validation:
[user1@centos73 ~]$ cp -r dir1 dir2
[user1@centos73 ~]$ ll dir2
drwxrwxr-x. 2 user1 user1 19 Jan 4 15:52 dir1
drwxrwxr-x. 3 user1 user1 19 Jan 4 08:45 perl
You may use the -i option for overwrite confirmation if the destination already has a matching file or directory.
Try running ll dir2 -R to view the entire hierarchy.
The cp command can also use -p, which is another useful option that can provide the ability to preserve the attributes (timestamp, permissions, ownership, etc.) of a file or directory being copied. Try running cp -p file1 /tmp and then use ll to compare the attributes on both files.
Moving and Renaming Files and Directories
A file or directory can be moved within the same file system or to another. Within the file system move, an entry is added to the target directory and the source entry is removed, which leaves the actual data intact. On the other hand, a move to a different file system physically moves the file or directory content to the new location and deletes the source.
A rename simply changes the name of a file or directory; data is not touched.
Moving and Renaming Files
The mv command is used to move or rename files. The -i option can be specified for user confirmation if a file already exists by the same name at destination. The following example moves file1 to dir1 and prompts for confirmation:
[user1@centos73 ~]$ mv -i file1 dir1
mv overwrite: dir1/file1? (y/n)
To rename newfile1 as newfile2:
[user1@centos73 ~]$ mv newfile1 newfile2
You may add the -f option to mv to force the command to overwrite without prompting in case newfile2 already exists. The behavior of the -f option is opposite to that of the -i option.
Moving and Renaming Directories
To move a directory along with its contents to elsewhere, or to simply change the name of a directory, use the mv command. For example, to move dir1 under /tmp (/tmp must exist, otherwise it will be a rename operation), issue the following:
[user1@centos73 ~]$ mv dir1 /tmp
To rename dir2 as dir20:
[user1@centos73 ~]$ mv dir2 dir20
Removing Files and Directories
The remove operation deletes a file entry from the directory structure and marks its data space as free. For a directory, the remove operation weeds corresponding entries out from the file system structure.
Removing Files
You can remove a file using the rm command, which deletes one or more specified files. For example, to erase a file called newfile1, issue rm newfile1 at the command prompt. You may add the -i and -v options to control accidental erasures and add verbosity, respectively.
By default, you do not need the -i option specified for a yes/no confirmation if you are root. There is a pre-defined alias “alias rm=’rm -i’” in the root user’s ~/.bashrc file that takes care of that. In this case you may use the -f (force) option with rm to override the behavior of -i.
The rm command can also be used to remove a file that has a wildcard character, such as an asterisk (*) or a question mark (?), embedded in its name. These characters have special meaning to the shell, and filenames containing them must be prepended with the backslash () character to instruct the shell to treat them as regular characters.
A careful use of the rm command is particularly important when you have administrative rights on the system.
For example, if a file exists by the name * under the /tmp/ directory (use touch /tmp/* to create it), you can remove it by executing rm /tmp/*. If you mistakenly run rm /tmp/* instead, all files there will be deleted.
Wildcard characters are used in filename globbing and in commands where an action needs to occur on multiple files matching certain criteria. They are discussed in Chapter 4 “Dealing with the Bash Shell and Processes”.
Removing Directories
The rmdir and rm commands are available to remove directories. The rmdir command is used to delete empty directories, while the rm command requires the -d option to accomplish the same. In addition, we can use the -r or -R (recursive) option with rm to remove a directory and all its contents. Both commands support the -v option for reporting what they are doing. Let’s look at a few examples.
To erase an empty directory called emptydir (assuming emptydir exists), use either of the following:
[user1@centos73 ~]$ rmdir emptydir -v
[user1@centos73 ~]$ rm -dv emptydir
To remove dir20 and all its contents recursively, use either -r or -R with the command:
[user1@centos73 ~]$ rm -r dir20
Both -i and -f options are supported for interactive and non-interactive deletions.
The same rules that apply on filenames with wildcard characters in their names, apply on directory names as well. See the previous topic for details.

1. Pg 475, Appendix B - Answers to Sample LX0-103/101-400 Quiz - Answer to Question #13 "Which command can be used to determine the file type?" is A.