You are on page 1of 100

I) 301 BEST BASH COMMANDS \

HANDBOOK 2023 Edition

YOUR LINUX SKILLS


Power at Your
Fingertips
• Pipe and redirect output
• Monitor processes
• Create custom scripts

Keep this guide


as a permanent
reference!
ALL NEW!
INTERNET TOOLS
LINUX NEW MEDIA TERMINAL UTILITIES FOR
The Pulse of Open Source
[EMAIL AND GOOGLE SEARCH

WWW.LINUX-MAGAZINE.COM
openSUSE Conference

May 26 - 28, 2023


events.opensuse.org
WELCOME

BASH CLASS
Think like the experts: The powerful Bash shell provides a comprehensive collection
of utilities for configuring and troubleshooting Linux systems.

Before the icons, menus, and wobbly windows of the modern Linux user environment, users
managed and interacted with their systems from the command line. Many advanced users still
prefer to work from the keyboard, and many will tell you that exploring the command-line
environment is the best way to build a deeper understanding
of Linux. The Linux Shell Handbook is a thorough
primer on the Bourne Again Shell (Bash)
environment found on most Linux systems.
You'll learn to navigate, manipulate text,
work with regular expressions, and
customize your Bash settings. We'll show
you shell utilities for configuring
hardware, setting up users and groups,
managing processes, and installing
software - and we'll even help you
get started creating your own Bash
scripts to automate recurring tasks.
Keep the Linux Shell Handbook
beside your computer as a
permanent desktop reference on
the world of the terminal window.

paylessimages, 123RF.com LINUX SHELL HANDBOOK- 2023 EDITION 3


LINUX

GETTING AROUND

6 Introducing Bash 14 Regular Expressions


The Bash command shell isn’t magic - anyone can Regular expressions work with other tools to filter data
learn it. This Linux Shell special edition provides a and help you find the snippet you really need. We show
comprehensive look at the world inside the terminal you how to match characters with regular expressions.
window.
17 Pipes and Redirection
9 File Learn how to direct the output of one command to
Management another command.
We show you
how to navigate 19 Customizing Bash
directories and Get more productive by customizing the command-line
manage your file environment.
resources.
22 Text Manipulation Tools
12 Search Tools Why slow down for a mouse? You can use some simple
Handy tools like find, locate, and whereis help you chase command-line tools to search, sort, cut, paste, join, and
down files and programs on your system. split your text files to zero in on the information you need.

CONFIGURATION
26 Hardware Configuration 32 Configuring Filesystems
Learn about some tools for You can’t store files without a filesystem. Use these Bash
configuring and managing commands for easy filesystem configuration.
hardware on your Linux
system. 34 mount and fstab
Most Linux distros mount storage media automatically,
30 fdisk, gdisk, and parted but someday you might need a classic command-line tool.
Use these handy disk
partitioning utilities to 36 Time Tools
configure your hard drive These utilities let you set and keep time.
before you install a new operating
system.

4 LINUX SHELL HANDBOOK - 2023 EDITION


HANDBOOK

<9 Al best bash


JU I COMMANDS
MANAGEMENT COMMUNICATION

39 Users, Croups, and Permissions 67 Networking Tools


The shell comes with some simple commands for We show you some Bash utilities for configuring and
managing users and granting access to system troubleshooting networks.
resources.
74 Internet Tools
43 su and sudo The Linux environment provides command-line tools for
Why log in to the root account if you can avoid it? many common Internet tasks, such as checking email,
surfing the web, and even searching on Google.

81 SSH
Manage your server from a distance with this convenient
and secure remote access toolkit.

84 Rsync
Sync your files to stay consistent and avoid data loss.

46 systemd
Systemd has become the standard for starting,
stopping, and managing services in
Linux.
AUTOMATION
54 Managing Processes 86 cron and at
Monitor and manage the Automate and schedule common tasks.
processes running on your
system. 88 Bash Scripting
We show you how to start writing your own Bash
58 Package Management scripts.
Tools
Linux package tools help 93 Images and PDFs
you install and manage software. We show you some Use these picture perfect command-line tools to convert
package tools in Debian and RPM-based systems. and adapt your digital images.

65 dd and mkisofs/genisoimage/xorrisofs
Create backups and bootable CDs with these handy
disk utilities.
96 Bash Command Index

LINUX SHELL HANDBOOK- 2023 EDITION 5


GETTING AROUND Introducing Bash

AT YOUR COMMAND
Beyond all the splash screens, screen savers, and vivid rock-star poses. The option -debugger is also used
to log debugging information.
wallpaper is the simple yet powerful Bash shell. BY BRUCE BYFIELD

Getting Around at the


any desktop users approach the Bash runs non-interactively, reading in­ Prompt

M command line as though armed


with a magic spell. They have a
structions from the .bashprofile file in
your home directory. In many cases,
command - complete with options -commands
type or paste to get the desired results,
to give you the option to create
a file and run it non-interactively.
In the old days, the command prompt
was the primary means of interacting
with Linux, but most contemporary
Linux systems open up in some form
but they are unclear what else might be Most of the time, though, Bash runs as of graphical user interface. To reach
going on. This approach is understand­ an interactive shell, meaning that you the command prompt on a GUI-based
able; however, if you take the time to can enter commands and scripts using Linux system, you’ll need to open a
understand something of the structure the keyboard, and Bash will process terminal window. Systems that use the
of the command line, you can increase your input and display output. You can Gnome desktop environment typically
control over your computing. also fine-tune how Bash runs with a set include the Gnome Terminal applica­
By default, most Linux distributions of options similar to any commands. tion. On Ubuntu, you’ll find the Termi­
run Bash (the Bourne Again Shell). Bash These options can be entered in a termi­ nal application by searching the dash
is a command-line interpreter - a pro­ nal profile or in a script that you run for “Terminal” (Figure 2). KDE-based
gram that runs macros and other utilities. when opening a command line. openSUSE systems, on the other hand,
These macros and utilities are the com­ One of Bash’s most common options include the Konsole terminal program,
mands that you enter at the prompt. They is -r, which places Bash in restrictive which you will find in the Applications
include those built into Bash, such as cd, mode. In restrictive mode, some actions, | System menu. Several other terminal
and many others that are external, includ­ such as using the cd command or chang­ programs are also available for Linux
ing most of the commands that you run. ing environment variables, are disabled. systems. Consult your vendor docu- E
However, from the end user’s perspective, Some administrators place Bash in re­ mentation for more on finding your |
the difference between internal and exter­ strictive mode in the hope of limiting the way to a command prompt.
nal commands is unimportant. damage that rash users can cause on a While in the shell, you can forget □-
Like other shells, Bash can run inter­ network, but, more often, restricted about your mouse, but you can copy £
actively or non-interactively. When act­ shells are used to sandbox - that is, to and paste, as the Edit menu shows. To §
ing as a login shell for your account, run a command in isolation for test pur­ communicate with your system

6 LINUX SHELL HANDBOOK - 2023 EDITION


Introducing Bash GETTING AROUND

The default is to look in the current di­


Tweak Your Bash
rectory, however, you can include a
You can modify how Bash operates by ample, shopt-scdspellenables Bash to path with the source or destination to
using its built-in commands. For instance, correct minor misspellings in its default copy from or to a different directory.
the umask command changes the default directories when you use the cd com­
Of course, you must have the neces­
permissions used when creating a file, mand. Similarly, shopt -s checkjobs lists
whereas the alias command can be used any stopped jobs that remain when you sary permissions to access the direc­
to change the name used to run a specific close the shell. tory. To delete a file, use the rm com­
command-for example, my Debian sys­ These few examples of what you can do mand, and to delete a directory, use
tem comes with Is -color=auto aliased to with Bash should be sufficient to show the rm -r or rmdir command. (Need­
Is, so that directories and different file that Bash is far from the passive recipient less to say, be careful how you use
types are all colored. of your commands. Instead, like the com­ these commands.)
Another way to modify Bash is through mands that it runs, Bash is full of options A summary of these basic commands
the shopt built-in (Figure 1). The shopt and can be customized to suit your needs. appears in Table 1. Each of these com­
command includes a number of interest­ You'll learn more about customizing the mands includes additional options that
ing, if seldom used, possibilities. Forex- Bash environment later in this issue.
you can enter at the command line. As
you will learn later in this article, you
bruce@nanday:-$ shopt -s cdspell
bruce@nandaycd /usr/sahare
can type man or info, followed by the
/usr/share command, for information on syntax
bruce@nanday:/usr/share$ | The tilde character (~) represents the and usage. For example, to learn the var­
Figure 1: shopt is a command built in to Bash home directory, so wherever you are, you ious options for the mkdir command,
that provides many interesting features. can return to your home directory with: you would enter:
Here, the cdspell option automatically cor­
rects errors when you type directory names. $ cd ~ man mkdir

through the keyboard, type a line, then If you start to get lost when you are navi­ In later articles, you will learn about
press Enter. Of course, modern tools gating around in the directory structure, other Bash commands for modifying
like Konsole or the Gnome Terminal you can always enter the pwd command text, managing users, overseeing
are not terminals in the old sense but (print working directory) to display the processes, and troubleshooting net­
are actually terminal emulators. You name of the current directory. works.
can close or minimize the terminal To create a new directory, enter the
window as you would any other win­ mkdir command and give the name of History
dow on your Linux system. the new directory: If you are doing repetitive commands in
This handbook assumes you have Bash, you can save time by using the
some basic knowledge of how to move $ mkdir /home/berney/Music/Beatles history for the current account. Stored
around in the Bash shell. If you are look­ in the bashjzistory file in your home di­
ing for a very basic crash course, a few Or, if user bemey were already in his rectory is a list of commands you have
simple commands will help you get fa­ Music directory, he could just type: run, with the oldest numbered 1. You
miliar with the command prompt. can use the arrow keys to move up and
Most likely, the terminal will open in $ mkdir ./Beatles down or use the plain command history
your home directory. Type Is to list the to see a complete list of what is stored
contents of the directory. You can use the The cp command lets you copy files. The in your history.
cd (change directory) command to move syntax is as follows: If you are somewhat more adventur­
to another directory. You’ll also need to ous, you can use a number of shortcuts
mention the path to the target directory: cp <source_filename> P to run a previous command in the his­
< dest inat ion_f ilename> tory. Inumber runs the command with
$ cd /home/bemey/Music that number. Similarly, !-number sets the
number of previous commands to revert
Bash shells let you use a dot (.) in the to, and Istring runs the first command
path to represent the current directory. that includes that string.
In other words, a user named berney When you are either very certain of
could move from his home directory to what you are doing or willing to live
the Music subdirectory by typing: dangerously, you can enter ^stringl^
string2/'' to repeat the last command but
$ cd ./Music replace the first string of characters with
the second. Another trick is to add :h to
A double dot means “go up one level in remove the last element of the path in
the directory path,” so if berney wanted the command or :t to remove the first el­
to go from /home/bemey/Music back to ement. However, if you are uncertain of
/home/bemey, he could type: Figure 2: Finding the Terminal in Ubuntu. the results, you can add :p to print the

LINUX SHELL HANDBOOK- 2023 EDITION 7


GETTING AROUND Introducing Bash

brucegnandaycd /home/bruce
Table 1: Some Basic bruce@nanday:'$ ''bruce''trish/' Table 2: Man Page Sections
Bash Commands cd /home/trish Section Description
brucegnanday:/home/trish$ !-l:h
Is List contents of the current 1 General commands
directory cd /home
brucegnanday:/home$ | 2 System calls
cd Change directory
Figure 3: You can use several keyboard 3 C library functions
pwd Show current working directory
shortcuts to run commands in the history 4 Special files (usually devices
mkdir Make directory found in /dev) and drivers
with slight changes. Here, the string "bruce"
cp Copyfile(s) 5 File formats and conventions
is replaced with "trish'’ in the first case,
rm Remove file(s) then only the head of the path is preserved 6 Games and screensavers
rmdir Remove directory in the second. 7 Miscellanea
8 System administration com­
mands and daemons
command that you find but not run it press Ctrl+Z followed by Ctrl+C to re­
(Figure 3). turn to the command line.
When you are doing deeper research, ers simply maintain both info and man,
Documentation consider using apropos followed by a focusing on the command structure in
Bash and the individual commands as­ topic to receive a list of all the applicable the man pages and on basic instruction
sociated with it add up to a lot to learn. man pages. The one drawback to apro­ in the info pages. Still, it can never hurt
Fortunately, you don’t have to remember pos is that, unless you are very specific, to check both in the hope of finding the
everything. Like other Unix-type sys­ you could get dozens of pages, only a most complete information.
tems, GNU/Linux includes a number of few of which are relevant to you.
different help systems. By contrast, if all you need is a brief Digging Deeper
The most basic form of help is the snippet of information, use whatis fol­ As experts will be quick to note, these
man page (Figure 4). Man pages are di­ lowed by the command. For example, if comments provide only the barest out­
vided into eight sections (see Table 2), you enter whatis fdisk, you receive the line of subjects that have filled entire
but most of the time, you only need to line fdisk (8) - Partition table manipula­ books. Read on for more about working
type the command man followed by the tor for Linux. The (8) refers to the man in the Bash shell. For additional informa­
command, file, or concept about which section where detailed information is tion, a good place to start is the man
you want information. available. Similarly, if you need to iden­ pages. Another important reference is
However, some topics have entries in tify a file type, use type then the file. the online Bash Reference Manual [1].
several sections. To go to the specific For several decades, man pages have Read this material with a Bash shell
section, place the number of the section been the standard help form. However, open next to the text, so that you can try
between the man command and the more than a decade ago, the GNU Proj­ commands as you learn about them. ■
topic. Thus, man man takes you to the ect made info its official help format.
basic page about the man command in But, instead of replacing man, info has INFO
section 1, but man 7 man takes you to a simply become an alternative (Figure 5).
[1] Bash Reference Manual:
section about the collection of macros Although some man pages today stress
http://www.gnu. org/software/bash/
used to create man pages. Either way, that the full help file is only available
man ual/bashref.html
when you are finished reading, you can through info, in practice, many develop-

L5(l)

(UPTIOWJ ... ItUSJ...

ESCRIPIIOM
List information about the FILES (the current directory by default).

Mandatory arguments to long options ar

with -I, print the author of each filo

--block-size=SIZE
use SIZE-byte blocks

-B, --ignore-backups
do not list implied entries ending with -

Figure 4: The man page for the Is command. Figure 5: The info page for the Is command.

8 LINUX SHELL HANDBOOK - 2023 EDITION


File Management GETTING AROUND

create the directories immediately above


it by adding the -p (parent) option.
To delete, use rm (remove) for files
and directories and rmdir for directories.
Don’t forget that, unlike the desktop, the
Bash shell has no Trash folder. The clos­
est you can get is to create a special
folder and move files to it instead of
using rm or rmdir.
By default, rm works only on files. To
Learning file management commands delete directories with it, you have to
use the -r option. As you might imagine,

k
FILE POWER i'H
We give you an overview of commands for moving, editing,
II
rm -r can remove key system files when
used thoughtlessly; thus, some users
prefer to add -preserve-root when run­
ning the command anywhere near the
root directory. In comparison, rmdir is a
compressing, and generally manipulating files. BY BRUCE BYFIELD much safer option, because it works
only on empty directories (Figure 4).
A completely different approach to file
NU/Linux treats everything as a owner or timestamp, or -no-preserve management is taken by dd, an old Unix

G file. For this reason, learning file


management commands should
= mode to have them changed in the
files’ new location. Whether or not you
be among your first priorities. These preserve attributes is especially important
commands are easy to remember be­ when you are logged in as root and mov­
utility that copies bytes or blocks rather
than files. Used mainly by administra­
tors, dd has a non-standard syntax.
Briefly, dd can be used for such tasks as
cause their names are usually abbrevia­ ing around files owned by another user - creating an ISO image from a CD/DVD,
tions of their actions - for example, mv say, for a backup of the /home directory. wiping a disk by filling it with random
for move and Is for list - but their op­ Sometimes, you might not want to data, and duplicating a partition or mas­
tions can take time to learn. waste hard drive space on multiple cop­ ter boot record. Just remember to con­
Basically, file management commands ies of the same file, in which case you struct your dd command carefully and
fall into three categories: directory and might prefer to use In -s file link to create double-check it. Even more than rm, the
file movement, navigation and editing, a symbolic link, or pointer, to the origi­ dd command can be hazardous to your
and compression. Commands in all three nal file, which takes up much less space system if you are inattentive. For more
categories are typically more powerful (Figure 2). Later, if you copy these sym­ information on dd, see the “dd and gen-
(and potentially more dangerous) than bolic links to a backup, you can use cp isoimage” chapter.
their desktop equivalents, thanks mainly -L to ensure that the original file, not the
to file globbing, or the use of standard link, is used. Navigating and Editing
patterns to refer to multiple files. Alternatively, you might prefer to Directories and Files
move a file with mv, which takes many You probably already know that you
Moving and Editing of the same options as cp. Also, you can move around the directory tree with the
Directories and Files use mv to rename a file, giving it the command cd < directory > - a command
The most basic command for moving di­ same directory path but a different final so simple that it has no options. You
rectories and files is cp. Its structure is name (Figure 3). For example, to change might not know, however, that cd has
simple: cp < options > < filesourcefile > the name of the file garden.png while several shortcuts: cd.. moves to the di­
< target >. By default, cp overwrites any keeping it in the same directory, you rectory immediately above the current
files of the same name in the target di­ could use mv ,/garden.png ./sun-yat-sen- one; cd - returns you to the previous di­
rectory, but you can be cautious and use gardens.png. rectory; and cd ~ returns you to your
the -b option to back up any files that are As you copy or move files, you might home directory (Figure 5). Combined
overwritten or the -u option to overwrite want to create a new directory with with the command history in a virtual
only files that are newer than the ones in mkdir. Although this is a relatively terminal, these shortcuts are enough to
the target directory (Figure 1). straightforward command, you can fine­ give you the equivalent of the back and
Also, you can add -preserve = mode to tune it with -mode = octal-permissions to forward buttons in a web browser.
choose to preserve file attributes, such as set permissions for the new directory or Once you are in a directory, use Is to
view the contents. In many distributions,
nanday:-# cp -u --preserve=owner /home/bruce/*.odt /media/disk/| you will find that Is is actually an alias of
Is -color, which displays different types
Figure 1: The cp command allows you to be both cautious and flexible. Here, the root user of files in different colors. Sometimes, it
ensures that files with the same name as those being copied are not overwritten and that the is an alias of Is -color -classify, which
owner of the files does not change. adds the use of symbols such as / to in-

LINUX SHELL HANDBOOK- 2023 EDITION 9


GETTING AROUND File Management

four commands for compression: the


bruce@nandayIn -s ./screenshotl.pngj./webpage/images/
original tar, gzip, bzip2, and - more
Figure 2: Creating a symbolic link with In is a space-saving way of having the same file in two rarely - cpio.
places at the same time. When you exchange files with users
of other operating systems, use gzip so
bruce@nandaymv ./garden.png ./sun-yat-sen-gardens.png they can open the archive. Gzip’s basic
use is straightforward, with a list of
Figure 3: The mv command does double-duty, both moving files and renaming them. files following the command, but you
can use a variety of options to control
bruce@nandayrmdir ./download what happens.
rmdir: failed to remove './download': Directory not empty To set the amount of compression,
you can use the parameter -best
Figure 4: The rmdir command is much safer to use than rm -r, because it can't delete directo­ < number >, or to set the speed of com­
ries that still have files in them. pression, you can use -fastest < num­
ber >. Both are measured on a scale of
1 to 9. Note that you need to use the -N
option to preserve the original files;
otherwise, they will be deleted when
the archive is created.
To work with files in a gzip archive,
you can use several utilities:
• zcat displays files in a gzip archive.
• zcmp compares files in a gzip archive.
• zdiff lists differences between files in a
gzip archive.
• zgrep, zegrep, and zfgrep search for
text patterns in gzip-archived files.
One especially useful utility is gurtzip,
which amounts to an alias for gzip be­
cause it uses most of the same options.
But, if you can’t be bothered learning
dicate a directory or * to indicate an exe­ view the contents of compressed files another command, you can simply use
cutable file (Figure 6). (more on this later). the command gzip -d.
For many users, these options are Yet another tool for tracking down files By contrast, the bzip2 command pro­
more than enough. However, sooner or is find. The find command takes so duces archives that are 10 to 20 percent
later, you will likely need the -a option, many options that I list only some of the smaller than those produced by gunzip.
which displays hidden files - those most important ones in Table 1. But, although bzip2 and gzip serve simi­
whose names start with a period. To pin­ When you have located a file, you can lar purposes, bzip’s options are consider­
point a file, you might use -I to display use the touch, command to edit its time­ ably different. For one thing, you have to
file attributes. To help sort files with Is, stamps. For example, the command specify sub-directories, because bzip2
various options let you sort by size (-s), lacks an -r option. For another, you use
time (-t), or extension (-X). touch -a grocery list.txt 1(110311200.00 the -z option to compress files and -d to
All this information can easily occupy decompress. To keep the original files
more lines than your terminal window would change the access time to noon after the archive is created, use the -k
displays, so you might want to pipe the on October 31, 2014, and you can use option.
command through less (Is | less) so that the same date format after -m to change Like gzip, bzip2 has some related utili­
only one screenful of information is visi­ the last modification time. Similarly, ties for working with its archives:
ble at a time. If you are trying to identify -t= < YYMMDD.ss > changes the date
a file, file is a supplement to Is, identify­ and the time that the file was created. bruce(8nanday:-/download$ Is
ing the type of file (Figure 7). If you have Also note that the time starts with the
symbolic links, you can add the -L op­ last two digits of the year and ends with
tion so that you can identify the type of the seconds.
the original file. Also, you can use -z to
Compressing and Archiving
bruce@nanday:-/download$ cd .. Compression is less essential now than it F12-Alpha -1685 - Live.iso
bruce@nanday| Fedo ra-11-i685- Live.iso
was in the days of lOOMB hard drives,
Figure 5: cd command shortcuts require one but it continues to be important for cre­ Figure 6: Many distributions create an alias
or two characters - far fewer than when typing ating backups or sending files as email for Is, so it automatically displays different
the names of most directories in your home. attachments. The Bash shell includes file types with different colors.

10 LINUX SHELL HANDBOOK - 2023 EDITION


File Management GETTING AROUND

• bzipcat displays the contents of a file tives as the ability to archive an entire di­ pride themselves on their ability to con­
in an archive, with the same options rectory tree and create archives in multi­ struct elaborate and elegant globs.
as the cat command. ple formats (of which TAR is the only one But what if you want to work with a
• bziprecover helps recover damaged ar­ that is widely used), as well as numerous metacharacter? Then you put a back­
chived files. options to view and edit already-archived slash (\) in front of it. For instance, \\ in­
• bunzip2 decompresses files. files. However, unless you are a system dicates that you are looking for a back­
The differences between gzip and bzip2 administrator or an old Unix hand, slash, not a directory. The backslash is
can be hard to remember, so many users chances are you will rarely see cpio used. known as an escape character, and it sig­
prefer to rely on the tar command. The nals that the command should read what
tar command not only has the advantage Extending File follows literally, instead of as a glob.
of having options to use gzip and gunzip Management with Globbing Globs can be especially useful when
(-z) or bzip2 (-;), but it also offers far One reason shell commands are so pow­ you want a selected list from a directory
more control over exactly how you com­ erful is that they can work with multiple full of files or when you are using one of
press files. files. With many commands, the easiest the grep commands to find content in­
In fact, tar's options run into the doz­ way to work with multiple files by enter­ side a file. However, you must be careful
ens - too many to detail here. For exam­ ing a space-delimited list directly after about using globs with commands like
ple, you can use -exclude < file > to ex­ the command. However, the most con­ rm or mv that change or rearrange the
clude a file and -p to preserve the per­ cise and efficient way to handle multiple content of your hard drive. Otherwise, a
missions of a file. If you want to preserve files is through file globbing. command can have disastrous conse­
a directory structure, use -p. To be safe File globbing refers to the use of quences. To be safe, consider using a
when decompressing, use -k to prevent regular expressions (often abbreviated newly constructed glob with the innocu­
any accidental overwriting of files. to regex), pattern matching, metacha­ ous Is command, so you can see what
The tar command also includes its racters, or wildcards. The terms are files it might affect.
own built-in utilities in many cases. To not quite synonymous, although they
add one archive to another, use the are mostly used as if they were. What­ Learning that Pays
format ever term you use, it refers to a string File management commands have a long
of characters that can stand for many history in Bash. During the course of
tar --append <tarfilel> <tarfile2> different strings. their development, they have accumu­
The most widely used glob in the Bash lated options the way ships accumulate
To update an archive with newer versions shell is the asterisk (*), which stands for barnacles - constantly and apparently
of files with the same name, use the -u any number of unknown characters. haphazardly.
option, or to compare the files in an ar­ This glob is especially useful when you However, often, the options are sim­
chive with other files, use the format: want to find files that share the same ex­ pler than they first appear. For example,
tension. For instance, the command Is you can be fairly certain that most file
tar --compares <tarfile files> *.png lists all the PNG graphics in the management commands will use -r to in­
current directory. clude sub-directories and their contents
The fourth compression command, cpio, By contrast, a question mark (?) and -v to print a detailed description of
has fallen out of favor in recent years, stands for any single character. If you what they are doing to the terminal.
probably because its format is non-stan­ enter the command Is ca?.png, the list of Similarly, to force a command to work,
dard. For example, to create an archive matches will include the files cat.png regardless of consequences, you gener­
with cpio, you have to pipe Is through it and cab.png but not the file card.png, ally use -f. Adding the -i option, how­
and specify the file for output: which contains two characters instead of ever, means that every action needs to
one after the ca. be confirmed by you before it happens.
Is | cpio -o > <outputfile.cpio> From these simple beginnings, globs Even with such hints, these commands
can quickly become more elaborate. To can take a long time to master.
That said, cpio has even more options specify specific characters, you can use In fact, for basic actions, they might
than tar, including such powerful alterna­ square brackets, so that test[12].png lo­ offer little more than a graphical file
cates files test1.png and manager can. But, if you try to do some­
bruce@nanday:~$ file ./visits.odt test2.png, but not test3.png thing more intricate - such as specifying
./visits.odt: OpenDocument Text (Figure 8). Also, you can how symbolic links are going to be
Figure 7: The file command identifies the format of files, specify a search for a regex at treated or excluding a file from an ar­
helping you identify them. the start (A) or the end ($) of chive - the file management tools easily
a line. Similarly, you can outclass their desktop equivalents. If you
magazine@MacBuntu:~$ find ./test[12].png search at the start of a word learn some of the less straightforward
./testl.png with \< or the end of a word options for these commands, you’ll soon
./test2.png with \> - and these are sim­ understand why many experts prefer to
magazine@MacBuntu:-$ |
ply a few common possibili­ use the command line for file manage­
Figure 8: A few regular expressions increase the flexibil­ ties. Using globs is an art ment over anything that the desktop has
ity of commands. Here, they greatly simplify finding files. form, and experts rightly to offer. ■

LINUX SHELL HANDBOOK- 2023 EDITION 11


GETTING AROUND Search Tools

T O

rinaing rues ana searcning ror texi Mil


FINRFRC KFFPEI
With Linux, you can keep track of your files using a variety of
tools; we examine some of the most useful utilities. We also
show you how to search for text patterns in files using grep.
BY DMITRI POPOV AND JOE CASAD

hen it comes to finding and /home, and /tmp directories to look for owner. For example, if you want to find

W identifying files on your


system, you are spoiled for
all .bin files:

choice. Linux offers a variety of tools


that can help you locate files and pro­
find /usr /home /tmp -name "*.bin"
all files owned by root, you can use the
following command:

find . -user root


grams, including find, locate, whereis, If you don’t have the appropriate per­
and which.. These tools are not particu­ missions to search in the system direc­ In a similar manner, you can use find to
larly difficult in use, and mastering them tories, find will display error messages. search for files owned by a specific group:
can help you use your Linux system To avoid cluttering up the search re­
more efficiently. sults, you can send all error messages find . -group www
to the null file (i.e., discard them):
Finding Files with find The -type option is useful for specifying
The find tool lets you search for files by find /usr /home /tmp P the type of object to search for, such as
name or a part of the name. By default, -name "*.bin" 2>/dev/null f (regular file), d (directory), I (symbolic
find searches recursively, meaning it link), and a few others. Do you want to
looks for files through the entire direc­ The find tool also supports the AND, find the directory of photos from Berlin?
tory tree. At the very minimum, find re­ OR, and NOT Boolean operators, which Here is the command for that:
quires two options: a path to the direc­ let you construct complex search strings.
tory where the search should start and For example, you can use the -size pa­ find berlin/ -type d
the name of the file to look for. The rameter to limit the search to files that
name of the file is specified with the are larger than the specified limit: The find tool also offers several options
-name switch. For example, the follow­ that can be used to find files by time,
ing command will search for files whose find /photos P including -mmin (last modified time in
names start with Lin in the foo directory -iname "*.NEF" -and -size +7M minutes), -amin (last accessed time in
and its subdirectories: minutes), -mtime (last modified time in
The command line above searches for .NEF hours), and -atime (last accessed time
find /home/foo -name "Lin*" files (Nikon raw files) that are larger than in hours). So, if you want to find photos
7MB. In a similar manner, you can use the that were modified 10 minutes ago, you
As shown in this example, you can use I (NOT) operator to find files that are larger can use the following command:
wildcards in the search string to broaden than 7MB but are not .NEF photos:
the search. Because the find command find /photos -mmin -10 -name "*.NEF"
is case sensitive, the previous command find /downloads -size +7M ! P
line initiates a search for all file names -iname "*.NEF" The -exec option is another rather useful
that start with Lin, but not those that option that allows you to execute a com­
begin with Un. However, you can in­ The OR operator also can come in handy mand on every search. For example, the
struct find to ignore case with the use when you need to find files that match following command searches for *.NEF
of the -iname switch: either of the specified criteria: files in the photos directory and renames
the found file with the exiv2 tool:
Photo by Nadjib BR

find /home/user -iname "Lin*" find /downloads -size +7M P


-or -iname "*.NEF" find /photos -iname "*NEF" P
The find command lets you specify mul­ -exec exiv2 mv P
tiple starting directories. The following Instead of searching for files by name, -r "%Y%m%d-%H%M%S" P
command will search through the /usr, you can use find to search for files by *.NEF {} \;

12 LINUX SHELL HANDBOOK - 2023 EDITION


Search Tools GETTING AROUND

Note the {} \; at the end of the com­ time. Just execute the updatedb com­ In its most basic form, grep searches a
mand. The {} symbol is a placeholder mand as root to force the system to up­ file for text matching a specified pattern
for the name of the file that has been date the database. and outputs every line of the file that
found, whereas \; indicates the end of contains the string.
the command. Instead of -exec, you can whereis and which The syntax for the grep command is:
also use the -ok option, which asks you If you need to find the path to an execut­
for confirmation before the command is able program, its sources, and man grep [options] pattern file_name(s)
executed. pages, the whereis tool can help. The fol­
Finally, you can use the -fprint option lowing command, for example, returns You can specify the search pattern ex­
paths to binary, source, and man pages plicitly or use a regular expression. (See
find /home/user -name "Lin*" P for the Rawstudio application: the article elsewhere in this issue on reg­
-fprint search_results.txt ular expressions.)
whereis rawstudio Several options help to refine the
to print the search results to a text file. search (see Table 1 for some exam­
Using the available options, you can ples). For example, if you don’t want
Searching for Files with limit your search to specific types. To to output all the lines that match the
locate and updatedb search only binaries, you can use the -b search string but only want to know
Similar to find, the locate tool lets you option, or use -m to search for man the number of matching lines, use the
find files by their names. But instead of pages and -s to search for source files. -c option.
searching the system in real time, locate Whereas the whereis tool lets you lo­ To specify more than one pattern, use
searches the database of file names, cate program files and man pages, which the -e option once for each pattern:
which is updated daily. The key advan­ tells you which version of a command
tage of this approach is speed; finding will run if you just type its name in the grep -e patternl -e patterns P
files with locate is much faster than terminal. For example, the which soffice filename.txt
with find. The use of locate is easy: Just command returns the /usr/bin/soffice
run the locate command with the name path. This means that the soffice com­ Alternatively, you can use the -f option
of the file you want to find: mand runs the application in the /usr/bin to specify a pattern file that can contain
directory. If you want to find all the lo­ multiple patterns.
locate backup.sh cations of the command, you can use Although most modern text editors
the -a option: and word processors have built-in
To ignore the case, you can use the -i search features, grep is still very useful
option: which -a soffice for searching across a group of several
files or for expressing complex search
locate -i backup With just these few, simple commands, you patterns that would be cumbersome in
can locate your files quickly and easily. a GUI tool. System administrators often
As with find, you can use wildcards in use grep to hunt for errors, warnings,
your searches: grep devices names, and other information
The Bash command shell also has tools in system logs. See the following arti­
locate "*.jpg" that will let you search for a text string cles on “Regular Expressions” and
inside of a file. The most popular com­ “Pipes and Redirection” for more grep
If you want to see only a limited num­ mand for finding a search string is grep. examples. ■
ber of results, you can do so by using
the -n option followed by the number Table 1: Examples of grep Options
of your choice: Option Description

-c Prints only a number representing the number of lines matching the pattern
locate "*.jpg" -n 5
-e Specifies an expression as a search pattern (you can specify multiple
expressions in one command - use the -e option with each expression)
As mentioned before, locate performs
-E Use extended regular expressions (ERE)
searches by querying the database of
-ffile_name Take patterns from a pattern file
file names, which is automatically up­
dated every day, so if you have just -i Ignore case
downloaded a batch of photos from -/ Prints a list of file names containing the search string
your camera, the locate command -o Only prints matched parts of matching line
won’t see them until the database is -v Prints all the lines that do NOT match the search pattern
updated. -w Match a whole word
Fortunately, you don’t have to wait
-A n Prints the matched line and n lines after the matched line
until the system updates the database;
-Bn Prints the matched line and n lines before the matched line
with the updatedb command, you can
manually update the database at any -Cn Prints the matched line with n lines before and n lines after

LINUX SHELL HANDBOOK- 2023 EDITION 13


GETTING AROUND Regular Expressions

Regular expressions help you filter through the data to find the information you need. BY MARTIN STREICHER

ost computer systems have an library, or PCRE. You will find the PCRE lowed by an n. The letters must appear

M assortment of tools for filtering


and processing data. A virus
in Perl, Apache, Ruby, PHP, and many
other languages and tools.
scanner, a spam fighter, a web search
engine, a spell checker - each is a filter Introducing Regular
together and in that order with no inter­
vening characters, but otherwise, they
can appear anywhere on the line, even
embedded in a larger word. Catwoman,
that sifts though data to isolate the infor­ Expressions Batman, Spider-Man, and Ant-Man, and
mation you really need. Your shell pro­ To understand the purpose of a regular the others each contain the string man.
vides a filter, too. For example, Is *.jpg expression, consider a situation in which (The i option told the grep command to
lists only JPEG images. you need to find all the words in a file ignore letter case.)
Because so much of Linux depends on that contain a predefined string of charac­ Grep also has a nice feature to exclude
interpreting and processing plain text ters. One common tool for this task is the rather than include all matches found.
files, an entire shorthand exists for creat­ Linux grep utility, which scans input line The -v option omits lines that match a
ing filters. The shorthand is called regular by line looking for a string. specified pattern. For example,
expressions, or regex. A regex applied to In its simplest operation, grep readily
text can find, dissect, and extract virtually finds a given word and prints the lines grep -v -i spider heroes.txt
any pattern you seek. Table 1 shows some that contain the word. Suppose you have
common regex operators, which you can a file called heroes.txt that lists the prints every line except those that con­
string together and use in combination to names of familiar caped crusaders (List­ tain the string “spider.” Batgirl and
build arbitrarily complex filters. ing 1), and you want to find all the Batman are valid matches (among oth­
The origin of regex dates back some names that contain man. The command ers) ; Spider-Man and Spider-Woman
60 years to research in theoretical com­ are invalid.
puter science, a branch of study that in­ $ grep -i man heroes.txt What if you only want names of su­
cludes the design and analysis of algo­ perheroes that begin with Bat or with
rithms and the semantics of program­ would output the following results: any of bat, Bat, cat, or Cat? Or perhaps
ming languages. The earliest progenitor you want to find how many avenger
described models of computation in a Catwoman names end with man. In these cases, a
shorthand notation called a “regular ex­ Batman simple string search doesn’t suffice; you
pression. ” The shorthand was first co- Spider-Man need to seek matches on the basis of =
opted for use in the QED editor found in Wonder Woman content and position.
the original Unix operating system, but it Ant-Man A regex can specify position - such as *
Photo by Mikkel

has since expanded into a POSIX stan­ Spider-Woman the start or end of a line, or the begin­
dard for pattern matching. Today, the ning and end of a word. A regex can also
most popular implementation of regex is Here, grep scans each line in the file, describe alternates (i.e., occurrences of
the Perl-Compatible Regular Expressions looking for an m, followed by an a, fol­ this or that pattern); fixed, variable, or

14 LINUX SHELL HANDBOOK - 2023 EDITION


Regular Expressions GETTING AROUND

indefinite repetition (zero, one, two, or each regex on the command line with grep -i -E ,A(bat|cat)' heroes.txt
more of any stretch); ranges (e.g., any of single quotes to protect the regex opera­
the letters between a and m, inclusive); tors from interpretation by the shell. For The second approach uses the set opera­
and classes (kinds of) characters (e.g., example, both * and $ are regex opera­ tor ([ J). If you place a list of characters
printable characters or punctuation). tors, but they also have special meaning in a set, any of those characters can
In the rest of this article, I explore to the shell. The shell’s asterisk is differ­ match. (Think of a set as shorthand for
some examples of regular expressions ent from its facsimile regex operator: It alternation of characters.) For example,
that work with grep. Many other Unix matches any portion of a file name. The
tools, including interactive editors Vi regex * is a qualifier, matching zero or grep -E ,A[bcBC]at' heroes.txt
and Emacs, stream editors sed and awk, more operands. The dollar sign indicates grep -E 'A(bat|Bat|cat|Cat)1 heroes.txt
and all modern programming languages a variable in the shell but marks the end
also support regex operations. of a line or string in a regular expression. both produce the same results. To sim­
For more information on regex theory To find names that end with man, you plify again, you can ignore case with -i
and practice, see the Perl man pages (or might use the regex man$ to match the to reduce the regex to /'[bc]at.
see perl.org [1]) and books by Jeffrey sequence m, a, and n, followed immedi­ To specify an inclusive range of char­
Friedl [2] and Nathan Good [3]. ately by the end of the line or string ($). acters in a set, use the hyphen (-) opera­
Given the purpose of A and $, you can tor. For example, usernames typically
Match a Position find a blank line with A$ - essentially, begin with a letter. To validate one in a
To find names that begin with Bat, use: this regex specifies a line that ends im­ web form submitted to your server, you
mediately after it begins. might use ^[A-Za-z]. This regex reads:
grep -E 'ABat' To find words that begin with bat, Bat, “Find the start of a string, followed im­
cat, or Cat, you can use one of two tech­ mediately by any uppercase letter (A-Z)
The option -E specifies a regular expres­ niques. The first is alternation, which or any lowercase letter (a-z).” By the
sion. The A (caret) character matches the yields a match if any of the patterns way, [A-z] is the same as [A-Za-z].
beginning of a line or a string - an imag­ match. For example, the command You can mix ranges and individual
inary character that appears before the characters in a set. The regex [A-MXYZ]
first character of each line or string. The grep -E 1A(bat|Bat|cat|Cat)' heroes.txt matches any of uppercase A through M,
letters B, a, and t are literals and only X, Y, and Z. If you want the inverse of a
match those characters. Filtering the does the trick. The vertical bar regex op­ set - that is, any character except what’s
contents of heroes.txt, the command erator (|) specifies alternation, so this\ in the set - use the special set [A ] and
that matches either the string this or the include the range or characters to ex­
grep -E 'Abat' heroes.txt string that. Hence ^(bat\Bat\cat\Cat) clude. To find all superheroes with at in
specifies the beginning of a line, fol­ the name, excluding Batman, type:
produces Batman and Batgirl. lowed immediately by one of bat, Bat,
Many regex operators are also used by cat, or Cat. Of course, you could simplify grep -i -E '[Ab]at' heroes.txt
the shell (some with different seman­ the regex with grep -i, which ignores
tics), so it’s a good habit to surround case, reducing the command to: The command produces Catwoman and
Black Cat.
Table 1: Common Regular Expression Operators Certain sets are required so
Operator Purpose frequently that they are repre­
. (period) Match any single character. sented with a shorthand nota­
A Match the empty string that occurs at the beginning of a line or string. tion. For instance, the set
$ Match the empty string that occurs at the end of a line. [A-zO-9_J is so common, it can
A Match an uppercase letter A. be abbreviated \w. Likewise,
a Match a lowercase a.
\d Match any single digit. Listing 1: heroes.txt
\D Match any single non-digit character. $ cat heroes.txt
Iw Match any single alphanumeric character; a synonym is [:alnum:]. Catwoman
[A-E] Match any of uppercase A, B, C, D, or E. Batman

lAA-E] Match any character except uppercase A, B, C, D, or E. Here, the caret P) inverts the The Tick
range operator to exclude any of the characters that appear in the range. Spider-Man
X? Match no or one capital letter X. Black Cat
X* Match zero or more capital Xs. Batgirl

x+ Match one or more capital Xs. Danger Girl


Wonder Woman
X{n} Match exactly n capital Xs.
Luke Cage
X{n,m} Match at least n and no more than m capital Xs. If you omit m, the expression tries to
match at least n Xs. Ant-Man
Spider-Woman
(abcldef)+ Match a string that contains one or more occurrences of the substring abc or the sub­
string def. abc and defwould match, as would abcdef and abcabcdefabc. Blackbolt

LINUX SHELL HANDBOOK- 2023 EDITION 15


GETTING AROUND Regular Expressions

the operator \IV is a convenience for the no or 1,1 or more, and 0 or more re­ perl -n -e '/AThe\s+(.*)$/P
set [AA-zO-9_]. Also, you can use the no­ peats, respectively (e.g., ?is shorthand print heroes.txt
tation [:alnum:] instead of \w and for {0,1}). The regex boys? matches
[A[:alnum:]] for \W. boy or boys. The regex Goo?gle matches the result should be Tick. The perl -e lets
Gogle or Google. The regex Goo+gle you run a Perl program right from the
Repetition, Repetition matches Google, Gooogle, Goooogle, and command line, perl -n runs the program
So far, I've shown literal, positional, and so on. The construct Goo*gle matches once on every line of the file. The regex
two kinds of alternation operators. With Gogle, Google, Gooogle, and on and on. portion of the command, the text be­
these operators alone, you can match al­ • Repetition modifiers can be applied to tween the slashes, says: “Match the liter­
most any pattern of a predictable length. individual literals, as shown immedi­ als at the beginning of the string, then
For example, you could ensure a user­ ately above, and can also be applied to ‘T’, ‘h’, ‘e’, followed by one or more
name started with a letter and was fol­ other, more complex combinations. white space character(s), \s + ; then cap­
lowed by exactly seven letters or num­ Use the parentheses just as you do in ture every character to the end of the
bers with the regex [a-z][a-zO-9] [a-zO-9] mathematics to apply a modifier to a string. ” The rest of the Perl program
[a-zO-9][a-zO-9][a-zO-9][a-zO-9] [a-zO-9], subexpression. prints what was captured.
but that approach is a little unwieldy. Consider the file test.txt containing lines Individual Perl captures are placed in
Moreover, it only matches usernames of with typos: special Perl variables named $1, $2, and
exactly eight characters. so on, one variable per capture de­
A regular expression can also include The rain in Spain falls mainly scribed in the regex. Each nested set of
repetition operators. A repetition opera­ on the the plain. parentheses, counting from the left, is
tor specifies amounts, such as none, 1, placed in the next special, numerical
or more; 1 or more; 0 or one; 5 to 10; It was the best of of times; variable. Consider the following,
and exactly 3. A repetition modifier must it was the worst of times.
be combined with other patterns; the $ perl -n -e '/A(\w+)-(\w+)$/T
modifier has no meaning by itself. As an Entering the following command, print "$1 $2\n"'
example, the regex A[A-z] [A-zO-9] {2,7}$
implements the username filter desired grep -i -E '(\b(of|the)\ ){2,}' test.txt which yields: Spider Man, Ant Man, Spi­
earlier: A username is a string beginning der Woman:
with a letter, followed by at least two but produces on the the plain. It was the best Capturing text of interest just scratches
not more than seven letters or numbers of of times;. The regex operator \b the surface. Once you can pinpoint ma­
followed by the end of the string. matches a word boundary, or (\W\iv| terial, you can surgically replace it with
The location anchors are essential \iv\W). The regex reads: “A sequence of other material.
here. Without the two positional opera­ whole words ‘the’ or ‘of’, followed by a
tors, a username of arbitrary length space.” You might be asking why the Express Yourself
would erroneously be accepted. Why? space is necessary: \b is the empty string Regular expressions are extremely power­
Consider the regex A[A-z][A-zO-9] {2,7}. at the beginning or end of a word. You ful. Virtually every Linux command that
It asks the question: “Does the string have to include the character(s) between processes text supports them in one form
begin with a letter, followed by two to the words; otherwise, the regex fails to or another. Most shell command syntax
seven letters?” But it makes no mention find a match. also expands regular expressions to
of a terminating condition. Thus, the match file names, although the operators
string samuelclemens fits the criteria, but Capture the Needle might function differently from shell to
is obviously too long to be valid. If your Finding text is a common problem, but shell. For example, Is [a-c] finds the files
match must be a specific length, don’t more often than not, you want to extract a, b, and c; Is [a-c] * finds all file names
forget to include delimiters for the begin­ a particular snippet of text once it’s that begin with a, b, or c. Here, the * does
ning and end of the desired pattern. found. In other words, you want to keep not modify [a-c] as in grep; rather, * is in­
Following are some other samples: the needle and discard the haystack. terpreted as. *. The ? operator works in
• {2,} finds two or more repeats. The A regular expression extracts informa­ the shell, too, but matches any single
regex AG[o] {2,}gle matches Google, tion via capture. To isolate the text you character. Check the docs for your favor­
Gooogle, Goooogle, and so on. want, surround the pattern with paren­ ite utility to see what is supported. ■
• Repetition modifiers ?, +, and * find theses. Indeed, you already used paren­
theses to collect terms because parenthe­ INFO
Locales ses capture automatically (unless they
[1] Perl documentation:
Iw (and its synonym [:alnum:]) are locale are disabled).
http://perldoc.perl. org/
specific, whereas [A-z0-9_]is literally the To see a capture, I’ll switch to Perl
{grep does not support capture because [2] Fried I, Jeffrey. Mastering Regular
letters A to z, the digits 0 to 9, and the
Expressions. Apress, 2004
underscore. If you're developing inter­ its purpose is to print lines containing a
national applications, use the locale­ pattern). grep’s regex operators are a [3] Goog, Nath a n. Regular Expression
specific forms to make your code porta­ small subset of what Perl has to offer. If Recipes, 2nd ed. O'Reilly Media,
ble among many locales. 2006
you type this command,

16 LINUX SHELL HANDBOOK - 2023 EDITION


Pipes and Redirection GETTING AROUND

PIPE TIME
Special tools in the shell help you combine commands to create
impromptu applications. BY MARTIN STREICHER

he Linux command line provides commands with many pipes. For example, the file does not exist, it is created; if

T hundreds of small utilities to read,


write, parse, and analyze data.

combine those utilities into innumerable


if you want to count the number of words
Groucho speaks, you can append the
clause | wc -w to the previous command.
With just a few extra keystrokes, you can
The pipe is just one form of redirec­
the file exists, its contents are over­
written with the results.
• > > output_file is similar to > but ap­
pends stdout to the named file. If the file
impromptu applications. For example, tion. Redirection tools can change the does not exist, it is created; however, if
imagine you must extract an actor’s lines. source or the destination of a process’s the file exists, its contents are preserved
That is to say, given the text shown in List­ data. The shell offers other forms of redi­ and amended with the results.
ing 1, you must produce That's what they rection, too, and learning how to apply • > & output_file works like >, but it
call a sanity clause for Groucho. The grep these tools is key to mastering the shell. captures stdout and stderr in the spec­
command can find substrings, strings, and ified file, creating the file if necessary,
patterns in a text file. You can use grep to Data In, Data Out and overwriting the contents if it pre­
find all lines that begin with GROUCHO. If you run grep by itself, it reads data from viously existed.
Then you can use cut to divide the match­ the standard input device (stdin) and A few examples are shown in Listing 2.
ing lines into pieces and combine the two emits results to the standard output device In Listing 2, the first command
commands with a pipe (|): (stdout). Errors are sent to a third channel should look familiar. The addition of
called the standard error device (stderr). > groucho.txt saves the output of the
$ grep -i -E ,AGroucho' marx.txt | 7 Typically, the data for stdin is provided command-line to the file groucho.txt.
cut -d 1:' -f 2 by you via the keyboard, and by default, The second command appends the
That's what they call a sanity clause. both stdout and stderr are sent to the ter­ string I started work on Nov 2 at 9 am. to
minal connected to your shell. However, the file timecard. txt. The third command
The grep clause searches the file marx.txt you can redirect any or all of those con­ runs the Ruby script myapp.rb. Input is
for all occurrences of “Groucho” that ap­ duits. For instance, you can redirect stdin taken from the file named data and the
pear at the beginning of a line (-E 'AGrou- to read data from a file instead of the key­ stdout and stderr are captured in log.
cho'), ignoring differences in case (-i). board. You can also redirect stdout and
The cut clause separates the line into stderr (separately) to write data some­ Advanced Use of Pipes
fields delimited by a colon (-d ’:') and se­ where other than the terminal window. Consider the following command-line
lects the second field (-f 2). The pipe op­ As shown previously, you can also redi­ combination:
erator turns the output of the grep clause rect the stdout of one command to become
into the input of the cut clause. the stdin of a subsequent command. $ find /path/to/files 7
A pipe connects any two commands, The syntax for redirection depends on -type f | xargs grep -H -I 7
and you can construct a long chain of the shell you use, but almost all shells -i -n string
support the following operations:
Listing 1: marx.txt • < input_file redirects stdin to read This command enumerates all plain
GROUCHO: That's what they call a data from the named file. files in the named path, searches each
sanity clause. • > output_file redirects stdout, sending one for occurrences of the given string,
CHICO: Ah, you fool wit me. There the results of a command or a pipe and generates a list of files that contain
ain't no Sanity Claus!
(but not the errors) to a named file. If the string, including the line number
and the specific text that matched. The
Listing 2: Redirection Examples find clause searches the entire hierar­
01 $ # First example 11 $ echo 'I started work on Nov 2 at 9 chy rooted at /path/to/files, looking for
02 $ grep -i -E ,AGroucho' marx.txt | am.' >> timecard.txt plain files (-type f). Its output is the list
cut -d ':' -f 2 > groucho.txt 12
03 $ cat groucho.txt
of plain files.
13 $ cat timecard.txt
04 That's what they call a sanity clause. The xargs clause is special: xargs
14 I started work on Nov 1 at 8.15 am.
OS launches a command - here, grep plus ev­
15 I finished work on Nov 1 at s pm.
06 $ # Second example
07 $ cat timecard.txt 16 I started work on Nov 2 at 9 am. erything to the end of the line - once for
08 I started work on Nov 1 at 8.IS am. 17 each file listed by find. The options -H
09 I finished work on Nov 1 at 5 pm. 18 $ # Third example and -n preface each match with the file
10 19 $ ruby myapp.rb < data >& log
name and line number of each match,

LINUX SHELL HANDBOOK- 2023 EDITION 17


GETTING AROUND Pipesand Redirection

respectively. The option -i ignores case. -I that sort of output - which is useful, be­ $ { ps; w } > state.'date '+%F''
(capital I) skips binary files. cause it often interferes with working at
Assuming that the directory /path/to/src the command line - redirect your output In the preceding command, ps runs, fol­
contains files a, b, and c, using find in to the “bit bucket, ” /dev/null. Bits check lowed by w (which shows who is using
combination with xargs is the equivalent of: in, but they don’t check out. the machine), and the collected output is
Listing 3 shows a simple example. If captured in a file.
$ find /path/to/src you redirect the standard output of cat You can also embed a sequence of
a to /dev/null, nothing is displayed. (All commands in parentheses to achieve
b the bits are thrown into the virtual ver­ the same result, with one important
tical file.) However, if you make a mis­ difference: The series of commands
$ grep -H -I -i -n string a take, error messages, which are emitted collected in parentheses runs in a sub­
$ grep -H -I -i -n string b to standard error, are displayed. If you shell and does not affect the state of
$ grep -H -I -i -n string c want to ignore all output, use the >& the current shell. For example, you
operator to send stdout and stderr to might expect the command { cd
In fact, searching a collection of files is the bit bucket. $H0ME; Is -1 }; pwd to produce the
so common that grep has its own option You can also use /dev/null as a zero­ same output as (cd $H0ME; Is); pwd.
to recurse a file system hierarchy. Use -d length file to empty existing files or create Note, however, that the commands in
recurse or its synonyms -R or -r. For ex­ new, empty files (Listing 4). braces change the working directory of
ample, the command the current shell. The latter technique
Other Tricks is inert.
grep -H -I -i -n -R string /path/to/src In addition to redirection, the shell offers The decision to use a combination or
many other tricks to save time and effort. a subshell depends on your intentions,
works as well as the combination of find The “back tick” or “back quote” op­ although the subshell is a much more
and xargs. However, if you need to be selec­ erator ('... ') expands commands in powerful tool. You can use a subshell
tive and pick specific kinds of files, use find. place. A phrase between back ticks to expand a command in place, just as
runs first, while the shell interprets the you can with back ticks. Better yet, a
Bit Bucket command-line, and its output replaces subshell can contain another subshell,
As you’ve seen, most commands emit the original phrase. You can use back so expansions can be nested. The two
output of one kind or another. Most com­ ticks to yield, for example, a file name commands
mand-line commands use stdout and or a date:
stderr to show progress and error mes­ $ { ps; w } > state.$(date '+%F')
sages, in that order. If you want to ignore $ ps > state.'date 1+%F’' $ { ps; w } > state.'date '+%F''
$ Is state*
Listing 3: The Bit Bucket state.2009-11-21 are identical. The notation $( ) runs
01 $ Is $ cat state.2009-11-21 the commands within the parentheses
02 secret.txt 13842 ttysOOl 0:00.54 -bash and then replaces itself with the out­
03 $ cat secret.txt
04 I am the Walrus. 30600 ttysOOl 1:57.15 P put. In other words, $( ) expands in
05 $ cat secret.txt > /dev/null ruby ./script/server place, just like back ticks; however,
06 $ cat socrates.txt > /dev/null unlike back ticks, $( ) can be very
07 cat: socrates.txt: No such file or
directory $ cat 'is state.*' complex and can even include other $( )
08 $ cat socrates.txt >& /dev/null 13842 ttysOOl 0:00.54 -bash expansions:
09 $ echo Done. 30600 ttysOOl 1:57.15 P
10 Done.
ruby ./script/server $ (cd $(grep strike /etc/passwd | P
cut -f6 -d':'); ls)xw
Listing 4: Empty Files The first command-line captures the
01 $ cat secret.txt list of running processes in a file This command searches the system
02 Anakin Skywalker is Darth Vader. named something like state. password file to find an entry for user
03 $ cp /dev/null secret.txt
YYYY-MM-DD, where the date portion strike, clips the home directory field
04 $ cat secret.txt
05 of the name is generated by the com­ (field six, if you count from zero),
06 $ echo "The moon is made of mand date ' + %F'. The single quotes changes to that directory, and lists its
cheese!" > secret.txt around the argument prevent the shell contents. The output
07 $ cat secret.txt
08 The moon is made of cheese!
from interpreting + and %. The last
09 $ cat /dev/null > secret.txt command shows another example of grep /etc/passwd strike | cut -f6 -d':'
10 $ cat secret.txt the back tick. The evaluation of Is
11
state. * yields a file name. is expanded in place before any other
12 $ cp /dev/null newsecret.txt
13 $ cat newsecret.txt Speaking of capturing results, if you operation. Because the subshell has
14 want to capture the output of a series of so many uses, you might prefer to use
15 $ echo Done. commands, you can combine them it instead of the { } or the back tick
16 Done.
within braces ({ ... }): operators. ■

18 LINUX SHELL HANDBOOK - 2023 EDITION


Customizing the Bash Shell GETTING AROUND

Environment variables can be stored


Customizing the command-line with Bash J
in several places. The most common file
for variables is ~/.bashrc. However,

BESPOKE * your home directory may also include


.profile or .bash-profile, a standard set of
variables that sets the paths and deter­
mines whether .bashrc can be run. Your

SHELL
home directory may also contain .bash_
login and bash_login. These dot files -
so called because each file name starts
with a period - are not ordinarily visible
when viewing directory contents. In­
Make the Bash shell your own by customizing the shell
stead, the Is command must specify the
environment with variables and aliases. You may end up -a option to make them visible. However,
with a more efficient Bash shell. BY BRUCE BYFIELD even then, you may not see most of
them, because the modern trend is not
ash is the default command shell defines what your command line looks to install any of them by default, espe­

B for most Linux distributions. As


installed, it is perfectly func­

it more to your liking or for greater effi­


like and what it can do. Some variables
are added during installation to oversee
general system functionality. Other vari­
tional. However, you may want to adjust
ables are added as you install applica­
cially on standalone machines. When
one is used, it is generally .bashrc (Fig­
ure 1). Many distributions heavily com­
ment the files to make them more useful.
ciency. Whatever your reason, Bash of­ tions such as desktop environments. In addition, /etc/profile/. bashrc and/etc/
fers plenty of opportunities for custom­ Table 1 shows some of the common en­ bash/.bashrc are global files - templates
ization. Many customizations are stored vironment variables. Environment vari­ used when setting up new users. They are
in a handful of files, although these days ables can be set temporarily from the com­ used primarily for setting up multiple com­
a few are managed by terminal applica­ mand line or loaded as commands along­ puters or networks, so home users may
tions. Additionally, users can always side snippets of code in Bash configuration never have seen them. As you might guess
write scripts for specific tasks. files that run when Bash opens (Table 2). from the file names, both have similar con­
Essentially, Bash is a collection of envi­ Before going further, you should check out tents to the correspondingly named files in
ronmental variables (and sometimes each command’s man page to learn more a home directory. Should both global and
functions). At first glance, that might about each one’s purpose. Note that vari­ home directory versions exist, those in
seem a formidable statement to a non­ ables are printed in uppercase letters only. home directories override the files in/etc.
programmer. However, all that means is When used in a command, they are pref­ Read on for more details about specific
that Bash includes a group of settings that aced with a dollar sign ($). variables.

Table 1: Common Environment Variables Setting the Editor


COLUMNS The width of the terminal display in characters (usually 80) If you do not define EDITOR, applications
that need one are likely to use Vim. How­
DESKTOP-SESSION The default desktop environment
ever, you may prefer Emacs, or the more
DISPLAY The display used by X, (usually set to :0.0, which is the first dis­
play on the current computer) user-friendly JOE, nano, Pico, or Tilde.
Working from the command line, you
EDITOR Your default text editor
probably do not want to wait for a graphi­
HISTCONTROL Settings to control the history file
cal editor to start up - and in some cases,
HISTFILESIZE The maximum lines in the history file
HISTSIZE The maximum number of entries in the history file Table 2: Commands for
HOSTNAME The computer's hostname Environment Variables
HOME Your home directory env Customizes the environment in
LANG Your current language which a command runs. By it­
self, it lists current variables.
MAIL The location of your mail spool (usually /var/spool/mail/USER)
set Creates a variable for the local
MANPATH The list of directories to search for man pages
terminal, either temporarily at
PS1 The default prompt in Bash the command line or perma­
PWD The default current working directory nently in one of the files in
which variables are defined. By
SHELL The path to the current command shell (e.g.,/bin/bash)
itself, it lists current variables.
TERM The current terminal type The unset command removes
TZ Your time zone variables.
USER Your current username export Like set, except it sets the
variable for the entire login
Note: The default variables depend on your distribution. environment.

LINUX SHELL HANDBOOK- 2023 EDITION 19


GETTING AROUND Customizing the Bash Shell

# ~/.bashrc: executed by bash(l) for non-login shells. local/bin, /usr/bin, /bin, /usr/local/games,
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples and /usr/games. To add a directory to the
# If not running interactively, don't do anything
path called ~/sandbox/bin, you would
case S- in first define it as a path and then add it to
*i*) ;;
*) return;; the general list of paths:
esac
# don't put duplicate lines or lines starting with space in the history. PATH=$PATH:~/sandbox/bin
# See bash(l) for more options
HISTCONTROL=ignoreboth export PATH

# append to the history file, don't overwrite it


shopt -s histappend To remove a path from the path state­
# for setting history length see HISTSIZE and HISTFILESIZE in bash(l) ment, replace the existing statement in
HISTSIZE=1000 .bashrc using the command:
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS. export PATH=[pathl]:[path2]:[paths]
I_______________________________________________________________________
Figure 1: The beginning of a Debian .bashrc file. Setting the History
Bash’s history is a list of previously en­
you may not be using Bash from a desk­ on your system. Should you try to use a tered commands. Instead of retyping,
top. Be sure to define your editor and command not on the path, you will re­ you can use the history, either with the
know how to use it before you need it ceive a “command not found" message. history command or the arrow keys, to
(especially how to close the editor). To use a command off the path, you have select a command. Items in the history
to change to the command’s directory or are stored in .bashjiistory, but control
Setting the Path else type out the full path, either of which of how the history command operates is
By defining PATH, you make any com­ is a nuisance if you use the command defined in .bashrc.
mands on the path accessible anywhere regularly. Most distributions use the HISTSIZE
The default variable to change the number of com­
1866 2021-01-29, 14:50:38 git stage partl.txt
1867 2021-01-29, 14:50:38 git commit partl.txt paths are the most mands in the Bash history. After all, if a
1868 2021-01-29, 14:50:38cd ./wip common directo­ command is used more than once, no
1869 2021-01-29, 14:50:38 Xs
ries for storing exe­ convenience is gained by listing it more
1870 2021-01-29, 14:50:38 git commit -m "MESSAGE"
1871 2021-01-29, 14:50:38 git checkout master cutable files. You than once. Another common history vari­
1872 2021-01-29, 14:50:38 git branch checkout master can view the cur­ able is HISTFILESIZE, which is a misno­
1873 2021-01-29, 14:50:38 git branch --list
1874 2021-01-29, 14:50:38 git merge lst-draft rently defined mer, since what it defines is the number
1875 2021-01-29, 14:50:38 git checkout lst-draft paths with echo of lines. The default is 1,000 lines, but if
Figure 2: Finding items in the Bash history is easier if you modify SPATH. Typically, you work regularly at the command line,
the history to include the date and time. the paths are /usr/ you may want to increase that number.
The less common HISTTIMEFORMAT,
Table 3: Building Blocks for Command Prompts in the form
\d Displays today's date in [weekday]/[month]/[day]
export HISTTIMEFORMAT='%F, %T '
\t Current time in 24-hour HH:MM:SS format
\T Current time in 12-hour HH:MM:SS format adds a date and timestamp to the history,
W 24-hour clock in HH:MM format (no seconds) making items easier to find (Figure 2).
\H Full hostname If you add
Number of jobs being managed by the shell
PR0MPT_C0MMAND='history -a'
Is The name of the shell
lu Current username then all commands are entered in the his­
Iv Bash version tory immediately after being run, instead
II/ Extra information about the Bash version of at the end of the Bash session, which is
Iw Current working directory (SHOMEis represented by ~) the default. Immediately saving com­
mands is especially useful if the same
in/ The basename of the working directory (SHOME is represented by ~)
1/ This command's number in the history
Table 4:
1# This command's command number Prompt Font Weights
IS Specifies whether the user is root (#} or otherwise ($) 0 Normal
II Backslash 1 Bold
\[ Start a sequence of non-displayed characters 2 Dim
\] Close or end a sequence of building blocks 4 Underlined

20 LINUX SHELL HANDBOOK - 2023 EDITION


Customizing the Bash Shell GETTING AROUND

General Tabs Appearance Scrolling Keyboard Mouse Advanced to run when Bash alias lists the aliases currently on your
opens, but to be system. Usually, aliases are stored in
Color Scheme & Background
hidden, or to store .bashrc, but they can also be stored in
New...
Breeze administrative in­ .bash_aliases, which is slightly more
Edit Color ...e — Konsole ? © formation at the convenient to find. Typing alias lists the
Dark Pastel
Description: New Color Scheme prompt where it is aliases currently on your system.
Green on Bl;
always easily seen.
Name Color tense col aintcolo
Linux Colors For instance, the Up Next: Bash Scripting
Foreground
default Debian When you have implemented the built-in
Red on Blad prompt conceals a customizations that you want in the Bash
Color
prompt for a chroot shell, you may want to explore Bash script­
Solarized Color
jail that does not ing. Bash scripting is done in a simple lan­
Vary the background color for each tab
ordinarily display. guage, and sometimes is no more than a
Blur background
The more you collection of commands entered one per
Preview: Oxygen Mono Background transparency: O','..
learn about Bash, line. A script has an .sh extension and is
Text size: 18.0 0 Select! Background image:
the more reasons run with the sh command. Learning Bash
■ Smooth fonts for customizing the scripting is beyond the scope of this article,
■ Draw intense colors in bol prompt will be­ but you can get a start by looking up scripts
Figure 3: You can quickly change the look of Bash using profiles in come obvious. online and modifying them for your pur­
the terminal application. The prompt’s poses (sometimes this includes changing
color can also be the script’s permissions). Before long, you
user has several tabs opened - otherwise, customized. Use \e to mark the start of the may have a Bash shell far beyond the de­
only the first tab’s history is saved. color definition and \e[0m to mark the fault provided during installation. ■
Another useful variable is HISTCON- end. Numbers define the prompt’s font
TROL, which takes four definitions. If weight (Table 4) and color (Table 5). So Table 5: Prompt Colors
HISTCONTROL is completed with ignore- the following line in .bashrc 30 Black
space, it deletes history listings that
32 Green
begin with a space; ignoredups deletes PSI ="/0;32m]\u $\e[0m"
duplicate commands, while ignoreboth 33 Brown
deletes both those that begin with a displays the username and dollar sign in a 34 Blue
space and duplicates. normal green font. If you use a bold weight, 35 Purple
Yet another variable, HISTIGNORE you get a lighter version of the color.
36 Cyan
takes a list of commands not to be added
Cosmetics 37 Light gray
to history. Outside of export and .bashrc,
you can also run history -cw to com­ Besides using number codes to color the
pletely delete the current history. command prompt, you can set the color Table 6: Coloring the
in your terminal with tput (Table 6). terminal with tput
Customizing the Prompt However, tput seems to have fallen into Area Color
The command prompt marks the latest disuse. In this desktop era, Bash’s appear­ tput setb [1-7] Set a background color
position in the shell from which an entry ance is usually set not in Bash, but in the
tput serf[1-7] Set a foreground color
can be made. The default prompt on terminal application through the use of
Text Weight
most systems usually has the format of profiles that set both the appearance and
USER@HOST or something similar and the behavior of the terminal (Figure 3). tput bold Set bold mode
is set with the PSI variable. A sub­ Profiles offer far more customization tput dim Turn on half-bright mode
prompt is sometimes set with PS2 as choices than tput or prompt codes, and tputsmul Begin underline mode
well, usually >. Typically, the prompt they are far easier to set as well. tput rmul Exit underline mode
for an ordinary account ends in $, while tput rev Turn on reverse mode
the prompt for the root user ends in #. Aliases tputsgrO Turn off all attributes
Both PSI and PS2 can include any text An alias is an alternative name for a
Colors
you want. You can also use the building command. You might create an alias for
0 Black
blocks shown in Table 3, separating each a common misspelling (e.g., typing si for
with a backslash. Why would you want to Is), as an alternative to adding to a path, 1 Red
do this? There are many reasons. If you as a way of making a command name 2 Green
usually have Bash open, then you can easier to remember, or to save typing a 3 Yellow
save space by not having a desktop clock. long command. Many distributions in­ 4 Blue
If you frequently refer to the Bash history, stall with the alias Is for Is -color = auto, 5 Magenta
then a prompt that refers to a command’s which colors different types of files, pre­ 6 Cyan
history number might be convenient. Ex­ sumably on the assumption that no one
7 White
perts might like a command in the prompt wants the plain Is command. Typing

LINUX SHELL HANDBOOK- 2023 EDITION 21


GETTING AROUND Text Manipulation Tools


Text pr_____

TACKLINGTEXT Nicholas Piccillo, Fotolia

Enjoy a crash course on some of the text-processing and -filtering After I examine a few more shell tricks
in the sections that follow, I’ll return to
capabilities found in Linux. BY HAL POMERANZ this example.

head and tail


nix-like operating systems have this feature, use the following useful Another pair of simple text-processing

U historically been very much


about text processing. Really,
idiom for counting the number of files in
a directory:
the Unix design religion is: Make simple
tools whose output can be manipulated $ Is I wc -1
filters are head and tail, which extract
the first 10 or the last 10 lines from their
input, respectively. Also, you can specify
a larger or smaller number of lines. For
by others with the use of pipes and 138 example, to obtain the name of the most
other forms of output redirection. In recently modified file in a directory, use:
this article, I’ll look at the wealth of To count the number of bytes in a file,
Linux command-line tools for combin­ use wc -c: $ Is -t | head -1
ing, selecting, extracting, and otherwise kern.log
manipulating text. $ wc -c kern.log
106932 kern.log Then if you wanted to see the last few
WC lines of that file, use:
The wc (word count) command is a sim­ On a single file, wc -c isn’t necessarily
ple filter that you can use to count the that interesting because you could see $ tail -3 kern.log
number of lines, characters (bytes), and, the same information in the output of Is Nov 21 09:00:19 elk kernel: P
yes, even the number of words in a file. -I. However, if you combine wc with the [11936.090452] [UFW BLOCK INPUT]: 7
Whereas counting lines and bytes tends find command, you get byte counts for IN=eth0 OUT=...
to be useful, I rarely find myself using wc all files in an entire directory tree: Nov 21 09:00:21 elk kernel: 7
to count words. [11938.0836SS] [UFW BLOCK INPUT]: 7
You can count lines in a file with wc -I: $ find /var/log -type f P IN=eth0 0UT=...
-exec wc -c {} \; Nov 21 09:00:25 elk kernel: 7
$ wc -1 kern.log 79666 /var/log/kem.log.6.gz [11942.134431] [UFW BLOCK INPUT]: 7
1026 kern.log 3781 /var/log/dpkg.log.4.gz IN=eth0 0UT=...
106932 /var/log/kem.log
If you don’t specify a file name, wc will Here’s a trick for extracting a particular
also read the standard input. To exploit line from a file by piping head into tail:

22 LINUX SHELL HANDBOOK - 2023 EDITION


Text Manipulation Tools GETTING AROUND

$ head -13 /etc/passwd | tail -1 rw-r--r-- adjtime You can use the -F option with awk to
www-data:x:33:33:www-data:P specify a delimiter other than white
/var/www:/b in/sh space. This lets you use awk in places
That looks better! Notice the syntax with where you might normally use cut, but
In this case, I am extracting the 13th line tail here. The -n option is the alternative where you want to use awk’s conditional
of /etc/passwd, but you could easily se­ (POSIX-ly correct) way of specifying the operators to match specific input lines.
lect any line just by changing the nu­ number of lines tail should output. So, Suppose you want to output user­
meric argument that is passed in to the tail -10 and tail -n 10 are equivalent. If names and home directories as in the
head command. you prefix the number of lines with +, first cut example, but only for users with
Another useful feature of the tail com­ as in the example above, it means start directories under /home:
mand is the -/option, which displays the with the specified line. So, here I’m tell­
last 10 lines of the file as usual, but then ing tail to display all lines from the sec­ $ awk -F: ' ($6 ~ /A\/home\//) P
keeps the file open and displays any new ond line onward. The + syntax only { print $1 $6 }' /etc/passwd
lines that are appended onto the end of works after -n. sabayon:/home/sabayon
the file. This technique is particularly cut is wonderful for lots of tasks, but hal:/home/hal
useful for keeping an eye on logfiles - the output of many commands is sepa­ laura:/home/laura
for example, tail -fkem.log. rated by white space and often irregular.
The awk command is best for dealing Rather than matching against the entire
cut and awk with this kind of input: line, the command here uses the ~ op­
head and tail are useful for selecting par­ erator pattern match against a specific
ticular sets of lines from your input, but $ ps -ef | awk P field only.
sometimes you want to extract particular '{print $1 "\t" $2 "\t" $8}'
fields from each input line. The cut com­ UID PID CMD sort
mand is useful when your input has reg­ root 1 /sbin/init Sorting your output is often useful:
ular delimiters, such as the colons in root 2 [kthreadd]
/etc/passwd: root 3 [migration/O] $ awk -F: '($6 ~ /A\/home\//) 7
{ print $1 $6 }' 7
$ cut -d: -fl,6 /etc/passwd /etc/passwd | sort
root:/root awk automatically breaks up each input hal:/home/hal
daemon:/usr/sb in line on white space and assigns each laura:/home/laura
bin:/bin field to variables named $1, $2, and so sabayon:/home/sabayon
on. awk is a fully functional scripting
language with many different capabili­ By default, sort simply sorts alphabeti­
The -d option specifies the delimiter ties, but at its simplest, you can just use cally from the beginning of each line of
used to separate the fields on each line, the print command to output particular input. Sometimes numeric sorting is
and -/ allows you to specify which fields input fields as I’m doing here. what you want, and sometimes you
you want to extract. In this case, I’m awk also allows you to select specific want to sort on a specific field in each
pulling out the usernames and the home lines from your input with the use of input line. Here’s a classic example that
directory for each user, cut also lets you pattern matching or other conditional shows how to sort your password file by
pull out specific sequences of characters operators, which saves you from first the user ID field (useful for spotting du­
by using -c instead of -/. Here’s an exam­ having to filter your input with grep or plicate UIDs and when somebody has
ple that filters the output of Is -I so that some other tool. For example, suppose I added illicit UID 0 accounts):
you see just the permissions flags and wanted the filtered ps output above, but
the file name: only for my own processes: $ sort -n -t: -k3 /etc/passwd
root:x:0:0:root:/root:/bin/bash
$ Is -1 I cut -c2-10,52- $ ps -ef | awk '/Ahal / P daemon:x:1:1:daemon:/usr/sbin:/bin/sh
otal 1540 {print $1 "\t" $2 "\t" $8}' bin:x:2:2:bin:/bin:/bin/sh
rwxr-xr-x acpi hal 7445 P
rw-r--r-- adduser.conf /usr/bin/gnome-keyring-daemon
rw-r--r-- adjtime hal 7460 x-session-manager The -n option indicates a numeric sort, -t
hal 7566 P specifies the field delimiter (such as cut
/usr/bin/dbus-launch -d or awk -F), and -k specifies the field (s)
Darn! The output contains the header to sort on (clearly they were running out
line from Is -I. Happily, tail will help of option letters).
with this: Here, I use the pattern match operator Also, you can reverse the sort order
(/.../) to produce output only for lines with -r to get descending sorts:
$ Is -1 I tail -n +2 I cut -c2-10,52- that start with hal < space >. The com­
rwxr-xr-x acpi mand ps -ef | awk '($1 = = "hal") ...' $ Is /etc/rc3.d | sort -r
rw-r--r-- adduser.conf would accomplish the same thing. S99stop-readahead

LINUX SHELL HANDBOOK- 2023 EDITION 23


GETTING AROUND Text Manipulation Tools

S99rmnologin 8 apache But it’s not really that common to want


S99rc.local 1 dbus to glue files together on a line-by-line
8 dovecot basis. More often you want to match up
lines on some particular field, which is
Remember the find command that I used what the join command is for. The join
wc -c with to get byte counts for all files And with the use of another sort com­ command can get pretty complicated, so
under a given directory? Well, you can mand, you could sort that output by the I’ll provide a simple example that uses
sort that output and then filter with head number of processes: files of letters.
to get a count of the 10 largest files To put line numbers at the begin­
under your chosen directory: $ ps -ef | awk '{print $1}' 7 ning of each line in the files, use the
| sort | uniq -c | sort -nr nl program:
$ find /var/log -type f -exec 7 121 root
wc -c {} \; | sort -nr | head 11 hal $ nl capitals
44962814 /var/log/vnetlib 8 dovecot 1 A
24748291 /var/log/syslog 8 apache 2 B
24708201 /var/log/mail.log 3 C
24708201 /var/log/mail.info
10243792 /var/log/ConsoleKit/history Another useful trick is uniq -d, which
3902994 /var/log/syslog. 0 only shows lines that are repeated (du­ The join command could then stitch to­
3782642 /var/log/mail.log.0 plicated) and doesn’t show unique lines. gether the resulting files by using the
3782642 /var/log/mail.info.0 For example, if you want to detect dupli­ line numbers as the common field:
1039348 /var/log/vmware/hostd-7.log cate UIDs in your password file, enter:
804391 /var/log/installer/partman $ join <(nl capitals) <(nl lowers)
$ cut -d: -f3 /etc/passwd 7 1 A a
uniq | sort -n | uniq -d 2 B b
When you’re extracting fields with cut 3 C c
and awk, you sometimes want to output In this case, I didn’t get any output - no
just the unique values. There’s a uniq duplicate UIDs - which is exactly what I
primitive for this, but uniq only sup­ want to see. Notice the clever <(...) Bash syntax,
presses duplicate lines that follow one By the way, a uniq -u command will which means, substitute the output of a
right after the other. Therefore, you must output only the unique (non-duplicated) command in this place where a file name
typically sort the output before handing it lines in your output, but I don’t find my­ would normally be used.
off. For example, to get a list of all users self using this option often. For some reason, when I’m using join,
with processes running on the current life is never this easy. Some crazy combi­
system, use the following command: paste and join nation of fields and delimiters always
Sometimes you want to glue multiple seems to be the result. For example, sup­
$ ps -ef | awk '{print $1}' 7 input files together. The paste command pose I had one CSV file that listed the
| sort | uniq simply combines two files on a line-by- top 20 most populous countries along
apache line basis, with tab as the delimiter by with their populations:
dbus default. For example, suppose you had a
dovecot file, capitals, containing capital letters 1,China,1330044544
and another file, lowers, containing the 2,India,1147995904
letters in lower case. To paste these files 3,United States,303824640
sort | uniq is such a common idiom that together, use:
the sort command has a -u flag that does
the same thing. Thus, you could rewrite $ paste capitals lowers And suppose my other file listed the
the above example as capital cities of all the countries in the
B world:
ps -ef | awk '{print $1}' | sort -u
Afghanistan,Kabul
The uniq program has lots of useful op­ Albania,Tirane
tions. For example, uniq -c counts the Or if you wanted to use something other Algeria,Algiers
total number of lines merged, and you than tab as the delimiter:
could use this to report the number of
processes running as each user, as in the $ paste -d, capitals lowers What if my task were to connect the cap­
following command: ital city information with each of the 20
most populous countries? In other
$ ps -ef | awk '{print $1}' 7 words, I want to glue the information in
| sort | uniq -c the two files together with the use of

24 LINUX SHELL HANDBOOK - 2023 EDITION


Text Manipulation Tools GETTING AROUND

field 2 from the first file and field 1 from 1000 dictionary.01 shell normally interprets the backslash
the second file. The complicated thing 1000 dictionary.02 as a special character. Doubling them up
about join is that it only works if both indicates that the backslash should be
files are sorted in the same order on the taken literally.)
fields you’re going to be joining the files Here, I’m splitting the file called diction­ Instead of converting one set of char­
on. Normally, I end up doing some pre­ ary into 1000-line chunks (-Z1000, is actu­ acters to another, you can use the -d op­
sorting on the input files before giving ally the default) and assigning dictionary tion simply to delete a particular set of
them to join: as the base name of the resulting files. characters from your input. For example,
Then, I want split to use numeric suffixes if you don’t happen to have a copy of the
$ join -t, -12-21 <(sort -t, 7 (-d) rather than letters, and I use wc -I to dos2unix command handy, you can al­
-k2 most-populous) <(sort cities) count the number of lines in each file and ways use tr to remove those annoying
Bangladesh,7,153546896,Dhaka confirm that I got what I wanted. carriage returns:
Brazil,5,196342592,Brasilia Note that you can also specify a dash
China,1,1330044544, Beijing (-), meaning standard input, instead of $ tr -d \\r <dos.txt >unix.txt
a file name. This approach can be use­
ful when you want to split the output of Or, for a sillier example, here’s a way for
The options to the join command spec­ a very verbose command into manage­ all you fans of The Matrix to get a spew
ify the delimiter I’m using «) and the able chunks (e.g., tcpdump | split -d -I of random characters in your terminal:
fields that control the join for the first 100000 - packet-info).
(-1 2) and second (-2 1) files. Once $ tr -d —c [:print:] </dev/urandom
again, I’m using the < (...) Bash syn­ tr
tax, this time to sort the two input files The tr command allows you to transform Here I’m using [:print:] to specify the set
appropriately before processing them one set of characters into another. The of printable characters, but I’m also em­
with join. classic example is mapping uppercase ploying the -c (compliment) option,
The output isn’t very pretty, join out­ letters to lowercase. For this example, to which means all characters not in this
puts the joined field first (the country transform the capitals file I used previ­ set. Thus, I end up deleting everything
name), followed by the remaining fields ously, I’ll use: except the printable characters.
from the first file (the ranking and the
population), followed by the remaining $ tr A-Z a-z < capitals Conclusion
fields from the second file (the capital a This has been a high-speed introduction
city). The cut and sort commands can b to some of the text-processing and -filter­
pretty things up a little bit: ing capabilities in Linux, but of course it
really only just scratches the surface.
$ join -t, -12-21 <(sort -t, 7 Lots of sites on the Internet have more
-k2 most-populous) <(sort cities) | 7 But this is a rather silly example. A more examples and ideas for you to study, in­
cut -d, -fl,3,4 | sort -nr -t, -k2 useful task for tr is this little hack for cluding shelldorado.com, command-
China,1330044544,Beij ing looking at data under/proc: linefu.com, and the weekly blog I co-au­
India,1147995904,New Delhi thor with several friends at blog.com-
United States,303824640,Washington D.C. $ cd /proc/self mandlinekungfu. com.
$ cat environ The online manual pages can help a
GNOME_KEYRING_SOCKET=/tmp/7 lot too - and don’t forget man -k for
Examples like this are where you really keyring-lFz8t4/socketLOGNAME7 keyword searches if you’ve forgotten a
start to get a sense of just how powerful =halGDMSESSION=default... command name or just aren’t sure
the text-processing capabilities of the op­ $ tr \\000 \\n <environ where to start! But, really, the best
erating system are. GN0ME_KEYRING_S0CKET=/tmp/P teachers are practice, practice, and prac­
keyring-lFz8t4/socket tice. I’ve been using Unix and Linux
split L0GNAME=hal systems for more than 20 years, and I’m
Joining files together is all well and GDMSESSION=default still learning things about the shell
good, but sometimes you want to split command line. ■
them up. For example, I might split my
password-cracking dictionary into Typically, /proc data are delimited with Hal Pomeranz is the Founder and
smaller chunks so that I can farm out the nulls (ASCII zero), so when you dump CC Technical Lead of Deer Run Associ-
processing across multiple systems: /proc to the terminal, everything just o ates, an IT and Information Security
J consulting firm. He is also a Faculty
runs together, as shown in the output of Fellow of the SANS Institute and the
$ split -d -1 1000 dictionary 7 the cat command above. By converting course developer and primary instruc-
dictionary. the nulls (\000) to newlines (\n), every­ iii tor for their Linux/Unix Security certi-
$ wc -1 * thing becomes much more readable. X fication track (GCUX). And, yes, he
98569 dictionary (The extra backwhacks (\) in the tr com­ could replace you with a very small
shell script.
1000 dictionary.00 mand here are necessary because the

LINUX SHELL HANDBOOK- 2023 EDITION 25


CONFIGURATION Hardware Configuration

J 9 9 |

Hardware configuration in the shell

HARDWARE HELP W
Learn about some command-line tools for discovering and configuring hardware. \

BY KLAUS KNOPPER AND KARSTEN GUNTHER; REVISED BY BRUCE BYFIELD -

n the early days of Linux, drivers in IDE interfaces, which can include sound use increasingly unnecessary. You may

I the kernel were responsible for get­


ting board and peripheral hardware
to work. Changing a hardware-related
option meant recompiling the corre­
cards, graphics cards, or external drives.
The tool runs at the command line, and
you’ll need to set some options to control
it (Table 2).
want to remove a module (-remove, -r) if
you no longer need it, although the in­
crease in efficiency will often be minimal
unless a module is buggy. The basic
sponding driver. However, since the ar­ For the sake of completeness, hdparm command structure for adding or manip­
rival of kernel modules, viewing and (hardware parameters) should also be ulating a module is:
modifying the hardware configuration mentioned, hdparm works with the
without rebooting the entire system has Linux SATA/PATA/SAS libATA subsys­ modprobe [modulename] P
become easier, so long as the main tem, the older IDE, and some USB [optionl]=[valuel] P
(static) part of the kernel is in a func­ drives released after 2008. It does not [option2]=[values]
tional state. In modern Linux, you can work with most solid state drives, and
work with hardware in several different functional options may vary with the Before using modprobe, you can run
ways: general information commands, kernel. If hdparm does work on your modinfo [module] to see a list of options
viewing the /proc and /sys virtual filesys­ system, it allows extensive customiza­ for a particular module (Figure 2). To be
tems, manipulating kernel modules, tion, including setting power manage­ safe, you can run -dry-run (-n) to see
modifying daemon configuration files, ment features, 32-bit I/O support on what a command does without actually
and working with systemd. Each of IDE drives, and onboard defect manage­ running it.
these information sources could be a ment features. However, the wrong op­ To load drivers that match the hard­
long article in itself, so what follows is tions can crash a system and brick a ware, your operating system needs
only an overview. For more information, hard drive, and some options have some kind of table for mapping the
consult the man pages for each com­ warnings in the man page. If you can current hardware to the corresponding
mand or file mentioned. use hdparm, it is a powerful tool, but modules. The Ispci command provides
unless you understand exactly what an a nice overview of your hardware: Just
Working with Commands option does, you are better off avoiding type Ispci for a short listing of devices
Most standard Linux installations in­ the command altogether. on your computer.
clude commands for displaying the
specifications for different types of Using modprobe Getting Information from
hardware (Table 1). These commands modprobe adds or removes modules /proc and /sys
generally depend on information from from the Linux kernel. Typically, you Both /proc and /sys are virtual filesys­
the /proc and /sys virtual filesystems, will need it when adding a new piece of tems that mirror the structure of the
which can also be viewed directly (dis­ hardware to the system, although the Linux kernel, primarily for the purpose
cussed below). widespread use of USB makes even that of providing system information and for |
Image© Sergey Konyakin, 123rf.<

Among these commands,


the single most useful one is Table 1: Hardware Information Commands
probably Ishw (short for “list Isblk Lists information about all available or specified block devices.
hardware”) (Figure 1). The Iscpu Summarizes CPU architecture information.
Ishw command discovers the
Ishw Displays hardware information.
details of hardware compo­
Ispci Extracts detailed information on the machine's hardware configuration.
nents, such as the CPU, mem­
Isusb Displays information about USB buses in the system and the devices connected to them.
ory modules, or the devices at­
tached to your PCI, USB, or uname Displays software and hardware information.

26 LINUX SHELL HANDBOOK - 2022 EDITION


Hardware Configuration CONFIGURATION

nanday
description: Desktop Computer
product: MS-7693 (To be fitted by O.E.M.)
vendor: MSI
version: 4.0
serial: To be fitted by O.E.M.
width: 64 bits
capabilities: smbios-2.8 dmi-2.8 smp vsyscatt32
configuration: boot=normat chassis=desktop famity=To be fitted by O.E.M. sku=To be
fitted by O.E.M. uuid=00000000-0000-0000-0000-4CCC6A250851
*-core
description: Motherboard
product: 970 GAMING (MS-7693)
vendor: MSI
physical id: 0
version: 4.0
serial: To be fitted by O.E.M.
slot: To be fitted by O.E.M.
★-firmware
description: BIOS
vendor: American Megatrends Inc.
physical id: 0
version: V22.4
I
Figure 1: Ishw summarizes the hardware on the system.

Table 2: Important Ishw Options hardware, even without looking into


Output and Display files with a page viewer. For example,
-html Generate HTML output the command
-xml Generate XML output
cd /sys/fs/ext4/sdal
-short Show a short summary
-businfo Output bus information
opens a directory with 24 subdirectories
-X Use the graphical interface that list characteristics of a drive formatted
Actions with the ext4 filesystem, providing de­
-c, -C, -class <class> Show class information tailed information for experts (Figure 4).
-disable <test> Don't run test These virtual filesystems can also be
-enable <test> Run test used to edit hardware settings via
scripts. For example, to set the time
-quiet Hide the status bar
out - the time before changes in data are
-sanitize Hide confidential information
written to disk - to 30 seconds, enter:
-numeric Show numeric IDs
echo 3000 > /proc/sys/vm/ P
interacting with kernel modules such as less /proc/cpuinfo dirty_writeback_centisecs
udev. You cannot open the contents of
these subdirectories, not even when displays detailed information about the Or, to change it temporarily, enter:
logged in as root, but you can use view­ CPUs on the system (Figure 3). The /sys
ers like cat or less to read the informa­ virtual filesystem works similarly, drill­ sysctl -w vm.dirty_ P
tion in them. For instance, ing down to detailed information about writeback_centisecs=3000

filename: /lib/modules/4.9.0-8-amd64/kernel/drivers/usb/host/ehci-pci.ko
license: GPL
author: Alan Stern
author: David Brownell
description: EHCI PCI platform driver
alias: pci:v0000104Ad0000CC00sv*sd*bc*sc*i*
alias: pci:v*d*sv*sd*bc0Csc03i20*
depends: usbcore,ehci-hcd
retpoline: Y
intree: Y
vermagic : 4.9.0-8-amd64 SMP mod_unload modversions
[BiDM
Figure 2: modinfo lists the options for a module.

LINUX SHELL HANDBOOK- 2022 EDITION 27


CONFIGURATION Hardware Configuration

processor : 0
vendor.id : AuthenticAMD
cpu family : 21
model : 2
model name : AMD FX(tm)-8350 Eight-Core Processor
stepping : 0
microcode : 0x600084f
cpu MHz : 1400.000
cache size : 2048 KB
physical id : 0
siblings : 8
core id : 0
cpu cores : 4
apic id : 16
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat ps
e36 ciflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr.opt
_ pdpelgb rdtscp Im constant
_tsc rep_good nopl nonstop.tsc extd_apicid aperfmperf pni pcimulqdq monitor ssse3 fma
cx!6 sse4_l sse4_2 popcnt aes xsave avx fl6c lahf_lm cmp_legacy svm extapic cr8_legacy

Figure 3: /proc/cpuinfo lists basic system information.

oot@nanday:/sys/fs/ext4/sdal# Is
lei ayed_allocation-blocks last_error_time mb_st ream_req
r rors_count I ifetime_write_kbytes msg_ratelimit_burst
rr_ratelimit_burst max_writeback.mb_bump msg_ rat elimit-interval_ms
r r_ratelirnit.interval.ms mb_group_prealloc reserved-dusters
xtent_max_zeroout_kb mb_max_to_scan session-write.kbytes
irst_error.time mb_min_to_scan trigger.fs_error
node.goal mb_order2_req warning.ratelimit_burst
node,readahead blks_____ mb_stats_______________ warning,ratelimit_interval_ms
Figure 4: The subdirectory names in /sys give detailed information. Here, the characteristics of an ext4 drive are displayed.

The sysctl utility is designed specifically • Shell variables (written in capital let­ • If these scripts run as root, they have
to work with /proc and /sys. ters and with no spaces), like BLUE­ the potential to destroy your system if
TOOTH-ENABLED = 1 in /etc/default/ you add the wrong command or acci­
Working with Traditional bluetooth dentally activate a command that is
Configuration Files • Comments explaining what each vari­ supposed to be commented out. To
Although systemd is today the norm for able means prevent accidents, always backup a
launching services at boot time, there • Shell functions (sometimes) to extend configuration file before editing it.
are still services, traditionally called or override features in existing scripts • Scripts are usually called with an “in­
“daemons,” that are shell scripts. Distri­ In Debian-based systems, most of these clude” to another script by the dot (.)
butions use shell-like configuration files config scripts are placed in /etc/default/* shell command, and the calling script
to configure these services easily, with­ and can be edited in a text editor as root will terminate if an exit appears.
out having to invent a new syntax for (Figure 5). • In the shell, no spaces are allowed be­
each configuration. You can usually rec­ If you make changes to any system shell fore and after the equal sign (=) when
ognize these configuration files because script or write your own system scripts, setting variables. KDE and Gnome con­
they have: please keep the following facts in mind: fig files frequently have spaces every­

root@nanday:/etc/default# Is
acpid bsdmainutils gdomap locale rsyslog
amd64-mic rocode cace rt 5 google-talkplugin minidlna saned
anac ron console-set up grub minissdpd sma rtmontools
apache-htcacheclean c r da halt mysql spamassassin
apt-firewall cron hddtemp networking speech-dispatcher
avahi-daemon dbus ht dig nfs-common t imidity
bacula-dir devpt s hwcloc k nss tmpf s
bacula-fd ebtables intel-microcode openvpn uf w
bacula-sd exim4 irqbalance rcS useradd
bluetooth firebird2.5 keyboard r sync virtualbox
Figure 5: /etc/default contains configuration files that run as scripts.

28 LINUX SHELL HANDBOOK - 2022 EDITION


Hardware Configuration CONFIGURATION

where to make them easier to read, but temd/system. To


in the shell, a space means separation be used, a new [Manager]
of a command and its parameters, override must be #LogLevel=info
which can cause a syntax error. Values activated with #LogTarget=console
or options containing spaces should systemctl dae­
#LogColor=yes
#LogLocation=no
have quotes around them. mon-reload. Run­
#SystemCallArch itectures =
ning the com­
#T ime rSIac kNSec =
Using systemd mand systemd- #DefaultTimerAccuracySec=lmin
Systemd began as a replacement for init delta shows all #DefaultStandardOutput=inherit
for starting daemons and soon morphed the overrides cur­ #DefaultStandardError=inherit
into a general system manager. Configu­ rently running on #DefaultTimeoutStartSec=90s
ration files are stored within /etc/sys­ the system. An #DefaultTimeoutStopSec=90s
temd. General information is stored in override marked #DefaultRestartSec=100ms
nine basic files in /etc/systemd, most of [EXTENDED] #DefaultStartLimitIntervalSec=10s
which have self-explanatory names, in­ shows the loca­ tfDefaultSt art LimitBurst = 5
cluding ones for login, the logfile, and tion of the over­ #DefaultEnvironment=
the network. Systemd configuration ride file, whereas #DefaultLimitCPU=
files typically begin with a series of one marked #DefaultLimitFSIZE=
fields in a section labeled [Manager] [OVERRIDDEN] Figure 6: systemd configuration files start with a [Manager] section con­
that can be edited freely. The most im­ shows the differ­ taining editable fields.
portant of these files is system.conf ence between the
(Figure 6). All the files are detailed in original and the currently used replace­ should use the same approach consis­
systemd-u.ser.conf(5) in the man pages. ment unit file (Figure 7). tently, so you can keep track of all the
For editing individual system re­ Although controversial when first in­ changes made more easily. In many
sources, systemd uses the systemctl util­ troduced, systemd is a far more orderly modern systems, the most straightfor­
ity. systemctl works with units, or system approach than the other methods of con­ ward approach is to use systemd. How­
resources configuration files, usually as figuring or finding information. How­ ever, experienced users often prefer to
a three-part structure: ever, it does introduce numerous new edit configuration files, a practice that
concepts that can be overwhelming at is as old as Linux itself - if not older.
systemctl [sub-command] [unit] first. As with any other methods, be sure Most of the time, what matters is not
you know what you are doing with sys­ the method so much as consistency.
For example the major sub-commands temd before you actually edit one of its Whatever your approach, a wealth of
for system services are status, enable, files. See the article on systemd else­ information is available. In fact, there is
or disable. where in this issue. probably more information than all ex­
Each unit has its own configuration cept a small minority of users can com­
file. However, rather than being edited Consistency Is Key prehend or use, but Linux is built on the
directly like traditional configuration These sources of information and ways assumption that users want to tinker -
files, unit configuration files can be pro­ to edit are a lot to absorb. Unsurpris­ and the beginning of tinkering is infor­
vided an override file or a full replace­ ingly, functions are often duplicated mation and options. With the tools listed
ment file by using the systemctl com­ between different sources. If you here, users have an embarrassment of
mand. Overrides are stored in /etc/sys­ change the configuration, usually you riches to use and to learn from. ■

root@nanday:/etc/systemd# systemd-delta
[EXTENDED] /Iib/systemd/system/rc-Iocal.service -* /lib/systemd/system/rc-local.servi
[EXTENDED] /Iib/systemd/system/systemd-timesyncd.service -* /Iib/systemd/system/syste
[OVERRIDDEN] /usr/Iib/systemd/system/wacom-inputattach@.service -» /lib/systemd/system/

Files /Iib/systemd/system/wacom-input attach®,service and /usr/lib/systemd/system/wacom

[EXTENDED] /Iib/systemd/system/systemd-resolved .service -» /lib/systemd/system/system

4 overridden configuration files found.


[lines 1-9/9 (END)
Figure 7: systemd has the option of overrides that take precedence over the original file without overwriting it.

LINUX SHELL HANDBOOK- 2022 EDITION 29


CONFIGURATION fdisk, gdisk, and Parted

Device partitions and volumes fdisk /dev/hda


fdisk -u /dev/sdc

DISK MAGIC
We show how to prepare a hard disk for the filesystem.
The program writes its output to the screen
and provides a command prompt but does
not provide paging (e.g., less), so you
might need to scroll up to read lengthy out­
put. Entering m at the prompt lists the
available fdisk commands. From the main
menu, you can create new partitions (n),
BY NATHAN WILLIS, HANS-PETER MERKEL, AND BRUCE BYFIELD delete existing partitions (d), verify the
partition table (v), and set several flags
hard disk on a modern computer is limiting). The Unified Extensible Firm­ (the most notable being the bootable flag,

A usually divided into partitions. A


partition can contain exactly one
ware Interface (UEFI) standard, defines a
new format for specifying partition infor­
filesystem (the data structure that storesmation known as the GUID Partition
files and directories). In Linux, swap space Table (GPT). As older PCs are replaced,
toggled with a). To apply any changes,
write a new partition table to the drive by
entering w. At any time, you can quit with­
out writing the partition table with q.
is usually implemented as a filesystem of GPT-based disks are replacing MBR-based Creating a partition is a multistep pro­
its own, requiring its own partition. Addi­ disks. All new personal computers, in­ cess. Type n to begin, and fdisk will ask
tionally, many users create separate parti­ cluding those running Linux, macOS, whether you want to create a primary
tions for the /boot, /var/, and /home direc­ and Windows, support GPT. Some oper­ partition (p) or an extended partition (e).
tories. In theory, although Linux can be in­ ating systems still offer MBR support for Whichever you choose, fdisk will then
stalled on one partition, many Linux sys­ compatibility with older hardware. ask you to select the partition number
tems use multiple partitions. (be careful to choose an unused one if
Before you can install an operating sys­ fdisk for MBR Partitions you have already created several), the lo­
tem, you need to create partitions and for­ The fdisk utility lets you create and man­ cation on the drive where you want the
mat them with filesystems. Most Linux in­ age partitions on MBR-based disks. Fdisk partition to start, and its size.
stallers provide a GUI for creating and has two basic modes: interactive and Fdisk will prompt you with the num­
managing partitions during the installa­ non-interactive. Non-interactive mode ber of the first available cylinder on the
tion process, but if your system is already queries a partition and displays the infor­ drive. To leave an empty space between
installed, you can turn to several manage­ mation. By contrast, interactive mode is partitions, choose a higher number,
ment utilities for configuring partitions. menu driven and lets you alter, as well as which could help if you ever need to re­
The Bash command line provides several explore, partitions and partition tables. size your partition.
utilities for creating and configuring parti­ Running fdisk -I prints a listing of the
tions, including fdisk, gdisk, and parted. partition tables of all of the drives on the gdisk for GPT Partitions
These tools are all generally safe, but system. To use fdisk, you might need to The new UEFI standard replaces the old
accidents such as power interruptions can preface it with su or sudo to attain root MBR with the new GPT format, which
happen, so be extremely careful. Before privileges, depending on your distribution. solves some of the problems associated
beginning, back up your data. Then boot To view only a single drive’s table, ap­ with the MBR, supporting a much larger
from a Live disk so all your hard drive pend the drive name to the command: disk size and theoretically allowing up to
partitions are unmounted before you edit 128 partitions on a disk.
them. Most of all, check all your actions fdisk -1 /dev/sda Because GPT uses a different format
twice before beginning them. for storing partition information, it re­
Note that fdisk requires a drive as its de­ quires a different utility. The most popu­
MBR to GPT Switch vice argument. Fdisk’s output (Figure 1) lar options for the Linux command line
For many years, information on the parti­ includes the total drive size and basic ge­ are the GPT fdisk utilities gdisk, sgdisk,
tion structure was stored in a small sector ometry, then lists the partitions on the and fixparts. The GPT fdisk toolset
at the beginning of the disk known as the drive and their start and end locations, comes standard on several contemporary
Master Boot Record (MBR). size, and partition type (both by name and Linux systems; if you don’t find it, install
The old MBR served the hard disk in­ by ID number). Size is reported in blocks. it through your distro’s package manage­
dustry well, but the industry outgrew it. By adding the -u flag, you can have fdisk ment system. Once you have installed the
MBR-based disks could only have four pri­ report partition start and end locations in GPT toolset, you can use it to check and
mary partitions, and the size of a partition sectors instead of cylinders. Running modify the disk. The gdisk command
was limited to 2TB (once an impossibly here returns what follows for a new disk:
large size but today sometimes severely fdisk -s </some/device>
gdisk /dev/sdh
file [dlt yiew Jkrmlnal Help prints only the size
iMgjzinc&tacBuntui-S sudo fdisk -I of the device, but it Partition table scan:
WARNING: GPT (GUID Partition Table) detected on '/dev/sda'I The util fdisk doesn't support
GPT. use GNU Parted.
works for both MBR: not present
drives and partitions. BSD: not present
Disk /dev/sda: see.1 gb. 566167862616 bytes
255 heads, 63 sectors/track, 66861 cylinders To create or APM: not present
units - cylinders of 16665 • 512 - 8225286 bytes
Disk identifier: 6x66066060 change partitions GPT: not present
Device Boot Start End Blocks Id Systen with fdisk, start it
/dev/sda1 1 26 204819- ee GPT
/dev/sda2 • 26 47773 383528984 at HFS / NFS* in interactive mode: Several choices for managing the parti­
/dev/sda3
/dev/sda4
47774
54786
magazincWacBuntuS |
47987
66779
1868668 83
48146865 83
Linux
Linux I Omit both the -I and
-s flags, and specify
tion table appear in the text mode menu.
For instance, choosing the p option prints
Figure 1: Listing the partition tables with fdisk. a drive, such as the partition table, whereas o first out­

30 LINUX SHELL HANDBOOK - 2023 EDITION


fdisk, gdisk, and parted CONFIGURATION

puts a security prompt and then creates a many common filesystems, including need to duplicate a partition in a new loca­
GPT table. The n option lets you create a ext4, FAT32, NTFS, JFS, UFS, XFS, and tion, perhaps to move a partition to a new
new disk-sized data partition. The w op­ Linux swap. The start and end parameters device in an attempt to free up space. At
tion writes the data (saves your changes) specify the location of the new partition the Parted prompt, use
from the gdisk session. on the disk; you do not have to use drive
Gdisk can convert MBR-partitioned geometry such as sectors, but you can cp </original/device> 7
hard disks to GPT, which removes the provide human-readable sizes expressed < ori ginalPart it ion> <t argetPart ition>
need to back up and restore existing par­ in megabytes.
tition content. Choosing r sends you to To remove a partition, use parted </some/ where /original/device is optional; if
the recovery and transformation menu, device> rm <N>, where <N> is the parti­ omitted, the current working device will
which offers options for converting your tion number. be assumed. Thus, the command
MBR disk to GPT. Gdisk can also convert Parted really improves on fdisk in its
from GPT to MBR. In some cases, this ability to move and resize partitions. For cp /dev/sdb 5 1
option will not work, so be sure to back variety’s sake, start Parted in interactive
up your data if you try it. mode before exploring partition manipu­ copies the/dev/sdb5 partition to/dev/hdbl.
lation. You still need a drive device ar­ If you accidentally delete a partition
GNU Parted gument, such as from the partition table or overwrite the
Fdisk is one of the older Linux tools, and partition table itself, entering
Gdisk is modeled after it. Increasingly, parted -i /dev/hdb
many users prefer GNU Parted. rescue <start> <end>
You can run parted in interactive or While in interactive mode, the device
non-interactive mode. The non-interac- given as an argument is assumed; you do initiates a search for filesystem signa­
tive syntax is parted </some/device> not need to include it in the commands tures on the disk. Parted searches a range
<command>. Running the command you type. To switch to a different device of sectors around the start and end posi­
within interactive mode, type tions for signs of the filesystem, so you
parted /dev/sda print do not need to be exact. If it finds a po­
select </some/other/device> tential filesystem in the appropriate loca­
prints the partition table found on the tion, Parted asks whether you want to
/dev/sda disk (Figure 2). The information at the Parted command prompt. create a new partition. For this rescue to
displayed is similar to fdisk’s. The resize command takes three argu­ work, the filesystem must be more or less
Providing the -i flag before the device ments: the partition number, the new intact; Parted can only recreate partition
and command arguments launches start location of the resized partition, and table entries - to fix filesystem corrup­
parted in interactive mode. Unlike fdisk, the new end location. To continue the tion, you need other tools.
however, you can create and modify par­ above example, running
titions in non-interactive mode as well. The LVM Alternative
One important difference between resize 1 0 1000 A Logical Volume Manager (LVM) is an
parted and fdisk and gdisk is that parted alternative to traditional partitioning that
commands take effect immediately; that at the prompt would resize the partition at treats the space on one drive - or even
is, when you create a new partition table, /dev/hdbl to begin at the start of the drive multiple drives - as a single unit and di­
the existing partition table (if any) on the and end at the 1000MB mark. vides it into logical volumes. GNU Parted
target drive is overwritten. This leaves lit­ You can use Parted both to grow and also works with LVMs.
tle margin for error when working with a shrink partitions. However, for ext2/3 file­ The use of LVMs may come at a price:
drive that has existing partitions and can systems, you cannot change the start loca­ Should a drive become corrupt, your en­
leave you hunting for recovery tools (for­ tion with a resize command, only the end. tire system suddenly can be inaccessible.
tunately, Parted can assist in that task, as That restriction does not apply to the By contrast, if you use traditional parti­
well). The command other filesystems that Parted supports. tions, especially for /home, you might be
Parted can move a partition to a new able to recover data by booting from a
parted </some/device> mklabel <type> free location on a drive with the move Live device after the root or boot parti­
command. The syntax is tion crashes. You should research the dif­
creates a new partition table on the speci­ ferences between LVMs and traditional
fied device. You must specify the partition move <partitionNumber> <start> <end> partitioning carefully before deciding
table type; for Linux, a widely used type which to use. ■
is msdos, although Parted supports several although <end> is
others. To create a new partition, use: optional. If omit­
File Edit View Terminal Help
ted, the partition is magazine@HacBuntu:~S sudo parted /dev/sda print
parted </some/device> P moved to the new [sudo] password for magazine:
Model: ATA Hitachi HTS54505 (scsi)
mkpart <partition_type> P location in its origi­ Disk /dev/sda: 590GB
Sector size (logical/physical): 512B/512B
<filesystem_type> <start> <end> nal size. If an end­ Partition Table: gpt
ing point defines a
Number Start End Size File system Name Flags
where partitionjtype is primary, extended, new size for the 1 20.5kB 210MB 210MB fat32 EFI System Partition boot
2 210MB 393GB 393GB hfs+ Untitled
or logical. For primary or logical parti­ partition, Parted 3 393GB 394GB 1094MB ext3
tions, you must also specify filesystem_ automatically re­ 6 394GB 394GB 1000kB bios grub
7 394GB 448GB 54.2GB ext4
type, the filesystem format that the par­ sizes as well as 8 448GB 451GB 2358MB linux-swap(new)
tition will hold. moves it. 4 451GB 500GB 49.3GB ext3
5 500GB 580GB 181MB linux-swap(new)
However, the mkpart command does When shuffling
magazine@HacBuntu:~$ |
not actually create the filesystem. To do and resizing parti­
so, use mkpartfs instead. Parted supports tions, you might Figure 2: Listing the partition tables with parted.

LINUX SHELL HANDBOOK- 2023 EDITION 31


CONFIGURATION Configuring Filesystems

Configuring filesystems with mkfs, df, du, and fsck mkfs -t ext4 /dev/sdal

This command uses the default block size,

BUILDER
inode parameters, and all other options,
some of which are determined at run time
when mkfs analyzes the geometry of the
disk partition. Using

Although most Linux distributions today have simple-to-use graphical mkfs -t ext4 -b 4096 /dev/sdal

interfaces for setting up and managing filesystems, knowing howto also creates an ext4 filesystem on /dev/
perform those tasks from the command line is a valuable skill. We'll sdal, but it forces the use of 4096-byte
blocks. Running
show you how to configure and manage filesystems with mkfs, df,
du, and fsck. BY NATHAN WILLIS mkfs -t ext4 -b 4096 7
- J device=/dev/sdbl /dev/sdal

inux supports a wide array of file­ where < filesystem_type > is a Linux- creates the same filesystem as the pre­

L system types, including many that


originated on other operating sys­
tems. The most common choices for
hard disks, however, remain the native
supported filesystem type (e.g., ext3 or
XFS) and < /the/device > is the location
of the target disk partition (e.g., /dev/
sdal or /dev/sdc3). Filesystem-specific
ceding command, but it creates the jour­
nal on a separate partition (/dev/sdbl~).
To create an XFS partition on /dev/sdal,
enter the following mkfs command:
Linux ext3/4, followed by the high-per­ options are added after < filesystem_
formance XFS and Btrfs filesystems. For type > (see also the “Filesystem Op­ mkfs -t xfs /dev/sdal
compatibility, knowing how to work tions” box).
with the VFAT filesystem is important, The basic form of the command de­ To specify the use of 4096-byte blocks on
because it is the standard choice found scribed in the previous example hands this filesystem, use
pre-installed on many media, including off creation of the filesystem to one of
USB thumb drives and flash disks. Addi­ several specialized utilities, depending mkfs -t xfs -b size=4096 /dev/sdal
tionally, several of the same utilities on the filesystem type you specify (e.g.,
used to manage normal filesystems also mkfs.ext3, mkfs.xfs, or mkfs.vfat). Be­ which is a different syntax than that
apply to swap partitions, which the cause filesystems differ so much from used for ext4. The following command,
Linux kernel uses as virtual memory each other, having specialized tools which uses the alternative (and now
when RAM is scarce. maintained by experts in the individual preferred) mkfs.*
filesystems results in more stable code.
mkfs Most of these utilities implement the mkfs.btrfs -L mylabel </dev/partition>
The mkfs command (Figure 1) creates a same options, although they vary accord­
new filesystem on a specified block de­ ing to the features implemented in the creates a Btrfs filesystem with a 16-KiB
vice, such as a partition on a hard disk. different filesystems. According to the default block size (where lOOOKiB =
The basic usage is: mkfs man page, the general form of the 1024KB). To create a partition with a 4KiB
command is now depracated in favor of block size, use:
mkfs -t <filesystem_type> </the/device> these type-specific mkfs. * utilities.
Despite the differ­ mkfs.btrfs -L mylabel -1 4k 7
ences, a few key op­ < /dev/part ition>
tions are common
to all mkfs. * utili­ The variations in syntax make it espe­
ties. Adding the -c cially critical to refer to the man page
flag checks the for more on the use of mkfs with spe­
specified device for cific filesystem options.
bad blocks, which
is then skipped over Routine Maintenance
during the filesys­ Running out of space on a filesystem is
tem creation step. one of the most common problems you
Adding the -v or -V are likely to encounter on a Linux sys­
flags produces ver­ tem, and it is not just an inconvenience
bose or extremely for storage reasons - the system’s use of
verbose output, re­ temporary files means that a full or
spectively. nearly full root filesystem could interfere
with normal operations.
mkfs To check filesystem usage, use df (Fig­
Examples ure 2). When given no arguments, df re­
To format the first turns a table summarizing usage of all
partition of the of the mounted filesystems - in kilo­
Figure 1: The simulated mkfs commands for XFS and ext3 differ. (The first drive on a sys­ bytes and as a percentage of each file­
-N and -n flags specify a simulation, which does not actually create a tem as ext4, you system’s total size. To get a report for a
filesystem.) The -f and -F flags tell mkfs to force filesystem creation, would run the particular filesystem, specify it as an ar­
even if it detects a filesystem already in place. command: gument, such as df /dev/sdal.

32 LINUX SHELL HANDBOOK - 2023 EDITION


Configuring Filesystems CONFIGURATION

Also, you can pass a file name as an ar­ Filesystem Options


gument, and df will report on the filesys­
tem that contains the specified file - which The mkfs.<fstype> utility, where <fstype> Larger block sizes can improve disk
could be handy if you don’t remember is a filesystem supported by the com­ throughput because the disk can read
where a particular filesystem is mounted. mand (e.g., ext3, ext4, XFS, Btrfs, VFAT), and write more data at a time before
Finally, a few options exist to make df supports options that tweak filesystem seeking to a new location; however, a
more useful: -i reports inode usage instead settings such as the size of blocks used, large block size can waste space in the
of block usage of the filesystem(s); -I lim­ number and size of inodes, fragment presence of many small files, because a
size, amount of space reserved for use full block is consumed for each fragment
its the report to local filesystems only;
by root-privileged processes, amount of of a file, even if only a small portion of it
-type = < filesystem_type > and -ex-
space reserved to grow the group block is used. Ext3/4 and XFS allow you to
clude-type = < filesystem_type > allow
descriptor if the filesystem ever needs to
you to limit or exclude output to a particu­ specify the block size (1024, 2048, 4096,
be resized, and settings for stripe, stride,
lar filesystem type. etc.) by adding a -b flag; the syntax that
and other details required for using the
On discovering a nearly full filesystem, filesystem in a RAID array. follows the flag varies, so consult the
you can further explore space usage with manual pages for each option.
du. Executing du </some/directory> re­ All of these parameters have default set­
tings, and unless you are sure you need The mkswap command creates a swap
turns a list of the disk space occupied by area on a disk partition, just as mkfs
to change them, you can safely create a
each subdirectory beneath </some/direc- creates a filesystem. The basic syntax
filesystem with the default settings. Nev­
tory>, expressed in kilobytes. Adding the -a is the same, mkswap </the/swap/de-
ertheless, it is a good idea to familiarize
option tells du to report the space used by yourself with the basics of filesystem pa­ vice>, with the optional -cflag again al­
the files in addition to the directories. rameters in general, in case you ever run lows you to check the partition for bad
Both commands are recursive. If you do into problems. blocks before creating the swap area.
not provide a directory as an argument to Just as a new filesystem must be at­
The block size is the size of the chunks
du, it reports on the current directory. The tached to Linux's root filesystem with
that the filesystem uses to store data - in
-c option produces a grand total in addi­ mount before you can use it, a new
a sense, it is the granularity of the pieces
tion to individual usage statistics. Other swap partition must be attached with
into which a file is split when stored on
helpful options are -L, which could help the disk. swapon -L </the/swap/device>.
track down an errant large file, following
all symbolic links; -x, which limits the
scope of the search to the current filesys­ command defragments the entire filesys­ others, it can be called in non-interactive
tem only; and -max-depth = N, which al­ tem verbosely. No such utilities exist for mode for use in scripts, and it can mark
lows you to limit the number of recursive ext3, but ext4 has e4defrag. bad clusters automatically to prevent
subdirectories into which you descend. their reuse in the future. The -V flag tells
This option is very helpful when dealing Troubleshooting fsck.vfat to run a second check after it
with a large file library. If you suspect trouble on a filesystem, you has tried to correct any errors.
Several utilities exist to help you get can run XFS has separate error-checking and
better performance out of your filesys­ repair utilities: xfs_check and xfs_repair
tems. The tune2fs program lets you con­ fsck /a/<device> (see the man pages for more on com­
trol many parameters of ext2, ext3, and mand-line options).
ext4 filesystems. You can set the number to check and make repairs. If you run fsck For ext2/3/4 problems, the debugfs tool
of mounts between automatic filesystem with no target device specified, it will run lets you examine a filesystem and correct
integrity checks with tune2fs -c N, set checks sequentially on all of the filesys­ errors interactively. It can step through
the maximum time interval between tems in /etc/fstab. and work within a filesystem with com­
checks with tune2fs -i N[d\m\w] (where The filesystem-specific error-checking mands similar to those of a typical Linux
d, m, and w are days, months, and programs - e2fsck for ext2, ext3 and ext4, shell, such as cd, open, close, pwd, mkdir,
weeks, respectively), or add an ext3 or btrfsck for Btrfs, and fsck.vfat for VFAT - and even chroot. ■
ext4 journal to a filesystem that does not support many of
have one with tune2fs -j. Additionally, the same options,
you can adjust RAID parameters, journal but again, the syn­
settings, and reserved block behavior, as tax may vary, so it
well as change parameters manually, is critical to read
such as the time last checked and num­ the man page for
ber of mounts, which are usually re­ the filesystem
ported automatically. checker before at­
Other utilities are associated with spe­ tempting any re­
cific filesystems. Btrfs has a separate util­ pairs.
ity for resizing filesystems (btrfs filesystem When cor­
resize). The btrfs-convert tool can migrate rupted, VFAT file­
data from existing ext2/3/4 volumes to systems suffer
the Btrfs filesystem. from bad clusters,
XFS also provides a defragmentation bad directory
tool called xfs_fsr that can defragment a pointers, and even
mounted XFS filesystem, and Btrfs sup­ bad file names.
ports defragmentation of metadata or en­ The fsck.vfat tool
tire filesystems. The can find and cor­
rect many of these Figure 2: The results of a df command showing disk usage on a Live
btrfs filesystem defragment -r -v / problems. Like the system. The -a flag includes "dummy" filesystems like /proc.

LINUX SHELL HANDBOOK- 2023 EDITION 33


CONFIGURATION mount and fstab

Media access with mount and fstab A number of optional parameters aside,
you have to specify the device file and the

MOUNT UP
mountpoint. If you call mount without
supplying any parameters, the command
tells you, among many other things, which
media are currently mounted (Listing 1).
Additionally, mount tells you about
We examine tools for mounting and unmounting storage media.
the filesystems for the devices, and it lets
BY HEIKE JURZIK AND JOE CASAD you know what mount options are in
access to various devices and filesys­ place. The /dev/sdal partition has been
inux attaches media directly to the

L
tems, you need to create a link between formatted with ext4 and mounted as the
directory tree in a process known as
a device and a directory in the filesys­ root partition (at /); the CD drive con­
mounting. Device files for devices
tem tree. The mount command (or the tains ISO 9660 media (the default filesys­
of all kinds - network, removable media,
equivalent systemd mount process) as­ tem for data CDs) and has been
hard disk partitions - can typically be
sociates a device with a directory. mounted under /media/cdromO.
found below the /dev (device) directory.
The listing also tells you if the hard
Many modern Linux systems handle the Mounting disk partitions are readable and writable
mounting process automatically. Your hard
Mounting occurs at boot time or manu­ (rw for “read-write”). The information
drives, CDs, and USB sticks just appear in
ally at a later stage. Hard disk partitions
the desktop GUI, and you can navigate errors=remount-ro
are normally mounted at boot time;
to the data without the need for explicit
USBs, CDs, DVDs, and other removable ensures the media will be remounted
mounting commands; however, the classic
media used to be mounted manually read-only; that is, the data will be read­
Unix/Linux mount system is still useful for
and were often in the domain of the able but with no write access.
troubleshooting or when working with
system administrator (root), unless the
systems that don’t offer udev support.
privilege was specifically given to users Mounting Removable Media
This article describes how to mount
(see the section titled “Tabular: /etc/ Data CDs/DVDs, floppy disks, and USB
and manage storage resources using
fstab"). Nowadays, most of these de­ media are normally mounted automati­
mount, amount, and the fstab file. Sys-
vices are autodetected and are mounted cally when you plug them in. If your
temd environments offer an alternative
automatically or at a user prompt. system does not automount or you’re
option for mounting using systemctl (see
However, if you have trouble or need working on the console, run mount
the box entitled “Mount and Systemd”).
a little more control, the utility used to manually. Linux assigns directories
Name Game mount from the command line is mount. below /mnt or /media for removable
IDE device names (names of hard disks,
CD-ROMs, or DVD drives) start with sd Mount and Systemd
(the “s” refers to the SATA interface used The systemd init environment used on the file - with hyphens replacing
for most modern mass storage); the let­ most modern Linux systems lets you cre­ slashes. For example, if the mount point
ter that follows depends on the connec­ ate a systemd unit file and then reference is /media/backup, the name of the unit
tor and the order. The first drive is sda, the file to mount the resource. See the file must be media-backup.mount.
the second sdb and so on. "Systemd" article for more on creating a The format for an automount unit file is
Linux handles USB mass storage de­ systemd unit file. similar, systemd.mount and systemd.
vices, SD cards and so on as SCSI de­ Systemd supports both the mount [1] and automount support several other unit
vices. Their device filenames also starts automount units [2]. A mount unit mounts file options. See the documentation on­
when executed (either at startup or manu­ line [1 ]. Once you create the unit file, you
with sd. CD and DVD drives tend to be
ally from the command line). An automount can mount and manage the resource
listed as sr, and floppy disk drives are fd. unit automounts on demand when a user using systemctlcommands:
Besides the letters, many devices attempts to access the resource. As with
# systemctl daemon-reload
have numbers that reflect the logical other systemd units, the extension on the
# systemctl start unit_file_name
structure of the storage media (e.g., the filename indicates the file's purpose. For ex­
first primary partition on an SATA hard ample, the filename for a mount unit would You can also use the systemd-mount com­
have the form: unit_file_name.mount. mand to mount the resource, or use sys-
disk attached to the first controller is
A mount unit file should contain a [Mount] temd-umountto unmount.
sdal, the second partition is sda2, etc.).
section with the following basic options: Systemd continues to support the/etc/
Logical partition numbers start at 5.
• W/?ar=-path, partition name, or UUID fstab file as described in this article. The
The second logical partition on sdc thus fstab file serves as an alternative means
maps to the device file /dev/sdc6. for a device, partition, file, or other re­
source you wish to mount for configuring mount units in systemd.
The system enumerates SCSI CD/DVD Mounts listed in fstab will be converted
• Where=-absolute path of the mount
drives in the same way (srO, srl, etc.), to native systemd mount units at
point
along with floppy drives (fdO, fdl, etc.). startup. Recent Linux systems include
• Type=- (optional) the filesystem type some additional fstab mount options
Many distros use aliases such as /dev/
You must name the mount unit file for that will pass unit file settings directly
cdrom or /dev/dvd that point to the
the path to the mount point specified in to Systemd [3].
names for CD/DVD drives. To support

34 LINUX SHELL HANDBOOK - 2023 EDITION


mount and fstab CONFIGURATION

media. In the command line, you need Combinations are also supported: To re­ automatically dismounts mounted media
to type the device file name and the move write access for media mounted with at shutdown, you can also unmount de­
mountpoint. read-write access, supply two parameters vices manually, including removable CD-
When you mount a USB mass storage when running the command; for example, ROMs/DVDs, floppies, and USB devices:
device, check the /var/log/messages or
mount -o remount,ro /media/usb amount /media/usb
/var/log/kern.log logfiles to see if the de­
umount /media/cdromO
vice has been detected correctly and to tells mount to remount the media and at
discover the device file name. To mount the same time disable write access (ro). USB media and floppies must be un­
the device detected, sdc, in an existing To test an ISO by mounting a 1:1 copy mounted before you remove them. CD
directory, /media/usb, type: of the image before burning, enter: and DVD drives block automatically
and refuse to open the drive bay while
mount /dev/sdcl /media/usb mount -o loop file_name.iso /mnt/tmp a disk is mounted.
Linux typically autodetects the filesys­ which uses a loop device to access the An additional safety mechanism is
tem type for media. If you get an error image. that umount will not unmount a filesys­
message, you can explicitly specify the tem while a process is accessing the
filesystem by supplying a value for the Tabular: /etc/fstab files. A program might be using the data
-t parameter - for example, Linux mounts some filesystems directly at on the CD in the drive, or the data might
boot time. The /etc/fstab file (see Figure 1) be part of the working directory used by
mount -t vfat /dev/sdcl /media/usb has entries for the filesystems to mount. the shell or a file manager (i.e., /media/
The fstab file used to contain config­ cdromO) or one of its subdirectories. To
for an older Windows filesystem on FAT-
uration information for the full set of determine which process is blocking the
formatted media. Besides vfat (for the
hard disk partitions in addition to the device, run Isof, which displays open
DOS/Windows filesystem), the sup­
various removable media. But, remov­ files and directories, as root against the
ported values are ext2 (extended filesys­
able media are now managed by the device name of the drive, as in Listing 2.
tem version 2), ext3 (extended filesys­
udev subsystem, which allows regular If Isof does not tell you what the com­
tem v3), ext4 (extended filesystem v4),
users to mount and unmount them mand is, it will tell you the PID (process
reiserfs (Reiser filesystem), iso9660 (ISO
from the command line or desktop. number). You can then use the ps tool
9660), ntfs (NT filesystem), and so on.
The first column is the device file, and output a list of all processes in wide
Most systems define the device names
UUID, or label, and the second is the display mode, pipe the output to grep,
and mountpoints for CDs/DVDs and and search the output for the process ID:
floppies, so a command such as mountpoint. The other entries specify
the filesystem for the media (the kernel ps auxwww | grep 23884 7
mount /media/cdrom normally autodetects this - auto), and paul 23884 0.3 1.2 804532 7
might be all it takes to mount a CD. various mount options. 76544 ? SI 22:36 0:00 7
Often you see entries such as user /usr/bin/gwenview /run/media/
Critical Mount Options (the device can be mounted without paul/Ubuntu 15.04 amd64/P
The -o ro option for mount makes a device root privileges), nouser (the opposite), ubuntu/pics/blue-lowerleft.png 7
“read-only.” Its counterpart, as well as the auto (mounted at boot time), noauto, -caption Gwenview —icon gwenview
default setting, is -o rw (for “read-write”). exec (executable), or noexec. If you
In this case, it looks like Gwenview is
want to modify the /etc/
the culprit. If you close the image viewer
fstab file, you must be­
window showing the pictures on the CD
come root.
content, you should be able to unmount
Out! the CD with:
To unmount filesystems, umount /media/cdromO
use the command
amount. Although Linux If this command doesn’t help, you might
have to be more assertive and use the
kill command. ■
Zdev/disk/byid/ata-ST9750-l23AS_6WS0Q7JM-part 1 swap defaults
Zdcv/dlsk/by-ld/ata-si9ZbH423AS_6wsev7JM-part2 Z acl,user_xattr
Zdev/diskZby-idZata-ST9750423AS_6WS0Q7JM-part3 Zhoae
proc
sysfs INFO
debugfs ZsysZkcrnelZdcbug
ZprocZbusZusb [1] systemd.mount:
devpts Zdev/pt s node=0620,gid=5
ihora:Zho«eZlnmsZcommon ZhomeZpaulZDocumontsZZcomnon nfs rsize=Bifl2,w»ize=ai02,nosuid o o
https://www. freedesktop. org/software/
zhorcZhoaeZlnms ZhomcZpaulZbocumentsZZlnms nfs rsize=8i92,wsize=8192,nosuid o o systemd/man/s ystemd.mount.html
Figure 1: The fstab file provides information on hard disk partitions. [2] systemd.automount: https://www.
freedesktop. org/software/systemd/
man/systemd. automount.html#
Listing 2: Isof/dev/sdd1 [3] systemd.mount Manpage with fstab
# Isof /dev/srO Mount Options: https://manpages.
COMMAND PID USER FD TYPE DEVICE SIZE/0FF NODE NAME debian.org/testing/systemd/systemd.
gwenview 23884 paul cwd DIR 11,0 2048 4096 /run/media/paul/Ubuntu 15.04 amd64/pics mount.5.en.html

LINUX SHELL HANDBOOK- 2023 EDITION 35


CONFIGURATION Time Tools

Cal, date, hwclock, and NTP

TIME WARP
I'm late, I'm late, for a very important date. For many

applications, it is important that your PC has the correct

time and time zone. We'll show you howto keep your PC

clock ticking and how to use NTP to synchronize the time

with a time server on the web. BY HEIKE JURZIK

n incorrectly set PC clock can be process of setting the clock by synchro­ -y flag produces a year calendar (Fig­

A disastrous - if your computer


loses track of the time, you
nizing your own timekeeper with a
server on the web via the Network Time
could end up juggling files from the fu
ture or email from 30 years ago. The
­
Protocol (NTP).
ure 2).
To output a specific month, you need
to pass the month to cal in the form of a
two-digit number for the month and a
time warp could lead to misunderstand­ Command-Line Calendar four-digit number for the year. By de­
ings, errors, or even crashes. If you call the calendar with cal and fault, cal will output the calendar in the
Almost all Linux distributions set the without parameters, the program dis­ language defined in the LANG environ­
time and time zone during the installa­ plays the current month of the current ment variable.
tion phase, and desktop environments year; the current day is highlighted. If you prefer the time format for any
such as KDE and Gnome display a clock The -3 option tells cal to show you the other language, but would like to keep
in the panel to give users quick access to previous and next months as well; the output from all other programs in the de­
tools for configuring the computer clock
(Figure 1). B Mon Feb 25,11:50 AM O petronella

In the shell, cal displays a simple


but neatly formatted calendar. The
date command gives you the date and
time, although the output itself is
fairly sparse. Additionally, this pro­
gram can help the administrator set
the date and time. The date tool also
demonstrates its potential in combina­
tion with other command-line tools
and in scripts, for example, when pro­
grams generate file names that con­
tain the current date.
The hwclock tool helps to synchronize
the system time and the hardware clock.
Of course, you will need to be root to
run this program.
If your machine has a permanent In­ Figure 1: Many GUI desktops let users right-click the clock in the panel to access the date and
ternet connection, you can automate the time settings.

36 LINUX SHELL HANDBOOK - 2023 EDITION


Time Tools CONFIGURATION

fault language, you can set the LC_TIME • joe<3>joe-lnspiron-S570: ~


variable to tell cal to use the language of File Edit View Search Terminal Help
your choice. 2019
January February March
The following example sets the date Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
and time output to English: 1 2 3 4 5 1 2 1 2
6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9
13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16
LC_TIME=C cal -y 20 21 22 23 24 25 26 17 18 EE20 21 22 23 17 18 1920 21 22 23
27 28 29 30 31 24 25 2627 28 24 25 2627 28 29 30
31
Of course, this command isn’t necessary April May June
if your default language is already Su Mo TuWe Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 12 3 4 1
English. 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
14 15 1617 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
21 22 2324 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22
What's the Time? 28 29 30 26 27 28 29 30 31 23 24 2526 27 28 29
If you type date at the command line, 30

you will see the date, time, and also the July August September
Su Mo TuWe Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo TuWe Th Fr Sa
time zone: 1 2 3 4 5 6 12 3 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21
$ date 21 22 2324 25 26 27 18 19 20 21 22 23 24 22 23 2425 26 27 28
Tue Feb 19 15:23:41 CST 2019 28 29 3031 25 26 27 28 29 30 31 29 30

October November December


The date command also references the
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
LANG variable to set the language, and it 12345 121234567
6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
can also be influenced by setting LC_ 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
TIME just like cal. 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
Date is even more flexible if you set
the TZ (time zone) variable with the joe@joe-Inspiron-5570:~$

command. Check your /usr/share/zo- Figure 2: With Cal, you can display a calendar for the whole year at the console.
neinfo/ directory to find out which time
zone values your computer supports $ TZ=America/New_York date (man date) for a complete list of the
with TZ. Tue Feb 19 16:27:24 EST 2019 options.
To find out the time in New York, for These formatting options are particu­
example, you simply run the following If you happen to live in Australia and larly practical if you use date to generate
command: need to phone friends in New York on a file names made up of date, time, or
regular basis, you might want to set up both values automatically.
Table 1: Date Command- an alias for the last command to make it The command
Line Parameters easier to check the time before you call.
Meaning
To set up an alias, just add the follow­ tar -cvjf backup_$P
Parameter
ing line to your Bash configuration file, (date +%d_%m_%Y).tar.bz2 *
%M Minutes (00 to 59)
~/.bashrc
%H Hours, 24-hour clock creates a Bzip2 compressed tarball
%l Hours, 12-hour clock alias NY=1TZ=America/New_York date1 with a name comprising the text string
%a Weekday, short form backup_, the date (that is the day,
and re-parse the settings after saving them month, and year separated by under­
%A Weekday, long form
by giving the source ~/.bashrc command. lines), and the file extension .tar.bz2 (for
%d Day as two-digit number Then, you can simply type NY at the com­ example, backup_05_ll_2009. tar. bz2).
%b Name of month, short form mand line to output New York time.
%B Name of month, long form
Setting the System Time
Formatted Output The root user can use date to set the time
%m Month as two-digit number
The date program has a large number and date for a machine. To do so, use the
%y Year as two-digit number of parameters that influence the output -s option followed by a string that con­
%Y Year as four-digit number format. You can format the date output tains the new time (see the next section,
%D Four-digit date (mm/dd/yy) with a plus sign, followed by a percent “Everything is Relative”). Before you
sign, and a letter. For example: enter the following command, make sure
%T Time in 24-hour clock
that all NTP components have been unin­
%r Time in 12-hour clock $ date +%Y_%m stalled (see the “Automated” section):
%t Tabulator 2019_02
%n Line break # date -s "19 Feb 2019 16:20"
Table 1 lists some of the more common # date
°/o% % sign
options; you can refer to the man page Tue Feb 19 16:20:03 CST 2019

LINUX SHELL HANDBOOK- 2023 EDITION 37


CONFIGURATION Time Tools

The first three parts of this are manda­


tory; if you leave out the year, date will
just default to the current year.
Other format options let you set the
date with seconds' precision. For this in­
formation, enter man date and study the
date string examples.

Everything Is Relative
As an alternative to the absolute date
and time, the date tool also under­
stands relative values and even has a
couple of predefined strings to help
you:
• yesterday
• tomorrow
• today
• now
• sec{s)/second (s)
• min{s) /minute{s)
• hour{s)
• day(s) Figure 3: To access documentation conveniently, use the info command at the command line.
• week{s) This information is the output of 'info coreutils date'.
• fortnight
• month{s) The hwclock program lets you read Internet, or you could use a manual
• year{s) and set the hardware clock; the com­ command in the shell.
Additionally, date understands concepts mands all require root privileges. When In the pre-Systemd era, most major
such as ago, so you can say day ago in­ used in combination with the -r option, Linux distributions had packages
stead of yesterday. you can display the local hardware time: available for enabling NTP support.
If you use one of these strings to set Many of those packages still exist -
the time, you must specify the -s para­ # hwclock -r see the documentation for your own
meter like so: 2019-02-19 15:44:09.49830-0500 Linux distribution to learn about NTP
package options.
# date -s '+3 mins' Additionally, hwclock has options for Systemd provides a built-in sys­
setting the system time to reflect the temd-timesyncd service that performs
To display a relative time, you need the hardware clock time {hwclock -s) or vice basic time synchronization duties. To
-d parameter instead: versa {hwclock -w). check whether the service is running on
A combination of -set and -date sets your system, enter:
# date -d '+S days -2 hours' a specific time. You need to enter a string
Sun Feb 24 13:14:18 CST 2019 to describe the new date and time after systemctl status P
the -date parameter. The format is ex­ systemd-timesyncd.service
The date information page tells you actly the same as the date program’s -s
more about strings and how to use option. The command The systemd-timesyncd service is like
them. To read the documentation at the other Systemd services. You can start,
command line, use info coreutils date # hwclock —set --date="+2 hours" stop, or restart it using a variation of the
(see Figure 3). systemctl command:
sets the hardware clock to a time two
Setting the Hardware Clock hours in the future. systemctl restart P
In addition to the software clock, your systemd-timesyncd.service
computer has another timekeeper, and Automated!
this one will continue to count down Network Time Protocol (NTP) is a stan­ See the article on Systemd elsewhere in
the days when your computer is dard for automating the synchronization this issue, or consult the systemctl man
switched off and even when it is not of clocks in computer systems [1]. The page, for more on managing Systemd
plugged in. time signal propagates over the network services. ■
To ensure uninterrupted timekeeping, from an NTP server to a client, and you
computer mainboards have a battery- can configure the point in time when INFO
buffered clock, referred to as the CMOS your Linux machine’s NTP client con­ [ 1 ] NTP: http://en. wikipedia.org/wiki/
clock, RTC (Real-Time Clock), BIOS tacts a server on the network. This could Network- Ume_Protocol
clock, or even hardware clock. be at boot time or when you get onto the

38 LINUX SHELL HANDBOOK - 2023 EDITION


Users, Groups, and Permissions MANAGEMENT

The third and fourth fields are still the


permissions to users and groups
UID and the GID of the group to which
the user belongs, but the fifth field, which
once stored additional information about
a user, such as a full name and phone
number, now either points to a subdirec­
tory of /mn/systemd or oi/var, which
provides resources for systemd. The

INTED!
sixth field, can still list the user’s shell,
but /sbin/nologin is more likely to be en­
tered than in the pre-systemd days.
The /etc/shadow file has preserved its
original functionality (Figure 2). The
T. . „ ... . . . , .
The shell comes with some simple commands for managing first field in each line is the username,
and the second is the encrypted pass­
users and granting access to system resources.
word - or a placeholder if the user can­
BY MATT SIMMONS, JOE BROCKMEIER, HEIKE JURZIK, not log in. The third through fifth fields
BRUCE BYFIELD, AND JOE CASAD are used for controlling passwords -
showing the age of the password, the
minimum age before the password can
sers and groups are concepts Files for Users and Groups be changed, and the maximum time be­

U central to multiuser operating


systems. Assigning a name to a
Users are defined on one line in /etc/
passwd and a corresponding line in /etc/
user account allows users to log in sepa
rately, set up their own environments,
shadow;
­ memberships in groups are de­
fined in /etc/group. Each user is assigned
fore a password must be changed. The
sixth field is supposed to define the
number of days before a password ex­
pires that the user will receive a warn­
and control access to their private files a unique identifier, called the user ID ing, the seventh field defines the number
by assigning permissions. (UID), and each group is assigned a of days after expiry that the account will
Strategies for applying users and group identifier, referred to as the GID. be disabled, and the eighth field is left
groups have changed through the Valid UIDs and GIDs are integers from blank for future purposes.
years, but essentially, a group is a col­ zero to 2A32 - 1, although the maximum The use of /etc/group has also changed
lection of users typically assigned ac­ recommended is 65535. over the years. Each group is defined in
cess to a collection of resources associ­ UIDs between 0 and 999 are generally a single line of four fields (Figure 3). The
ated with a specific function or profile. reserved for system accounts. The root ac­ first is the group’s name, which is usu­
For instance, the financial group might count typically has a UID of 0 and belongs ally self-explanatory. The name is fol­
be assigned access to a common direc­ to a group also known as root, which is as­ lowed by a field for a group password,
tory with financial documents or ac­ signed a GID of 0. By default, most Linux which these days is almost always
cess to the printer located in the finan­ distributions number user accounts from marked by an x, because the custom is
cial office. 1000, which is assigned to the user ac­ to rely on user passwords. The third field
On home systems with only a few count created during installation. is the GID, and the fourth is a comma-
users, groups sometimes matter so little The/etc/passwd file is readable by separated list of users.
that users mostly ignore them. In fact, every user of the machine. Because allow­ When you install most distributions, the
you can sometimes hear suggestions that ing users to view even encrypted pass­ ordinary user account created at installa­
groups are obsolete and should be elimi­ words is a security hazard, passwords tion is added automatically to the groups
nated. However, on networks, groups are were long ago removed from /etc/passwd that an average desktop user might need,
a means of exercising the security princi­ to /etc/shadow, which only the superuser such as cdrom or sudo. When you add a
ple of least privilege: restricting access to can view. In fact, with the introduction of user account, the user is typically added to
data and functions only to those who re­ systemd, /etc/passwd has become even the same groups assigned to the user ac­
quire them. Modern Linux systems have more limited. Each account continues to count created at installation. You can also
GUI-based utilities for managing users be defined in six colon-separated fields add a user to a group directly by opening
and groups, but many experienced users (Figure 1), starting on the left with the /etc/group in a text editor as root.
still prefer the swift and decisive Bash username. The second field is now always
commands. marked with an x, which originally indi­ daemon:*:15434:0:99999:7:::
cated that the ac­ bin:*:15434:0:99999:7: : :
root:x:0:O:root:/root:/bin/bash count could be sys:*:15434:0:99999:7:::
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin used to log in, but sync:*:15434:0:99999:7:::
bin:x:2:2:bin:/bin:/usr/sbin/nologin games:*:15434:0:99999:7: : :
now it seems to
sys:x:3:3:sys:/dev:/usr/sbin/nologin
indicate that the Figure 2: /etc/shadow contains encrypted
sync:x:4:65534:sync:/bin:/bin/sync
field is governed passwords where they exist, but many of its
Figure 1: The /etc/passwd file under systemd. by systemd. fields are no longer used by many users.

LINUX SHELL HANDBOOK- 2023 EDITION 39


MANAGEMENT Users, Groups, and Permissions

passwd USER, authenticating with the use finger, adding a user after the com­
root:x:0: current password before changing it. mand for specific information.
daemon:x:1: If you want to disable a user account As you edit an account,
bin:x:2: rather than delete it, the easiest solution
sys:x:3: is the command usermod OPTIONS USER

adm:x:4:logcheck passwd —expire 1 USER should take care of most circumstances.


Figure 3:/etc/group remains useful, but it is For example, you can change the name of
also a repository of obsolete groups. This command sets an expiry date in the an account with the option -I NEWNAME,
past, automatically making the account un­ the home directory with -d DIRECTORY,
Adding, Locking, and available. It is preferable to passwd -I, be­ the expiry date with -e DATE, or the num­
Removing cause it not only prevents a normal login, ber of days after the expiry date that the
The command for adding users is run but also a login by ssh. When you want to account is disabled with -f NUMBER; bet­
from the root account: restore the account, use passwd -u USER. ter yet, combine the two options.
When you decide to delete an account, The groupmod command performs most
adduser OPTIONS USER first transfer any information you want to of the functions of usermod, but for groups
save from the home directory. To delete a (e.g., change the group name with -n or
The adduser command calls the useradd user account, log in as root and type: the GID with -g). If you are using a
utility. You can also call useradd directly chroot jail (an isolated directory struc­
from the command line on most Linux userdel USER ture), you can also use -R to create a new
systems, but adduser is a bit more user /etc/group using the configuration of the
friendly. If you no longer need the home direc­ jail. However, many users will likely find
By default, the user and a group with tory, add the -r option. However, you can usermod more handy than groupmod.
the same name are created. You are also use the -f option to delete the ac­
asked to type the password for the new count, even if the user is logged in. Note Permissions
account, and a home directory is cre­ that the command gives no output of its The whole purpose of users and groups is
ated with the same name as the ac­ progress; the only sign that the account to have a way to assign permissions. Gran­
count under /home (Figure 4). How­ has been deleted is when you return to ular access privileges for files and directo­
ever, you can use options to modify all the command line. ries make Linux a safe operating system.
these defaults, adding or changing the Similar commands, groupadd and The root user is subject to no restric­
default groups or the location of the groupdel, are available for editing groups. tions, and this includes assigning read,
home directory. You can also set the Generally the only groups you will want to write, and execute permissions to other
number of days before the account ex­ edit are those created for users. For pre­ users throughout the system. If you are
pires or set the account to use a shell defined groups that give access to hard­ the owner of a file or directory, you can
other than Bash. To save time, you can ware or functionality, it is usually better to grant access to these resources to other
also edit /etc/default/useradd to set the just take all the users out of an unused accounts. If you are also a member of a
default information created for new ac­ group rather than deleting the group itself. specific group, you can modify the group
counts. If you do delete a group, be aware ownership of files and folders for more
After you enter the password, you can that deleting the group does not change granular permission assignments to files.
add user information such as the Full permissions on any files. Before delet­ For every file (and thus for directories,
Name, Room Number, Work Phone, and ing a group, locate any files that the device files, etc.), Linux defines who
Home Phone, but many users simply group owns with the command may read, write, and execute that file.
press the Enter key to bypass these fields. Also, every file belongs to an owner and
Later, you can change the password with find / -gid GID to a group. The following three permis­
sions are assigned separately for owners,
root@nanday:/etc/default# adduser jack and change the groups, and other users:
Adding user jack’ ...
Adding new group jack' (1002) ... group permissions. • Read permission (r flag): Users can dis­
Adding new user jack' (1004) with group jack1 ... play the contents of a file or folder on
Creating home directory '/home/jack' ... Managing screen, copy the file, and do a few other
Copying files from /etc/skel' ...
Enter new UNIX password:
Users and things. Directories should additionally
Retype new UNIX password: Groups have the x flag (see below) to allow
passwd: password updated successfully Before editing a user users to change to that folder; other­
Changing the user information for jack
Enter the new value, or press ENTER for the default or group, make sure wise, only a list of files can be displayed.
Full Name []: that no one who is • Write permission (w flag): Users can
Room Number []:
logged in will be af­ change files and directories and store
Work Phone []:
Home Phone I]: fected by typing the their changes. Write permission also
Other []: w or who command. includes the ability to delete.
Is the information correct? [Y/n] |
If you want more de­ • Execute permission (x flag): For pro­
Figure 4: The adduser command sets up a basic account. tailed information, grams, this means that the user is permit-

40 LINUX SHELL HANDBOOK - 2023 EDITION


Users, Groups, and Permissions MANAGEMENT

ted to run the program. Execute permis­


sion for a directory means that the user is
permitted to change to the directory (the
user additionally needs read permission
to be able to view the folder content).
To discover the permissions for a file at the
command line, you can simply set the -I
flag with the Is command (Figure 5). Per­ missions for all) in place of the execute Permissions and Priorities
missions are indicated by the letters r (for flag to ensure that users are only allowed Permissions for the user, group, and all
read), w (for write), and x (for execute). In to modify - and thus delete - their others have different priorities. If you
the Is output, note the three sets of r, w, own data. The sticky bit is typically set are the owner of a file, permissions for
and x (or -) at the beginning of the file for /tmp (Figure 5). This stores tempo­ the owner apply (the first block of three
name entry. The first block shows the per­ rary files for multiple users. letters). If you're not the owner but be­
missions for the owner, the second block If everybody had the right to read, long to the group, the second block ap­
refers to the group, and the third block re­ write, and execute these files, in theory, plies. If you're neither the owner nor a
fers to all users. Folders are indicated by a everybody would be able to clean up the group member, the third set of permis­
sions apply.
d (for “directory”) at the start of the list, system and delete arbitrary data. The
regular files by a single dash (-), symlinks t bit ensures that users can only delete
by an I (for link), block devices like /dev/ their own files (or those files for which (See the “Permissions and Priorities”
sdal by a b, and character devices (e.g., they have write permission). The excep­ box for the hierarchy of permissions.)
/dev/tty1) by a c. tion to this rule is that the owner of the An equals sign lets you assign pre­
folder with the sticky bit is allowed to cisely the permissions specified at the
Special Permissions delete within that folder. command line. For example,
Linux has two special permissions: the s
bit (also known as the setuid/setgid bit) Modifying Permissions chmod ugo=rxw directory
and the t bit (also known as the sticky The chmod program lets you modify file
bit). Both replace the x in the nvx block and directory permissions, assuming you gives the owner, group members, and all
of three. The s is commonly seen with are the owner or the system administra­ other users read, write, and execute per­
executable files, whereas the t bit is tor. chmod lets you set the permissions missions for the directory. Instead of
more common with directories. using either letters or numbers. ugo, you could alternatively use a (for
The setuid/setgid (set user ID/set If you are using letters, u stands for all) to assign user, group, and other per­
group ID) bit executes a program with user (owner), g for group, and o for oth­ missions.
the permissions of the user or group, no ers (all other users). As I described pre­ The chmod program also under­
matter who runs the program. In this viously, r stands for read, w for write, stands numbers. Instead of specifying
way, nonprivileged users can access re­ x for execute, s for the setuid/setgid bit, the permissions with letters, you can
sources they would not normally be able and t for the sticky bit. pass in three- or four-digit octal num­
to access. Although this is a potential se­ A combination of these letters (with­ bers. The octal number is an ingenious
curity risk, the s bit has its uses. Many out spaces!) with plus, minus, and shorthand for referring to a binary
programs, including su, sudo, mount, or equals signs tells chmod to add, remove, number that spells out the rwx permis­
passwd rely on the s bit (Listing 1). or assign these permissions (Table 1). To sion bits (see Table 1). Calculate the
The passwd program, for example, mod­ give a group read and write permissions numbers as follows: 4 stands for read
ifies passwords, accessing the /etc/shadow for a file, just type chmod g + rw file. Re­ permission, 2 for write permission, and
file in the process of entering the new moving permissions follows the same 1 for execute permission; the first num­
password. By default, the file is protected pattern: The chmod o-rwx file command ber refers to the owner, the second
against write access by nonprivileged removes all permissions for all users number to the group, and the third to
users and reserved for use by the adminis­ who are neither the owner nor members all others.
trator to prevent just anybody having the in the owner group. You could combine
ability to manipulate the passwords. The these two commands thus: Table 1: Permissions
s bit executes the passwd program as the Octal Binary Letters
root user and enters the new password in chmod g+rw,o-rwx file
0 000
/etc/shadow “on
File Edit View Search Terminal Help 1 001 --x
behalf” of root.
magazinefgMacBuntui/S Is -tr 2 010 -w-
The other spe­ total 96
cial permission, I rwx rwx rwx 1 root root 30 2010-12-25 08:23 vnlinu z.old •> boot/vmli 3 (=2 + 1) 011 (=2 + 1) -wx
I rwx rwx rwx 1 root root 30 2011-01-27 16:14 -> boot/vmlinuz-
the t bit, com­ drwxr-xr-x 15 root root 4096 2010-10-07 12:38 var 4 100 r--
monly occurs in drwxr-xr-x 12 root root 4096 2610-04-15 12:35 usr
drwxrwxrwt 15 root root 4096 2011-62-04 11:09 tap 5 (=4+1) 101 (=4+1) r-x
shared directo­ drwxr-xr-x 12 root root 0 2011-62-04 11:68 sys
drwxr-xr-x 3 root root 4096 2010-09-09 17:08 srv
6 (=4 + 2) 110 (=4+ 2) rw-
ries (read, write,
and execute per­ Figure 5: Listing permissions at the command line.
7 (=4 +2 + 1) 111 (=4 + 2+1) rwx

LINUX SHELL HANDBOOK- 2023 EDITION 41


MANAGEMENT Users, Groups, and Permissions

On this basis, you can see, for exam­ chown petronella:audio FILE_NAME it (including the hidden configuration
ple, 644 would mean u = rw,go = r (re­ files) to user pooh:
sulting in rw-r-r--), or 777 would be The file now belongs to user petronella
a = rwx (resulting in rwxrwxrwx). and group audio. chown -R pooh /home/pooh
To set the s or t bit, you need to add a chown is mainly used by the root
fourth number at the start of the block of user, however, an ordinary user can use From the Beginning
three. The number 4 represents the s bit it for certain limited tasks, such as The umask program specifies the default
for the owner (setuid), 2 sets the 5 bit for changing the group membership for a permissions assigned to newly created
the group (setgid), and 1 sets the t bit. file the user owns to a group to which files and directories. Typing the umask
Listing 2 gives an example. the user belongs. command without setting any parame­
ters reveals the current setting:
Changing Group Across the Board
Memberships All three tools - chmod, chgrp, and $ umask
To change group membership for files chown - support the -R option for recur­ 0022
and directories, you can use the chgrp sive actions. If you want members of the
tool. As a “normal” user, you are al­ video group to access a directory and the The four-digit octal number that is re­
lowed to assign your own files to a spe­ files it contains, just type: turned specifies what to subtract from
cific group; however, this assumes that the default values (0666 for files, 0777
you are a member of the group. The root chgrp -R video DIRECTORY for directories). In other words, new files
user, as always, has no restrictions. are assigned 0644 (rw-r- -r- -), and new
The following command tells you your The -R option can also save you some folders are assigned 0755 (rwxr-xr-x)
own group memberships: typing in combination with the chmod when they are created.
command. To remove read, write, and To change the umask, enter the file
$ groups execute permissions from this folder for and specify the new value at the com­
petronella adm dialout fax cdrom 7 all users who are not the owner or mem­ mand line:
tape audio dip video plugdev fuse 7 bers of the video group, just type:
Ipadmin netdev admin sambashare umask 0077
chmod -R o-rwx DIRECTORY
In this case, the user called petronella This entry means that new files and direc­
may change access to her own files for Be careful when you run recursive tories are only available to their owner. To
members of the groups petronella, adm, commands that remove the execute make new files writable for group mem­
dialout, fax, cdrom, and so on. The flag. If you mistakenly type a-x instead bers, you can choose umask 0002 instead.
chgrp command first expects information of o-x, you will lock yourself out: The umask you assign in this way is
about the new group and then the name chmod will remove execute permissions valid for the current shell, but you can
of the file or directory. To assign a file to from the parent directory and your abil­ add an entry to your Bash configuration
the audio group, just type: ity to change the directory and modify file ^/.bashrc to make the change perma­
files (Listing 3). The use of the find nent. Don’t forget to run source ~/.bashrc
chgrp audio FILE_NAME command can help you avoid this kind to reload the Bash configuration file.
of dilemma (Listing 4). The find com­ To modify the umask for the system,
Changing Owners and mand first discovers the files (-type f) you will need to add a global entry to the
Groups in the test directory (and possible sub­ /etc/profile file, and you will need to
On a Linux system, the system adminis­ folders) and then runs chmod against work as root to edit it. ■
trator is allowed to assign new owners them, ignoring the
and new groups to files and directories. directory itself. Listing 3: Oops ... Locked Out!
To give a file to user petronella, simply To use the -R pa­ $ Is -1 test
use the chown command: rameter with the total 0
chown program, -rwxr-xr-x 1 petronella petronella 0 Nov 4 12:12 bar
chown petronella FILE_NAME you would enter -rwxr-xr-x 1 petronella petronella 0 Nov 4 12:12 foo
the following com­
$ chmod -R a-x test
Also, you can define a new group in the mand to hand over
chmod: cannot access 'test/bar': Permission denied
same command. To do so, add the name the home directory
chmod: cannot access 'test/foo': Permission denied
of the group after a colon: and all the files in

Listing 2: Setting the s Bit by Number Listing 4: Using the find Command
$ Is -1 script.sh $ find test -type f -exec chmod a-x \{\} +
-rw-r—r— 1 heike heike 3191789 Oct 6 05:01 script.sh $ Is -1 test
$ chmod 4755 script.sh total o
$ Is -1 script.sh -rw-r—r— 1 petronella petronella 0 Nov 4 12:12 bar
-rwsr-xr-x 1 heike heike 3191789 Oct 6 05:01 script.sh -rw-r—r— 1 petronella petronella 0 Nov 4 12:12 foo

42 LINUX SHELL HANDBOOK - 2023 EDITION


su and sudo MANAGEMENT

If you do not specify a username after the


Assuming administrative privileges with su and sudo
su command, the system logs you into

SPECIAL PRIVILEGES
the root account (Figure 1).
When you use the basic su command,
you change accounts but do not com­
pletely change your environment. To
Su and sudo give you a limited login to other accounts. Both commands be specific, only the $HOME, $SHELL,
play a role in Linux security by minimizing the time you'll need access $USER, $LOGNAME, $PATH, and $IFS
environment variables are reset. De­
to the root account. BY BRUCE BYFIELD
pending on how su was compiled,
$TERM, $COLORTERM, $DISPLAY, and
inux and other Unix-like systems conventional logins. Similarly, developers $XAUTHORITY may also be reset.

L use the root account for system


administration. Traditionally,

tem’s hardware and software settings,


can use su to run test accounts with dif­
ferent environments. The main purpose
­ su and sudo, though, is to minimize
only root has full control over the sysof
the security risk involved in using root.
These limitations make switching ac­
counts quicker and reduce your vulner­
ability if you are moving to the root ac­
count. However, they can create other
an arrangement that helps guard su and sudo have similar but different difficulties. For example, because you will
against external attacks. Other users goals. Although both can run on the same still be in your home directory, you will
might have some control over their per­ system, many OS vendors tailor their sys­ be unable to run scripts written for use in
sonal settings, but they cannot edit, or tems around one or the other tool. The su root. Entering su root will only change the
sometimes even view, key system files. command typically prompts the user to account, and not the environment.
Traditionally, the administrator became enter the root password, so it only works The same problem also exists with other
“root” by logging in to the root account out of the box on systems that configure accounts, and you can solve it by entering:
with a root username and password. the root account. Some Linux distribu­
However, a full login to root creates secu­ tions, such as Ubuntu and Knoppix, don’t su - [USER NAME]
rity problems. For example, if the user bother assigning a root password and
walks away from the keyboard, the sys­ therefore depend on sudo to let normal The -I or -login options have the same
tem is left in a state in which an in­ users execute administrative commands. function.
truder - physical or remote - can severely The options -m, -p, or -preserve-environ­
compromise the system. Even worse, su: Environments and ment will keep your original environment.
users might forget to log out and back Quick Commands You can also specify the shell to use when
in again for end-user tasks, leaving the The name su stands for “substitute user.” you switch accounts with -s or -shell
system potentially vulnerable. The command is a quick replacement for [SHELL] (e.g., if want to see whether a
In many cases, however, a full root logging in and out of accounts in the script written for Bash will run in an alter­
login is unnecessary. The administrator usual way. To use su, all you need to do is native shell such as Zsh).
might only need root privileges to run enter the basic command followed by a All this tinkering with environments
one or two commands, such as checking username. If you are in an ordinary ac­ can be confusing, which is why many
a system logfile or configuring a new count, you then enter the password for users stay with su -. However, this is the
printer. The advantage of su and sudo is the account; if you are currently root, you
° that they open the root account only for switch into the account automatically. bb@nanday:~$ su -
“ specific tasks. Once the tasks are done, When you are finished using the account, Password:
S users return quickly to their regular tasks, enter logout or exit or press Ctrl + D to re­ root@nanday:~# exit
| thereby minimizing the amount of time turn to the account in which you started.
Logout
bb@nanday|
| the system is vulnerable. Should you become confused about
| The root user can also use su to switch which account you are in, you can type Figure 1: Using su to switch accounts is
j between accounts more quickly than with the whoami command to orient yourself. much guicker than logging in and out.

LINUX SHELL HANDBOOK- 2023 EDITION 43


MANAGEMENT su and sudo

enter the first command - typically, five


minutes. Until they expire, you can enter
additional commands prefaced by sudo
without entering a password again. You
can extend this time by another 15 min­
utes using the -v option. Conversely, if
you do not need the additional time, run
sudo -K to remove your privileges. Less
drastically, sudo -k [COMMAND] re­
moves your current privilege for a spe­
cific command you are authorized to run
with sudo. To restore the privileges, you
need to run sudo again.
As with su -, sudo offers some control
over the environment in which it runs.
Using the -U option with sudo, you can
run a command as a user other than root.
You can also use -E to run commands in
your current environment or -H to run
them from your cunent home directory.
Figure 2: The env command shows active environment variables. If you have trouble running sudo, start
by running sudo -I (Figure 4). This com-
least safe alternative: you are better off password, sudo can be configured several mand shows the paths to commands that
running the env command if you become ways, depending on how a particular distri­ you can run from the current account, as
confused. The long output that env pro­ bution decides it is most secure. well as the set of commands themselves.
vides contains entries, such as the home Some Linux distributions, such as In Ubuntu-derived distros, you are proba­
directory, that will show just what envi­ Ubuntu, let users enter their own pass­ bly authorized to run all commands as
ronment you are using (Figure 2). words to use sudo. This practice lets a root, but on a custom configuration, your
Many users enter su -, change to root, user perform privileged operations with­ choices may be more limited. Note that if
and then enter a command. This habit is out the root password. On the other you do not see a list, but are only offered
methodical, but it also increases the hand, you control which tasks the user three attempts to log in, then sudo is not
amount of time your system is vulnera­ can perform, and letting users authenti­ configured on your system.
ble. A more efficient way is to use the cate with their own password minimizes
-c option. the number of users who need access to sudoers
For example, some files are readable the root password. Other distributions, The /etc/sudoers file contains information
only as root. If you try to view them such as openSUSE, require users to enter on which users can use sudo and for
from an ordinary account, you simply the root password with sudo. what purposes. The sudoers file is a plain­
get an error message. Instead of chang­ Most users know sudo as the equiva­ text file, but you should never open it di­
ing to root to read them, you can enter lent of the children’s magic word rectly from a text editor. Instead, run ei­
su -c "less /var/log/messages”. The sys­ “please.” That is, to run a command with ther the command sudo -e sudoedit or the
tem responds by displaying the file in the root privileges, you add sudo at the start. command visudo /etc/sudoers. Both com­
less viewer. When you press the q key to For example, to run the shutdown com­ mands lock the original file and open a
quit the viewer, you return immediately mand to stop the system, you would type temporary copy of sudoers in the default
to the original account, having spent the sudo shutdown and enter the appropriate text editor (Figure 5). If you prefer, you
minimal time possible as root. password (typically your password or the can replace the default editor by running
Quotation marks mean the command root password, depending on your sudo EDITOR = [EDITOR] /user/sbin/visudo.
should be read as a continuous option configuration).
of the su -c command. Without the Your expanded privi­ bb@nanday:su -c less /var/log/messages
No passwd entry for user '/var/log/messages'
quotation marks, su recognizes that leges can be set to last
less is a command but, expecting its for a time after you Figure 3: su needs quotation marks to read a literal command.
usual syntax, wrongly interprets the
sudo -I
file path as a username (Figure 3).
Matching Defaults entries for bb on this host:
env_reset, mailbadpass,
The Sudo Command secure_path=/usr/local/sbin\ :/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bi
n
sudo is short for “switch user, do.” Func­
tionally, it is roughly the equivalent of su -c, User bb may run the following commands on this host:
designed to run a single command as root (ALL : ALL) ALL
and then return to the original account. (root)_NOPASSWD: /usr/lib/linuxmint/mintUpdate/checkAPT.py

However, whereas su requires the root Figure 4: Query /etc/sudoers to learn what commands you can run.

44 LINUX SHELL HANDBOOK - 2023 EDITION


su and sudo MANAGEMENT

When you are finished, visudo checks Avoiding Self-Sabotage the bare minimum, but that doesn’t mean
for errors, giving you the chance to cor­ Like much of Linux, su and sudo can be you can relax other precautions.
rect them or go ahead and save to the as simple or as complex as you choose. Specifically, avoid using su to become
original file. Be careful before you save - Most popular uses of sudo, in particular, root and then keeping a terminal open
syntactical errors can prevent sudo from are extremely basic, and by copying and forgotten on some overlooked vir­
working properly, or even at all. them, you can quickly get up to speed. tual workspace. Similarly, reduce the
The top of the sudoers file sets aliases However, when you use su and sudo, be time that a successful sudo login lasts to
for advanced configuration. Aliases can careful that you do not undermine their the minimum. Consult system logs to
be used for such purposes as creating purpose. The entire point of both com­ ensure that the powerful su and sudo
comma-separated lists of users or com­ mands is to increase security by minimiz­ commands are only used for authorized
mands to simplify configuration. For ex­ ing the time you run as root. Both com­ activities. (Also see the box titled “The
ample, if you want to restrict who can mands can reduce your time as root to Administrator Sees Everything.”) ■
power off the system or network, add
the following line to create the command
alias SHUTDOWN:

Cmnd_Alias SHUTDOWN P
= /sbin/halt, /sbin/shutdown, P
/sbin/reboot, /sbin/poweroff

Once the alias is defined, you can give


users the right to run all three commands
simply by referencing the SHUTDOWN
alias. In the same way, you could define a
group of users called ADMINS, all of
whom can run the same commands.
Regardless of whether you specify
aliases, you can assign privileges with sin­
gle-line entries. Depending on the distribu­
tion, the assignment of various privileges
may be organized by commented lines
prefaced with the hash (#) symbol. Be sure
that the lines that assign privilege are
below the list of uncommented aliases. Figure 5: By default, visudo launches with sudo's default text editor, which is often nano.
The simplest form of privilege assign­
ment is [NAME] ALL = ALL. For example, The Administrator Sees Everything
bb ALL=ALL allows user bb to run any
The system will log unsuccessful calls to user ran with root privileges, butthat's not
command from any terminal. suand sudo. If you type suand enter the all. If you attempt to run a program with­
More restrictively, the line could read wrong password, an entry like the follow­ out having the necessary privileges, don't
as follows: ing will appear in the logfile (messages, be surprised if the administrator knows
syslog, or auth.log below the/var/log/di­ exactly what you have been up to and
bb /sbin/halt, /sbin/shutdown, 7 rectory): sends you a friendly reminder about un­
/sbin/reboot, /sbin/poweroff=ALL successful "break-in attempts." Users also
Nov 23 08:14:08 server su: P
FAILED SU (to root) esser on 7 learn that they are not allowed to run sudo
Or, if the SHUTDOWN alias suggested /dev/pts/3 thanks to a console message:
above was defined at the top of the sudo­
Unsuccessful calls to sudo are also $ sudo less /var/log/messages
ers file, the line could be: logged. Typically, you will see entries in Password:
the/var/log/messagesfile, although Fe­ peggy is not in the sudoers file.
bb SHUTD0WN=ALL dora Linux writes the entries to /var/log/ This incident will be reported.
secure and only logs the errors in mes­ In plain English, this message means that
The sudoers file can also contain fields sages: the root user will receive a message by
to adjust other behaviors. The most use­ Sep 11 21:10:47 huhnix sudo: huhn : 7 email that shows exactly when "peggy"
ful fields are passwd_tries, which sets TTY=pts/6 ; PWD=/home/huhn ; 7 failed to run sudo: The message is tagged
the number of attempts to log in to sudo; USER=root ; 7 as "SECURITY information for huhnix." If
passwd_timeout, which sets the length COMMAND=/usr/bin/less 7 you want to find out which commands
of time that a login lasts; and editor, /var/log/messages you are allowed to run under sudo, you
which sets the editors you can use with The sudo command differs from su in that can type sudo -/for a list of commands al­
sudo. For a complete list of these fields, the logfile also reveals which program a lowed through the sudo configuration.
see the sudoers man page.

LINUX SHELL HANDBOOK- 2023 EDITION 45


MANAGEMENT systemd

Controlling your Linux system through systemd Anatomy of a Unit File


In systemd parlance, a managed object is
known as a unit. The files that are used

SYSTEMD
to initialize and start units at boot time
are known as unit files. Admins will find
the unit files in folders such as:
• /etc/systemd/system/*
• /run/systemd/system/*

PRIMER • /usr/lib/systemd/system/*
Unit files serve a role that is similar to
the init scripts of older Linux systems;
however, a unit file is not executable. In­
stead, a unit file is more like a configura­
Systemd manages the services on most Linux systems. We'll show you tion file in the style of Windows .ini
files. A quick look at the unit file for
some useful commands for managing processes, analyzing log data, starting a MySQL server shows how sys­
and automating recurring tasks. BY JENS-CHRISTOPH BRENDEL, temd works (Listing 1).
The [Unit] section contains a human-
TIM SCHURMANN, AND JOE CASAD readable description of the service; the
After variable specifies other services
that need to start first. In this case,
ystemd has gradually replaced the while the system is running. Systemd also MySQL depends on the network and the

S ancient System V as the leading


init system for Linux. Most main­
logs system events, automates processes,
and much more. This article offers a brief
stream Linux variants now use systemd.
The init system launches processes when
introduction to systemd and highlights
some of the important command-line
syslog service already being up. You
could use the Before variable to declare
that the service you are defining with the
unit file must start before the service(s)
you start your Linux system, and it also tools you can use to interact with the specified with the variable.
stays around to start and stop services systemd environment. The [Service] section sets the user ac­
count and group that the database server
Listing 1: MySQL Unit File will use. Type determines the boot style:
01 [Unit] Simple means that the program specified
02 Description=MySQL 5.6 database server below ExecStart starts the main process.
03 After=syslog.target The two MySQL scripts specified below
04 After=network.t arget
ExecStartPre handle the preparatory work.
05
ExecStartPost calls scripts that need to
run after the main program starts. The
06 [Service]
mysql-wait-ready script makes sure
07 Type=simple
MySQL completes the cleanup that it
08 User=mysql
normally performs at start-up time. This
09 Group=mysql
means that services that require MySQL
10
do not start until the database is actually
11 # Execute pre and post scripts as root
ready to accept connections.
12 PermissionsStart0nly=true
Additionally, the unit file sets a time­
13 out and assigns the database service to
14 ExecStartPre=/usr/libexec/mysql-check-socket the multiuser target. This target is a spe­
15 ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n cial unit that basically assumes the role
16 ExecStart=/usr/bin/mysqld_safe --basedir=/usr of the previous runlevel 3 in System V,
17 ExecStartPost=/usr/libexec/mysql-wait-ready $MAINPID which starts the system normally in
18 ExecStartPost=/usr/1ibexec/mysql-check-upgrade multiuser mode.
19
20 # Give a reasonable amount of time for the server to start up/shut down More Security
21 TimeoutSec=300 Unit files support a slew of other param­
22 eters, including some options that pro­
23 # Place temp files in a secure directory, not /tmp vide an easy way for improving the secu­
24 PrivateTmp=true rity of your services.
25 The first of these parameters in the
26 [Install] [Service] section is:
27 WantedBy=multl-user.target
PrivateNetwork=yes

46 LINUX SHELL HANDBOOK - 2023 EDITION


systemd MANAGEMENT

This setting completely isolates the ser­ capabilities away from the service. If you allowed to spawn, the service cannot
vice from any networks. The service prepend the capability with a tilde (~ fork any other processes.
then only sees a loopback device, and this capability is explicitly taken away.
even that does not have a connection to You can also use the unit file to limit LimitNPROC=l
the host’s actual loopback device. Of the resources a service can access. The LimitFSIZE=O
course, this option is not very useful for setrlimit() man page lists all restrict­
network-based services. able resources. For example, if you set You can limit other resources in a
A word of caution: Sometimes you the maximum size of a file (FSIZE) that similar way.
need a network, even if the need is not the service is allowed to generate to 0,
apparent at first glance. For instance, a as shown in the example below, the Monitoring Processes
service might perform most of its work service cannot write the file anywhere. After you system boots, you might want
locally but use LDAP to handle authenti­ If you specify 1 as the maximum num­ to know whether all the required ser­
cation. In that case, you need to be sure ber of processes (NPROC) the service is vices are actually running. The systemctl
only users with a user ID below 1000 are
authenticated; names need to resolve to
UIDs locally through /etc/passwd for
these accounts.
A second security feature in [Service] is:

PrivateTmp=yes

If this option is set, the service uses its


own /tmp directory instead of the
global /tmp, which protects the service
against malicious Symlink and DoS at­
tacks that tend to use /tmp. However,
keep in mind that some services locate
communication sockets in /tmp that
will not work if they are in a private
directory.
The next two options let you prevent
services from writing to specific directo­
ries or even accessing them in any way:

ReadOnlyDirectories=/var Listing 3: Status Query for a Service


InaccessibleDirectories=/home
01 jcb@localhost:~$ systemctl status mysqld.service

Linux provides a means for assigning the 02 * mysqld.service - MySQL 5.6 database server
privileges traditionally associated with 03 Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled)
superuser. These privileges are known as OU Active: active (running) since Do 2015-11-26 09:52:45 CET; 7h ago
capabilities, and you can see the list of
05 Process: 1528 ExecStartPost=/usr/libexec/mysql-check-upgrade (code=exited,
all available capabilities by viewing the
status=0/SUCCESS)
capabilities man page:
06 Process: 1000 ExecStartPost=/usr/libexec/mysql-wait-ready $MAINPID
(code=exited, status=O/SUCCESS)
man capabilities
07 Process: 919 ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n (code=exited,

Systemd additionally lets you assign spe­ status=O/SUCCESS)

cific capabilities to a service or withdraw 08 Process: 793 ExecStartPre=/usr/libexec/mysql-check-socket (code=exited,


those capabilities through settings in the status=O/SUCCESS)
unit file. For example, the following line 09 Main PID: 999 (mysqld_safe)
in the [Service] section of the unit file: 10 CGroup: /system.slice/mysqld.service
11 | - 999 /bin/sh /usr/bin/mysqld_safe —basedir=/usr
CapabilityBoundingSet=P
12 |_1309 /usr/libexec/mysqld —basedir=/usr —datadir=/var/lib/mysql...
CAP_CH0WN CAP_KILL
13
defines a whitelist of capabilities that the 14 Nov 26 09:52:44 localhost.localdomain mysqld_safe[999] : 151126 09:52:44 mysql...
process must have. 15 Nov 26 09:52:44 localhost.localdomain mysqld_safe[999]: 151126 09:52:44 mysql...
Defining such a whitelist is not al­
16 Hint: Some lines were ellipsized, use -1 to show in full.
ways easy. The other option is to take

LINUX SHELL HANDBOOK- 2023 EDITION 47


MANAGEMENT systemd

command provides an overview of ser­ ExecReload = options in the unit file. draws a graph with the service startup
vice status. Systemctl lists all booted ser­ However, -kill-who = all (and this is the information.
vices with status information (Listing 2). default) would affect the control and main
If you only want to see the failed start­ processes. Accessing Log Data
ups, try: If you do not simply want to stop a Systemd includes a journal feature that
service, but you also want to prevent it serves as a log of system events. The
systemctl —state=failed from restarting on the next boot, disable creators of the systemd logging compo­
it with the following command: nent wanted to fix the shortcomings of
For a single service, you can view more earlier tools, but they also wanted a
detailed information with: systemctl disable Unit_name simple and reliable solution that didn’t
need maintenance. Other objectives
systemctl status mysqld.service If the process is still running, it is not were portability, security, and perfor­
stopped by disabling; if it was already mance. The developers wanted a design
The output (Listing 3) shows the exit stopped, it can still be started manu­ that delivered tight integration into the
states of the pre- and post-scripts from ally even after disabling. Only auto­ overall system and harmonized with ex­
the unit file, as well as additional infor­ matic restarting at the next boot time is isting logging systems.
mation on the service status. prevented. The solution differed considerably from
The status messages can be quite There is an even more precise use the previous Syslog daemon. Applications
long on a case-by-case basis. Admins case, even if it is rarely necessary: After
can thus use either the n line number typing: Listing 4: Analysis (excerpt)
parameter to limit the number of rows
01 jcb@localhost:
to output or the o file parameter to redi­ systemctl mask Unit_name
/var/log$ systemd-analyze blame
rect everything to a file.
02 3.234s docker.service
the service will not start automatically
Starting and Stopping (as is the case with disable), and it also 03 2.152s dnf-makecache.service

Sometimes you need to stop or restart won’t start manually. This command Od 1.281s Plymouth-start.service

individual services after a boot or re­ links the unit file to /dev/null; if you 05 1.269s mysqld.service
boot. Systemctl and the stop, start, re­ want to undo this action, you need to 06 1.009s plymouth-quit-wait.service
start, and reload commands can help; delete the link. 07 958ms systemd-udev-settle.service
for example: 08 603ms slapd.service
Analysis of Time 09 02ms firewalld.service
systemctl stop mysqld Reguirements 10 451ms systemd-journal-flush.service
systemctl start mysqld If you have ever considered where your
11 402ms cups.service
computer is wasting time at bootup, and
12 279ms accounts-daemon.service
A user who wants to start or stop a sys­ maybe used a tool like Bootchart to opti­
13 244ms libvirtd.service
tem service must authenticate. If the mize the boot process, you will find life
14 198ms ModemManager.service
process does not respond to the stop much easier with systemd. Systemd al­
command, the only way out is: ready has the necessary analysis tools 15 187ms systemd-logind.service

built in. The following command: 16 183ms NetworkManager.service


systemctl kill unit_name 17 170ms lvm2-monitor.service
systemd-analyze blame 18 167ms chronyd.service
This command sends a kill signal to each 19 155ms avahi-daemon.service
process in the process group, even to those produces a list in descending order of all 20 155ms systemd-vconsole-setup.service
that the parent process forked at a later started services with the time they 21 135ms mcelog.service
stage. The effect thus resembles killall pro­ needed for initialization (Listing 4).
22 126ms sysstat.service
cess name. The -s option also lets you send Note, however, that the times listed may
23 126ms udisks2.service
another specific signal to a process, for ex­ have run in parallel, since the boot pro­
24 125ms jexec.service
ample, SIGHUP to trigger a reload, as cess is no longer strictly serial. The tool
25 124ms bluetooth, service
shown in the following example: does not reveal anything about the
causes for long execution times, but sys­ 26 124ms docker-storage-setup.service

systemctl kill -s HUP 7 tem administrators can at least consider 27 123ms netcf-transaction.service
—kill-who=main crond.service whether they really need these time 28 121ms rtkit-daemon.service
wasters. 29 120ms livesys.service
The -kill -who option ensures that only The whole picture becomes even 30 115ms packagekit.service
the main process receives the signal. clearer if you visualize the data. The fol­ 31 104ms abrt-ccpp.service
Alternatively, you could also type lowing command: 32 102ms systemd-udevd.service
-kill-who = control to cover all control pro­
33 100ms var-lib-nfs-rpc_pipefs.mount
cesses; for example, all processes called systemd-analyze plot > plot.svg
34 [...]
by the = ExecStartPre =, ExecStop =, or eog plot.svg

48 LINUX SHELL HANDBOOK - 2023 EDITION


systemd MANAGEMENT

no longer hand over one formatted line manipulation is thus eas­


ily recognized.
Listing 5: Journal Entry
for each entry to the logging system.
Many entries are key-value pairs sepa­ 01 _SERVICE=systemd-logind.service
rated by line breaks. Entries can contain Introducing 02 MESSAGE=User peter logged in
both well-known and application-specific journalctl 03 MESSAGE_ID=455bcde45271414bc8bc9570f222f24a9
pairs. The values are usually strings, but Along with systemd jour­ 04 _EXE=/lib/systemd/systemd-logind
they can also contain binary data. nal’s numerous advan­
OS _C0MM=systemd-logind
The logging service itself adds some tages for saving log mes­
06 _CMDLINE=/lib/systemd/systemd-logind
metadata (e.g., timestamps, hostname, sages are some additional
07 _PID=4711
service name, PID, UID, and so on), improvements for admins
which means this information can no who need to browse the 08 _UID=0

longer be spoofed by a client. entries. The key for 09 _GID=0


Messages added by the system begin searching in the logs is 10 _SYSTEMD_CGROUP=/system/systemd-logind.service
with an underscore (Listing 5). All the journalctl command. 11 _CGR0UPS=cpu:/system/systemd-logind.service
fields that make up a log entry are If you call this command 12 PRI0RITY=6
stored as individual objects and refer­ without any further pa­ 13 _B00T_ID=422bc3d27149bc8bcde5870f222f24a9
enced by all log messages that need rameters as the root user, 14 _MACHINE_ID=c686f3b6547f45ee0b43ceb6eda479721
them. Nothing is stored twice on disk, you will see a list of all
IS _HOSTNAME=poseidon
which saves so much space that the existing messages, start­
16 L0GIN_USER=S00
new system does not use significantly ing with the oldest. This
more disk space than the classic Sys- list looks quite similar, at
log, even though it stores far more first glance, to the old /var/log/messages Because it is better to avoid working as
metadata. file (Listing 6). the root user, systemd additionally
Messages from non-privileged users However, journalctl offers some signif­ grants access to all logs to members of
are stored in individual journal files, icant improvements over previous out­ the adm group.
which the user can read. However, log put formats: Searching through all the log entries is
entries for system services are only ac­ • Lines with a priority of Error or higher not very efficient. The journal thus pro­
cessible to root and the users of a group are highlighted in red. vides powerful tools for filtering the
specifically assigned rights for the infor­ • Lines with a priority of Notice/Warn- logs. The simplest filter is:
mation. Context is not lost, because the ing are shown in bold type.
client transparently merges all messages • Timestamps are converted to the local journalctl -b
that a specific user is permitted to read time zone.
to create a large virtual logfile. Recurring • The output is automatically paged This command shows all the entries
events, such as “User logged in” can be with less. since the last boot. In addition, admins
marked with a 128-bit message ID, thus • All stored data is output, including can restrict the output to logs with a par­
allowing for quick filtering with similar data from rotated logfiles. ticular priority using the -p parameter:
events.
The Journal daemon automatically ro­ Listing 6: Log Message Output
tates logfiles when certain size limits are 01 [root@localhost jcb]# journalctl
exceeded. Rotation ensures that the sys­ 02
tem does not exceed a predetermined 03 [...]
disk utilization level. In addition, a sin­ 04 Jan 10 20:03:52 localhost.localdomain systemd[987]: Starting Paths.
gle client is limited to a maximum num­
05 Jan 10 20:03:52 localhost.localdomain systemd[987]: Reached target Paths.
ber of log messages in a certain period.
06 Jan 10 20:03:52 localhost.localdomain systemd[987]: Starting Timers.
This maximum is correlated with the
07 Jan 10 20:03:52 localhost.localdomain systemd[987]: Reached target Timers.
free disk space: If the disk is empty, the
08 Jan 10 20:03:52 localhost.localdomain systemd[987]: Starting Sockets.
Journal daemon is generous, but if it is
09 Jan 10 20:03:52 localhost.localdomain systemd[987]: Reached target Sockets.
almost full, the daemon only allows a
few messages per client. 10 Jan 10 20:03:52 localhost.localdomain systemd[987]: Starting Basic System.

An attacker who does successfully 11 Jan 10 20:03:52 localhost.localdomain systemd[987]: Reached target Basic System.

break into a system often tries to cover 12 Jan 10 20:03:52 localhost.localdomain systemd[987]: Starting Default.
the tracks by manipulating the system 13 Jan 10 20:03:52 localhost.localdomain systemd[987]: Reached target Default.
logs. The plain-text format of the old Sys- 14 Jan 10 20:03:52 localhost.localdomain systemd[987]: Startup finished in 13ms.
log daemon made this obfuscation very 15 Jan 10 20:03:52 localhost.localdomain gdm-launch-environment][948]: pam_unix(gdm
simple. But journald maintains a crypto­ -launch-environment:session)...
graphic hash of all messages and a hash 16 Jan 10 20:03:53 localhost.localdomain org.ally.Bus[996]: Activating service
of the preceding entry, which creates a name='org.ally.atspi.Registry'

chain in which the last entry can easily 17 Jan 10 20:03:53 localhost.localdomain org.ally.Bus[996]: Successfully activated
service 'org.ally.atspi.Registry'
authenticate all preceding entries. Log

LINUX SHELL HANDBOOK- 2023 EDITION 49


MANAGEMENT systemd

journalctl -b -p err Journalctl implicitly filters by _SYSTEMD_ journalctl _UID=1000


UNIT. But, what are the names of the
If the computer is rarely booted, the -b other services, or systemd units, whose or:
parameter is not very helpful. In that messages you might also want to filter
case, it is better to explicitly specify the out? To find out, type: journalctl _EXE=/usr/bin/gnome-session
time period:
journalctl -F _SYSTEMD_UNIT You can combine these search parame­
joumalctl -since=yesterday ters. Joumalctl logically ORs all the pa­
The -F parameter tells the command to rameters. You could also exclusively OR
If a longer period is required, you can list all the different values taken by the the search parameters, which is equiva­
enter -since or -until along with a date, metadata parameter specified in the cur­ lent to saying either/or. You can use the
optionally including a time: rent log. If you want to see all the meta­ plus sign for an exclusive OR (Listing 8).
data ever recorded, instead of individual This command discovers all the log en­
journalctl —since=2015-ll-15 7 entries, use: tries that either originate from the user
—until="2015-ll-16 20:59:59" with the UID 1000 on the local host or
journalctl -o verbose -n the user with the UID 1100 on the host
You might need to do more than just search mercury.
for messages within a certain time period. See Listing 7 for sample output.
One typical example is searching for all The database containing the log en­ Automation
messages for a particular service (or sys­ tries is already automatically indexed Systemd is also capable of managing ser­
temd service unit). You can combine these with all the additional metadata fields vice scheduling and automation. For in­
additional filters with the date or time: (they all start with an underscore, as stance, you might want to use your
mentioned previously) and can be di­ Linux system to automatically create a
journalctl -u mysqld 7 rectly searched for their values. For backup every evening and rotate the log­
—since 9:00 —until 10:00 example: files at regular intervals. In most distri­
butions, time-controlled tasks are han­
dled by the cron daemon. But systemd is
an interesting alternative to cron. Sys­
temd controls the startup process of
most distributions, and it can also trigger
time-controlled and recurring tasks on a
running system.
The first task is to tell systemd which
task to perform. To do this, you create a
unit file call a service unit. Listing 9
shows an example.
The [Service] section is required. Exec-
Start = is followed by the command to
be executed by the system. In Listing 9,
systemd would simply run a script that
backs up the system to the /mnt direc­
tory. The [Unit] section adds some meta­
data. In the simplest case, Description =
is followed by a description of the task.
Service units usually tell systemd
which services to boot when the system
starts. Systemd also supports additional
sections and settings. However, since
the system just needs to schedule the
task, these settings are not (absolutely)
necessary.
Save the newly created service unit to
/etc/systemd/system. The filename cor­
responds to the (internal) name of the
service unit. It must be unique among
all service units and end with .service,
as in backup.service. Systemd can also
start existing service units or service
units supplied by the distribution on a

50 LINUX SHELL HANDBOOK - 2023 EDITION


systemd MANAGEMENT

time-controlled basis. In
this case, simply make a
Listing 9: Service Unit
note of the filename of the [Unit]
service file. Description=Create a backup of the system
[Service]
Tick-Tock
ExecStart=/usr/bin/backup.sh /mnt
To avoid burning the cake
to a crisp, most hobby bak­
ers set a kitchen timer. In a similar way, dates, and times separated by
you need to set a separate timer for a commas. In the example from
task you wish to assign to systemd. the first line of Listing 11, sys­
First, create a new text file in the/etc/ temd starts the backup No­
system/system subdirectory. The text file vember 30, 2020 at lam and
should have the same filename as the 12pm (noon).
service unit you created earlier, but it You can also abbreviate the
ends with .timer. In the example, the file number ranges with two dots
would be named backup.timer. In sys­ (..), which means that you do
temd speak, the file with the .timer ex­ not have to list all the months,
tension is known as the timer unit. In for example. The entry from
the timer unit, you describe when the the second line of Listing 11, tells sys­ can also combine these. Systemd
timer should “go off,” at which point, temd to take action on the first day of would delay the backup by a maxi­
systemd will start the backup. each month. If the statement applies to mum of 90 seconds if you state
The structure of a timer unit is very all months, you can also use the wild­ RandomizedDelaySec = "Im 30s".
similar to that of a service unit. As the card * (last line).
example from Listing 10 shows, it typi­ The *-*-* entry from Listing 10 tells Repetition
cally consists of three sections: [Unit] is systemd to run the backup every day at Systemd lets you schedule a task to
followed by general information about 18:15 in every month and every year. occur at some recurring interval without
the timer. In Listing 10, this information specifying an exact time - for example,
would include a Description = that Extremely Hesitant every 15 minutes or once a week. Use
serves mainly as a reminder for the user. If the computer is not running at the se­ the OnCalendar = weekly option to start
Make a note on why the timer exists and lected time, systemd cannot create a a weekly backup. In addition to weekly,
what actions it triggers. backup. In Listing 10, the you’ll find options for minutely, hourly,
In the next section, [Timer], you tell Persistent = true setting ensures that sys­ daily, monthly, yearly, quarterly, and
systemd when to start the task. Make a temd catches up with the task as quickly semiannually.
note of this time after OnCalendar = in as possible in such situations. However, If you want to run a task 15 minutes
the notation weekday year-month-day if several actions start simultaneously, after system startup, use the following
hour:minutes:seconds. The setting they can slow down the system or even settings instead of OnCalendar =...:
OnCalendar=Fr 2018-11-30 12:00:00 interfere with each other.
tells systemd to create the backup on To prevent a traffic jam, systemd ran­ 0nBootSec=1Sm
Friday, November 30, 2018 at noon domly delays execution by a few sec­ OnUnitActiveSec=lw
precisely. You can omit unnecessary onds if necessary. The maximum num­
information, such as the day of the ber of seconds it can wait before exe­ OnBootSec = specifies how many sec­
week or the seconds. cuting is stated after Randomized- onds after system startup systemd
Normally, you will not want systemd DelaySec =. Systemd interprets the should execute the task. In the example,
to run the task once only, but to repeat number as minutes for a trailing m and the timer goes off 15 minutes after the
it. To set up a repeating event, you can as hours for an h. In Table 1, you will system startup. The second setting,
simply list the corresponding days, find all other supported time units; you OnUnitActiveSec=, tells systemd the
time intervals at which it should repeat
Table 1: Units Used by systemd the task. In the example, systemd would
Unit Long forms Meaning Example
run the backup 15 minutes after system
startup and then every week.
s seconds, second, sec second 5s
With both settings, you can use the
m minutes, minute, min minute 10m units from the Table 1 and combine the
h hours, hour, hr hours 2h information. For example, the
d days, day day 7d OnBootSec = ”5m 30s" setting would exe­
w weeks, week week 2w cute the task five and a half minutes
after system startup.
M months, month month 6M
If a timer is based on a (calendar)
y years, year year 4y
date, as per Listing 10, it is known as a

LINUX SHELL HANDBOOK- 2023 EDITION 51


MANAGEMENT systemd

Table 2: Monotonic Timers Listing 12: Enabling at


Setting Refers to the moment when... Startup
OnActiveSec= ... the timer was activated. $ systemctl enable backup.timer

OnBootSec= ... the computer was booted. $ systemctl start backup.timer

OnStartupSec= ... systemd started.


OnUnitActiveSec= ... the unit that activates the timer was last activated. Listing 13: Manual Stop
OnUnitlnactiveSec= ... the unit that activates the timer was last deactivated. $ sudo systemctl stop my.timer
$ sudo systemctl disable my.timer

“Calendar Timer.” If, on the other hand, you need greater accuracy, add the line
a timer starts after a specified period ofAccuracySec = 30s to the [Timer] sec­ at system startup, you need an [Install]
time relative to an event, such as a sys­ tion. The time specification determines section in the timer unit. The Want-
tem start, Systemd refers to it as a the desired accuracy; in the example, edBy = setting tells which other units the
“monotonic timer.” Such timers work in­ the action would be no later than 30 timer should start with. In Listing 10, the
dependently of the time zone. seconds after the assigned date. For WantedBy = timers, target setting ensures
The timer is not only triggered shortlysuch time entries, you can again use that systemd starts the timer together
after system startup, but also responds the units from Table 1. with all other timers at the regular sys­
to other events listed in Table 2. As in Timers also let you wake up the com­ tem startup time.
the previous example, several settings puter from suspend mode on a time-con­ If you want systemd to start the timer
can be combined with each other; each trolled basis. To do this, add the line at startup time, you have to enable it ex­
setting must have its own line. WakeSystem = true to the [Timer] sec­ plicitly (Listing 12, first line). Alterna­
tion. Systemd only wakes the system tively, you can start the timer manually
Relationship Helper when it is in sleep mode and if the hard­ (second line). All currently configured
The systemd-analyze tool helps you fig­ ware and the BIOS/UEFI of the computer timers are listed by the systemctl list-tim­
ure out the correct times. If you pass it support the process. Systemd is currently ers command (Figure 2).
the calendar parameter, systemd-analyze unable to put the computer to sleep on a In Figure 2 under Next, you can read
converts the relative time specifications time-controlled basis. when the system timer will execute the
into other formats (Figure 1). The fol­ Systemd assigns the timer unit to the task the next time. The time remaining
lowing command tells you, for example, appropriate service unit based on the until then is in the Left column. Simi­
which day of the week weekly corre­ filenames. In the example, the timer larly, you can see under Last when sys-
sponds to: backup, timer automatically starts the temd-timer last executed the task. How
command from the service unit long ago that was is shown in the
$ systemd-analyze calendar weekly backup.service. Alternatively, in the Passed column. Under Unit, you will
[Timer] section, you can explicitly find the name of the corresponding
By default, systemd guarantees one- specify the name of the service unit timer and thus its configuration file.
minute timer accuracy. You can there­ that you want systemd to execute You can end the display by pressing Q.
fore expect the backup not to start using the Unit= setting. This is espe­ By default, systemctl only presents tim­
punctually at 6:00pm, but at 6:01pm. If cially useful if you want to start an ex­ ers that are currently enabled. You can
isting service unit display the inactive timers on screen by
tim@ubuntu:~$ systemd-analyze calendar weekly with a new timer. appending the -all parameter.
Original form: weekly
Normalized form: Mon *-*-* 00:00:00
Next elapse: Mon 2018-05-28 00:00:00 CEST Winding Up Snooze Button
(in UTC): Sun 2018-05-27 22:00:00 UTC the Clock If required, each timer can be stopped
From now: 5 days left
If you want sys­ manually (Listing 13, first line) and dis­
Figure 1: A timer starting weekly would execute at midnight every temd to activate abled (second line). The man page [1],
Monday. The next event will be in exactly five days. the timer directly which goes by the name of systemd. timer,

NEXT LEFT LAST PASSED UNIT


Wed 2018-05-23 00:02:37 CEST 35min left Tue 2018-05-22 23:02:02 CEST 24min ago anacron.timer
Wed 2018-05-23 01:10:51 CEST Ih 43min left Tue 2018-05-22 11:00:48 CEST 12h ago apt-daily.timer
Wed 2018-05-23 06:55:48 CEST 7h left Tue 2018-05-22 11:00:48 CEST 12h ago apt-daily-upgrade.timer
Wed 2018-05-23 11:32:51 CEST 12h left Tue 2018-05-22 23:18:02 CEST 8min ago motd-news.timer
Wed 2018-05-23 22:33:44 CEST 23h left Tue 2018-05-22 22:33:44 CEST 53min ago systemd-tmpfiles-clean.timer
Mon 2018-05-28 00:00:00 CEST 5 days left Mon 2018-05-21 00:00:13 CEST 1 day 23h ago fstrim.timer

6 timers listed.
Pass --all to see loaded but inactive timers, too.
[lines 1-10/10 (END)|
Figure 2: Systemctl displays all timers currently running. The display reguires a wide terminal window; alternatively, you can use systemctl
list-timers -no-pager to output the information to the standard output.

52 LINUX SHELL HANDBOOK - 2023 EDITION


systemd MANAGEMENT

provides explanations for all presented The time units again correspond to starts the task stored in the backup, ser­
settings. For further information on those in Table 1. In the example, sys­ vice service unit every week.
the format of dates and times plus nu­ temd interprets the 30m as half an hour. The timers generated by systemd-mn
merous additional examples, see man Alternatively, use -on-calendar = to only exist temporarily. If you use the
systemd.time. enter a specific date. The details are -on-active parameter, the timer disap­
again provided in the same way as in the pears immediately after the action has
Short-Term Alarm timer unit. With appropriate time speci­ been executed; in any case, it disappears
If you want systemd to make a single fications such as weekly, the action can after rebooting the system. Systemd-run
backup in exactly 30 minutes, use sys­ execute repeatedly. only creates a timer for a service unit if
temd-run. The command looks like the In any case, systemd-mn creates a new no suitable timer unit exists.
first line of Listing 14. The /usr/bin/ timer in the background without you
backup, sh /mnt command appended needing to create a service file (Figure 3). Conclusions
there is executed by systemd at the spec­ If a suitable service unit already exists, Systemd lets you define how to start a
ified time. Use the parameter -on-active you can alternatively let systemd-mn service and what the service can do at
to tell it the waiting time. launch it. To do this, simply pass in the runtime. The clear and simple syntax is
name of the service in contrast to the shell-script-based
Listing 14: Examples unit using the -unit methods used in earlier init versions,
parameter. The exam­ and systemd also offers some interest­
$ systemd-run —on-active=30m /usr/bin/backup.sh /mnt
ple from the second ing new options for security, analysis,
$ systemd-run —on-calendar=weekly —unit backup.service
line of Listing 14 data visualization, and automation. ■

tim@ubuntu:~$ systemd-run --on-active=2m /usr/bin/backup.sh /mnt Info


Running timer as unit: run-ul27.timer
Will run service as unit: run-ul27.service [1] Man page for Systemd timer units:
h ttps://www. freedesktop. org/
Figure 3: The timers generated by systemd-run have cryptic names that typically do not software/systemd/man/systemd.
indicate the task solved by the timer. timer.html

Shop the Shop shop.linuxnewmedia.com

Missed an issue?
You're in luck.
usBBoot Privacy
Most back issues are still
available. Order now before
they're gone!

shop.linuxnewmedia.com

GET IT
'(earning

SAVE TIME ON and —


Computers teach
DELIVERY WITH OUR computers to lie

ALTERNATIVE
? PDF EDITIONS V
fosspicks
MANAGEMENT Managing Processes

Process and job control tools

NICE JOB
Be free, be nice, killall? We'll show you how find out more about

your system's processes and how to monitor and control them, all
from the command line. BY HEIKE JURZIK

he previous chapter on systemd • STAT: Process status. The states can be Entering ps / presents you with a tree

T described how to start, stop, and


manage services using the systemctl
S (sleeping), R (running), D (dead, the
process cannot be restarted), orZ
command. A single service or running (zombie, a process that has terminated
application can consist of one or many without correctly returning its return
view processes in the form of an ASCII
image. As an alternative, you can run
the pstree program, which also gives you
a useful overview of the relationships
processes, each of which has a unique status). between “parent” and “child” processes.
process ID. System administrators often • TIME: Computational time used. This tree structure shows you at a glance
need to view and manage the process list • COMMAND: Full command with all of who is descended from whom.
to look for bottlenecks and troubleshoot its command-line options. The pstree tool gives you more de­
problems. Linux has something similar to The ps command offers other options for tailed output if you set the -a flag. This
access controls for processes: Only the adding more information to the output. tells pstree to show you the parameters
user that started a process can stop, re­ For example, u shows the process owner with which the programs are running. If
start, or terminate the process. The only and CPU cycles or memory percentage, you use a terminal that supports differ­
exception to this rule is the root user, who and a gives you a list of all processes for ent fonts and bold type, such as Gnome
can control any process on a system. In all users. Terminal or KDE’s Konsole, you might
this article, I will be looking at tools that The I option is also practical, in that also want to try the -h parameter. This
monitor and control processes. its lengthy output provides you with ad­ tells pstree to highlight its own process
ditional information on the PPID (parent and its ancestors. If you want to use this
Listing Processes with ps process identifier) and on the UID (user practical feature for other processes, use
The ps command gives you a list of the identification) of the user who launched -H with the process ID, and pstree will
processes currently running on your the process. highlight the specified process and its
system. If you do not specify any com­ To display what can be fairly lengthy family tree. Setting the -p option tells
mand-line parameters, the tool will re­ command-line parameters in the pstree to output the process ID (PID),
strict the list to the current shell. If you COMMAND column, you might want and -u shows the user. All of these pa­
need more information, you can specify to set w for wider output, and you can rameters can be combined - for exam­
some of the tool’s impressive collection use this option multiple times. As ple, pstree -apuh (Figure 2).
of options. As the man page tells you, shown in Figure 1, you can combine
ps understands both Unix parameters these parameters as needed; the ps Top Tool!
with a simple dash, BSD options with­ command will let you know whether If you are looking for CPU hogs, ps is not
out a dash, and GNU options with two you’ve chosen conflicting options to your best option. Because it simply gives
dashes. It is a matter of preference format the output. (See the “Security
which you choose, but in this article, I Tip” box for more information.)
will be concentrating on the shorthand
variants without dashes. One Big Family
If you are interested in all of your Processes are never isolated and are al­
processes, call ps with the x option (List­ ways in good company. In fact, they are
ing 1). The tabular output in the shell in a hierarchical structure, with process
tells you the following characteristics: number 1, init at the top. On most distri­
• PID: Process identifier. A unique butions, init has been replaced by sys­
number that references a process temd, and /sbin/init is a symlink. This is
individually. the first process that Linux launches
• TTY: Terminal/console on which the after booting. All other processes share
process was started. A ? indicates the this common “ancestor” - systemd starts
process is not running on a terminal. the operating system’s basic programs.

54 LINUX SHELL HANDBOOK - 2023 EDITION


Managing Processes MANAGEMENT

command name (COMMAND). You also also assign a specific priority, where -20 is
Security Tip
can tell top what you want to see; just the highest and 19 is the lowest priority.
The ps tool displays the full set of com­ press F and the relevant letters to specify To set the level for the process monitor
mand-line parameters in the COM­ the status line content. top, for example, you would type:
MAND column. Some programs, such
as the wget download manager, option­ Several commands allow you to con­
ally accept passwords for authentication trol top interactively; for example, you nice -n 19 top
in the shell. The password also appears can press H to display the online help.
as a command in the process list; theo­ Entering U followed by a username gives If you skip the -n option and the nice
retically, any user on the system could you the processes for that user. Shift + R level, nice sets the value to 10. As men­
sniff sensitive data.
reverts the output, showing the most fru­ tioned before, regular users are only al­
gal processes instead of the CPU hogs, lowed to use positive increments:
you a snapshot of the current status, and entering Q quits the tool and takes
you will not find out too much about you back to the shell. $ nice -n -19 top
the current system load. However, Shift + Z lets you add color. The W key nice: cannot set niceness: P
Linux has the top tool to help you with toggles through several predefined color Permission denied
this task. Top is a process monitor that schemes, but you can also press the ap­
updates the display to give you the cur­ propriate letters and numbers to define To discover a program’s nice level, use
rent status. You can launch the monitor your own color scheme (Figure 3). the top (under column NI in the status
by typing top at the command line. bar) or ps command. In the ps output in
This program gives you extensive in­ Mister Nice Guy Listing 3, the top call has been “niced,”
formation about your system and the Processes have a specific priority, as indicated by the capital N in the STAT
processes running on it. The top line which becomes useful if you have a column.
shows the time, the computer uptime, program running in the background To change the priorities of programs
the number of processes, and the status and do not want to risk losing control that are already running, use the renice
details, along with the CPU, memory, over the system load. To start a pro­ command. Regular users manipulate
and swap load. To find out more about gram with a specific priority, use the only their own tasks; only the root user
used and unused memory and swap nice command. Non-privileged users can renice every program. To change a
space, you can also use free or uptime may only assign lower priorities to priority, find out the program’s PID,
(see the “More Information about their own tasks - assigning higher pri­ then use renice plus the -n parameter
Memory” box). orities is the administrator’s domain. and the value:
The top status line contains informa­ Processes have a nice value of 0 by de­
tion on the individual processes. The fault; if you run the command without $ renice -n 10 2342
columns of the status line present vari­ parameters, the program will confirm: 2342 (process ID) old priority 19, 7
ous categories, such as the process ID new priority 10
(PID), username (USER), priority (PR), $ nice
nice level (NI), memory usage as a per­ 0
centage (%MEM), parent process ID ■ HodcnManager, SIP
I - (gdbus) ,661
(PPID), user ID (UID), CPU time con­ With the nice com­
|-dhcllent,2075 -d -q -ST /usr/ltb/NetworkManager/no-dhcp-helper
sumed as a percentage (%CPU), and mand, you can
|-{gdbus},663
■-{gRatn),6S9
■VBosCllent,12M,huhn --clipboard
-VBoxCltent.1267 --clipboard
-{SHCLIPJ.1284
TIME COMMAND |-{gdbus},660
0:00 /sbin/init splash
0:00 [kthreadd]
0:00 [ksoftirqd/0] -anacron.SOO -dsq
0:00 [kworker/0:0H] -sh,2284 -c ru -report /etc/cron,weekly
0:00 [kworker/u2:0]
0:00 [rcu.sched]
0:00 [rcu.bh] •cat,23OO
0:00 [rcuOS/O] •avahi-daenon,621.avahi
0:00 [rcuob/0]
0:00 [nigration/O] -cgnanoger,616 -r nane-systewd
0:00 [watchdog/O] ■eolord,1096,colord
0:00 [khelper] |-(gdbus},1090
a:ee [kdevt«pfs] '-(gnatn},1099
0:00 [netns]
o:oo [perf]
0:00 [khungtaskd] '-{gdbus},675
0:00 [writeback]
0:00 [ksnd]
0:00 [khugepaged]
0:08 (crypto) -gnone-keyrtng-d,118S,huhn -daenontze -login
0:00 [kintegrityd] |-{gdbus),1356
O:O0 [bioset] |-{gnatn),1186
0:00 (kblockd)
0:00 [ata.sff] - kerneloops,1125,kernoops
0:00 [led] ■to -auth /var/run/lightdn/root/:0 -noilsten
O:00 [devfreq_wq]
0:00 [kworker/u2:l]
0:00 [kworker/0:l]
o:oo [kswapde]
0:00 [fsnotify.nark] i-(gdbus},140S
0:00 [acryptfs-kthroa] •{gnatn}.1410
0:00 [kthrotld]______ -at-spi2-reqlstc,1413 ■-use-qnone-session

Figure 1: The ps command shows you what is happening on your Figure 2: The pstree command shows you process relationships in
Linux machine. the shell. Combine the options to format the output.

LINUX SHELL HANDBOOK- 2023 EDITION 55


MANAGEMENT Managing Processes

More Information about Memory


Two more command-line tools provide information on your system's
memory. The free command is typically used without any parameters
and shows the total amount of free and used physical and swap mem­
ory in the system, as well as the buffers used by the kernel (Listing 2).
The default setting is kilobytes; to display megabytes or gigabytes,
use the -m or -g switch. It's also possible to add a fourth line of data
containing the totals for physical memory and swap space. To do so,
use the -t option.
To find out more about your system's load averages, you can use
the uptime tool. As the name suggests, this command is mainly
used to show how long the system has been running. The output
additionally displays the current time, the uptime, how many users
are currently logged on, and the system's load averages for the
past 1, 5, and 15 minutes:
Figure 3: Coloring the output of the top process monitor.
$ uptime
17:49:04 up 30 min, 2 users, load average: 0.00, 0.01, 0.08
After waiting formation on finding PIDs is shown in
in vain for a the “More Detective Work” box.
On some systems (e.g., Ubuntu 15.04) timeout, you probably have no alter­
the renice command will only work native but to reboot. Killer Command
with admin privileges, and non-super- • SIGSTOP interrupts the process until The killall program supports the same
users cannot increase scheduling priori­ you enter SIGCONT to continue. signals as its colleague kill, but instead
ties of their own processes (Listing 4). To send a signal to a process, you can of the ID, it expects the process name. If
If you want to change the nice level, enter either the signal name or number you run killall without specifying the
put sudo in front of the command and followed by the process ID - for exam­ signal, the program will assume that you
identify with your own password when ple, kill -19 9201. Also, you can specify mean -15 (-TERM). Thus, calling killall
asked. multiple process IDs. If you call kill gnome-terminal gracefully terminates all
without any parameters but with the instances of the Gnome terminal app.
Talk to Your Processes PID, it will send the SIGTERM signal (75) Because killall really does take a
Although the name might suggest other­ to the process. roundhouse swipe at active processes,
wise, the kill program need not be fatal. To find the right process ID, run ps as caution is advised - the command killall
On the contrary, it is used to send sig­ described previously. The shell com­ bash, will terminate all instances of Bash,
nals to processes, including polite re­ mand can be combined with other including the shell in which you typed
quests to stop working. As you might ex­ tools, such as grep, in the normal way. the command. However, you can specify
pect, non-privileged users are only al­ For example, you could do the following the -i option to switch to interactive
lowed to talk to their own processes, to find processes with ssh in their mode, which lets you choose which pro­
whereas the root user can send signals names: cesses to kill on an individual basis:
to any process.
Typing kill -I shows you the instructions ps aux | grep ssh $ killall -i bash
that kill passes to a process (Figure 4). killall -i bash
The following are the most relevant for Besides a running SSH server (sshd), Kill bash(1636) ? (y/N) n
your daily work: the list includes all of your SSH connec­ Kill bash(3689) ? (y/N) y
• SIGHUP tells a process to restart im­ tions. To send the same signal to all of Kill bash(3709) ? (y/N) n
mediately after terminating and is these processes, you would normally
often used to tell servers to parse mod­ list the PIDs in the kill command line, The command outputs the PID and
ified configuration files. which can be tricky if the list is too prompts you for each process that
• SIGTERM is a request to terminate that long. Using killall gives you a work­ matches the name you specified. At this
allows the process to clean up. around - the tool understands all of the point, you can decide whether to let the
• SIGKILL forces a process to terminate, kill signals but expects process names process live (by pressing the N) or
come what may. But, in some cases, it instead of IDs. The next section ex­ whether it’s “time to say goodbye” (by
takes more to get rid of the process. plains how to use killall, and more in- pressing the Y).

Foreground and
Background Processes
In some cases, a program you launch in
the shell might run for an extended pe­
riod of time. Graphical programs that
you launch in a terminal window block
the shell, preventing any command

56 LINUX SHELL HANDBOOK - 2023 EDITION


Managing Processes MANAGEMENT

Listing 4: Using Renice


$ renice -n 10 1940
renice: failed to set priority for 1940 (process ID): Permission denied
$ sudo renice -n 10 1940
an ampersand, you can press the key­
[sudo] password for huhn:
board shortcut Ctrl + Z to send it to sleep.
1940 (process ID) old priority 19, new priority 10
The shell confirms this action as follows:

input. In cases like these, you can run Besides the process ID, you can also Az
out and grab a coffee or open a second see the job ID in square brackets. The [4]+ Stopped gimp
console and carry on working. As an al­ job ID is allocated as a consecutive num­
ternative, you can move the process into ber by the shell. If you launch another If you now type bg (background), the
the background, either when you start it program in the same session, you will process will continue to run in the back­
or at a later time. see that Bash assigns job ID 2. The jobs ground. The job ID is useful if you have
To move a process into the back­ command (Listing 5) tells you which stopped several processes in a shell. The
ground when you launch it, just add the jobs are running in the current shell. bg %3 command tells the process with
ampersand character (<&) to the com­ After a program has completed its job ID 3 that it should start working
mand line (Listing 5). For the Gimp win­ task, the shell displays the job ID along again. In a similar way, the fg (fore­
dows launch, the shell informs you of with a status message (Done) and the ground) program moves jobs into the
the process ID (4302), and Bash can then program name: foreground. Again, this program might
accept more commands. need more details in the form of a job ID
[1] Done gimp following a percent character.

The job ID is also Detached


useful if you need The commands I have covered here move
to move a back­ processes to the background and option­
ground process ally let them continue running. If you
into the fore­ close the shell in which you launched the
ground or vice program, this also terminates all the active
versa. If you processes. The nohup program protects a
launch a program process from the shell’s HUP signal (see
Figure 4: The -I option outputs a list of kill signals. without appending the section “Talk to Your Processes”), thus
allowing it to continue running after you
More Detective Work close the terminal session. In other words,
this cuts the ties between the child pro­
If you are looking for process IDs, a combi­ The pkillcommand, which is an abbrevia­
nation of ps and grep is a good idea, but tion for the Linux "hit squad," under­ cess and its parent. To unhitch the process
you can save some typing by running stands the same options as pgrep and is from the shell, type nohup plus the com­
pgrep instead. To find all processes with run against processes by specifying a sig­ mand name and add an ampersand to
ssh in their names, do: nal in the same way as kill: send the process to the background:
$ pgrep ssh pkill -19 ssh
1451 Another practical aspect is that adminis­ $ nohup sleep 1000 &
1710 trators can target another user's processes [4] 4497
4660
by setting the -uflag:
nohup: ignoring input and P
# pgrep -Ifu petrosilie
If you need more context, just add the -I appendingoutput to 'nohup.out1
parameter, and pgrep will also reveal the 7682 Sleep 4000000000
names. To discover the full command line, 7792 bash
including all arguments, combine -/and -f. The output tells you that the process will
[...] go on running, even if you type exit or
$ pgrep -If ssh
# pkill -19 -u petrosilie press Ctrl + D to quit the shell. At a later
1451 /usr/bin/ssh-agent ...
To do this, root simply passes in the user­ time, you can check the nohup.out file to
1710 ssh 192.168.2.5 name as an option, as shown in the pre­ see what the program did while you
4660 /usr/sbin/sshd ceding command.
were away. ■

LINUX SHELL HANDBOOK- 2023 EDITION 57


MANAGEMENT Package Management Tools

Command-line software managers provide an easy way to install programs, games, fonts, and themes. Get
to know your system’s manager, and you'll never have to worry about searching for software on the Internet.
BY BRUCE BYFIELD AND PAUL BROWN

hen you install software in Debian and Debian operation. In practice, apt rarely needs

W Linux, dependencies (the nec­


essary libraries and utilities)

Debian package system was the first to


Derivatives
Debian and derivatives like Linux Mint
theUbuntu manage packages with
are added automatically. Years ago,and
dpkg. Many graphical interfaces are
options, having folded a few common
ones into sub-commands.
A sub-command must always be pres­
ent for both apt and apt-get, but for
include this feature, and a whole ecosys­ available, but for complete control, the some maintenance tasks, you do not
tem of utilities has grown up around it. only practical solutions is the dpkg front need a specific list of packages. To in­
Soon after, most other distributions end, Advanced Package Tool (APT) [1]. clude multiple packages, either list the
added their own dependency-resolving APT can be configured from /etc/apt/ packages separated by a space or use
features. Today, software installations preferences, although most people prefer regular expressions, such as the asterisk,
rarely fail because a dependency wasn’t to configure it through sub-commands although doing so can make trouble­
installed. The dreaded “dependency and options. shooting more difficult and sometimes
hell” is mostly a thing of the past, unless The apt command combines the basic lead to unforeseen results.
you try to install from poorly maintained options of apt-get and popular utilities If the packages to install are related, £
third-party sources or mix packages from such as apt-cache into a single command look for a metapackage, which is a
different repositories. and adds a progress bar (Table 1). If you dummy package meant to simplify the |
Linux includes far too many different ever need the old tools, or simply prefer installation of large applications that |
package managers to cover them all in a them, they are still installed by default. are split into more than one package. £
single article. Presented here are only Unlike most commands, apt and apt-get For instance, to run the Gnome desktop 32
the most widely used ones, from consist of three parts separated by spaces: environment in Debian, gnome saves |
Debian and Fedora, along with the so- the basic apt-get command, a sub-com­ you the effort of installing dozens of |
called universal package managers. mand, and the packages involved in the packages separately. To see whether a

58 LINUX SHELL HANDBOOK - 2023 EDITION


Package Management Tools MANAGEMENT

Table 1: apt and apt-get Compared*


Function apt apt-get

Display package information dpkg list list


Find available packages apt-cache search search
Display package information apt-cache show, dpkg-query -list show
Install software packages install install
Remove software packages remove remove
Remove no longer needed packages autoremove autoremove
Update sources list update update
Upgrade installed packages dist-upgrade upgrade
Upgrade installed packages, removing packages to avoid conflicts dist-upgrade full-upgrade
Edit repository list Open /etc/apt/sources.list in text editor edit sources
*Note: apt a Iso includes color-coded output and minor changes in the ordering of results.

metapackage exists for your purposes, if you go through with the installation, in­progress, as well as the download speed
search online in your distro’s reposito­ cluding the dependencies that will be in­ and the amount of time required to fin­
ries; if all else fails, guess its name, and stalled, the packages that will be up­ ish the operation. The times are only es­
see whether you are successful. graded and removed, and the amount of timates and will change as the Internet
Depending on whether you are using disk space that will be required. Unless connection speed changes. Once the
apt-get or apt, the basic command for the action can proceed automatically downloads are complete, both install the
adding or upgrading a software package without affecting anything else, you then software, sometimes pausing to ask
is either can confirm or cancel the process (Fig­ questions about how you want it in­
ure 1). Usually, you should read the sum­ stalled. With apt, you also get a progress
apt-get install options <packagename> mary carefully before continuing, just to bar. After everything is done, the com­
be sure what you typed doesn’t include mands then exit with a summary of any
or any unpleasant surprises. If you are using problems encountered, if necessary. As a
a non-standard online repository, it might final touch, the software you just in­
apt install <packagename> not be verified automatically as a valid stalled is added to desktop menus.
source. When that happens, you should In apt-get, the basic command for in­
Deleting a package uses the same struc­ only continue if you are absolutely sure stalling software can be modified with a
ture, except the sub-command is remove. that you can trust the repository. number of options. For example, you
Both apt and apt-get usually start with As apt or apt-get works, it shows might want to use -s to simulate the in­
a complete summary of what will happen which package is downloading and its stallation without actually doing any-
thing, just to make
nanday:-# apt-get install wesnoth sure you uncover any
Reading package lists... Done problems before the
Building dependency tree
real installation. If the
Reading state information... Done
installation reports
The following packages were automatically installed and are no longer required:
libboost-regexl.37.0 libboost-iostreams1.37.0 any problems, you
Use 'apt-get autoremove' to remove them. can run the command
The following extra packages will be installed: again, this time with
ttf-wqy-zenhei wesnoth-all wesnoth-aoi wesnoth-core wesnoth-data wesnoth-dbg the -/'option, in the
wesnoth-did wesnoth-editor wesnoth-ei wesnoth-httt wesnoth-1 wesnoth-low hopes that apt-get can
wesnoth-music wesnoth-nr wesnoth-sof wesnoth-sotbe wesnoth-thot wesnoth-tools intelligently provide a
wesnoth-trow wesnoth-tsg wesnoth-ttb wesnoth-utbs
solution, or with -m
The following packages will be upgraded:
to ignore any missing
ttf-wqy-zenhei wesnoth wesnoth-all wesnoth-aoi wesnoth-core wesnoth-data
wesnoth-dbg wesnoth-did wesnoth-editor wesnoth-ei wesnoth-httt wesnoth-1 dependencies in the
wesnoth-low wesnoth-music wesnoth-nr wesnoth-sof wesnoth-sotbe wesnoth-thot hopes that you will
wesnoth-tools wesnoth-trow wesnoth-tsg wesnoth-ttb wesnoth-utbs get satisfactory re­
23 upgraded, 0 newly installed, 0 to remove and 1207 not upgraded. sults. However, both
Need to get 255MB of archives. -/and -m must be
After this operation, 11.0MB of additional disk space will be used. used with extreme
Do you want to continue [Y/n]? []
care and only as a
Figure 1: Before doing anything, both apt and apt-get explain what they will do and give you a chance to back out of last resort, because
the operation. The only visible difference between the two commands is that apt includes a progress bar rather a they can lead to a
percentage-complete field. broken system.

LINUX SHELL HANDBOOK- 2023 EDITION 59


MANAGEMENT Package Management Tools

The most common useful option for dpkg -i digikam_'±_li_‘±-l. I_amd64.deb To help with these basic operations,
installation is -t <repository>, which al­ dpkg and apt-get include a number of
lows you to specify the online repository For other options, the command struc­ utilities, apt has only a few of these utili­
from which you want to install the pack­ ture is the same, except for the change in ties, presented as sub-commands. When
ages and all its dependencies. This op­ the sub-command. Even the available you run into difficulties and are seeking
tion is especially useful in Debian, options are the same, although some information, the command dpkg-query
whose main repositories (stable, testing, might not make sense with every sub­ or apt show can give you detailed infor­
and unstable) describe the state of the command. The remove sub-command mation about the packages involved. For
software. For example, if you want the uninstalls software, whereas the purge example, if you type
very latest version of Gnome, even if it sub-command removes all traces of a
has not been well-tested, you can down­ package, including things like configura­ dpkg-query -p kdepim4_4_4-l.Iamd64.deb
load it from the Debian unstable reposi­ tion files, from your computer (neither,
tory by entering: however, removes dependencies, which or
is why you might need to run some of
apt-get -t unstable install gnome the maintenance sub-commands listed apt show kdepim
later). If you want to upgrade every
No similar option is available for apt. package on your computer, you can use you receive a description of the package
Similarly, in other Debian-based distri­ the dist-upgrade (or the apt equivalent that lists contact information for the de­
butions, you might have added a devel­ upgrade) command rather than entering velopers who maintain it; the package’s
opment branch of the software to your every package individually. dependencies, size, and description; and
repositories or a privately developed ver­ Most people use the Debian package the homepage for the development team
sion of software that you only want to system to install precompiled binary (Figure 2). Similarly, you can use the -s
use occasionally. With this option, you files. However, if you want to ensure that option to determine the status of a file or
can downgrade a package when the all your software runs as efficiently as -L to see a list of all the files included in
most recent version is buggy or not possible on your system, you can use the the application’s package. All this infor­
working. source sub-command to download mation can be invaluable if you run into
If you are an expert, you could also source packages and the -b option to trouble, regardless of whether you want
download a single package to your compile them on your computer. If the to solve the problem yourself or find
hard drive for installation. In that case, source requires dependencies, you can someone to help you.
you would go directly to dpkg. For ex­ use the build-dep sub-command. Note, The apt-get command includes several
ample, if you downloaded a develop­ however, that compiling source packages other utilities in the form of sub-com­
ment version of the digiKam image can take considerable time, particularly mands that are issued without referring
manager, you could install it by chang­ with a large application - perhaps even a to any packages. Just as you might use
ing to the directory containing the matter of hours with an application like fsck to investigate and repair the struc­
package and entering: LibreOffice. ture of a filesystem, you can use the fol­
lowing command
nanday:~# dpkg-query -p kdepim
Package: kdepim
apt-get check
Priority: optional
Section: kde
Installed-Size: 68 to ensure that the package
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org> system is working properly.
Architecture: all
The more you install and
Version: 4:4.3.0-1
Depends: akregator (>= 4:4.3.0-1), kaddressbook (>= 4:4.3.0-1), kalarm (>= 4:4.3.0-1
uninstall, the more regu­
), kdepim-kresources (>= 4:4.3.0-1), kdepim-wizards (>= 4:4.3.0-1), kmail (>= 4:4.3. larly you should consider
0-1), knode (>= 4:4.3.0-1), knotes (>= 4:4.3.0-1), konsolekalendar (>= 4:4.3.0-1), k running apt-get with the
ontact (>= 4:4.3.0-1), korganizer (>= 4:4.3.0-1), ktimetracker (>= 4:4.3.0-1), kdepi clean and autoclean sub­
m-strigi-plugins (>= 4:4.3.0-1), kjots (>= 4:4.3.0-1), kpilot (>= 4:4.3.0-1), kleopa
commands. The clean com­
tra (>= 4:4.3.0-1)
Suggests: kdepim-doc mand removes all the pack­
Size: 16052 ages you have downloaded
Description: Personal Information Management apps from the official KDE release and installed while retain­
KDE (the K Desktop Environment) is a powerful Open Source graphical ing the installed software,
desktop environment for Unix workstations. It combines ease of use,
and autoclean removes all
contemporary functionality, and outstanding graphical design with the
technological superiority of the Unix operating system. packages that have become
obsolete and can no longer
This metapackage includes a collection of Personal Information Management be downloaded. By run­
(PIN) applications provided with the official release of KDE.
ning both occasionally, you
Homepage: http://pim.kde.org/
can free up extra space on
Figure 2: The dpkg-query utility tells you everything you could ever want to know about each software pack­ your hard drive without af­
age. Alternatively, you can use apt show. fecting the system.

60 LINUX SHELL HANDBOOK - 2023 EDITION


Package Management Tools MANAGEMENT

Another useful
maintenance sub­ [ root@local.host -]# dnf install sil-gentium-basic-book - fonts
Dependencies resolved.
command for
apt-get is autore­
move, which re­ Package Arch Version Repository
moves orphaned Size
packages (i.e.,
ones that serve no Installing :
sil-gentium-basic-book - fonts noarch l.l-10.fc20 fedora 240 k
purpose, because
sil-gentium-basic-fonts-common noarch l.l-10.fc20 fedora 22 k
they were added
as dependencies Transaction Summary
for an application
that you have Install 2 Packages
since removed).
Because these or­ Total download size: 262 k
Installed size: 1.1 M
phans do nothing Is this ok [y/N]: |
but fill space on
your hard drive, Figure 3: DNF gives complete information about what actions it is about to perform.
you might as well
remove them. The Debian package sys­ positories in sources, list and specifying package manager has for years been
tem keeps track of orphans and will re­ the -t option for setting the sources from Yum (originally, Yellowdog Updater,
mind you that they exist when you run which to install. In this way, you have Modified). However, in the past few
apt-get for some other purpose. less chance of making a mistake. years, it has started to be replaced by
Yet another bit of maintenance you Depending on your distribution, soft­ DNF [2] - DNF doesn’t stand for any­
might want to perform is to add or re­ ware installation can involve a number thing in particular; It is just a random
move online repositories from /etc/apt/ of other associated utilities. By far, the collection of letters - a new package
sources.list. With apt, the command is most useful package utility is apt-cache, manager that improves on some of
simply apt edit-sources. With apt-get, you which offers a treasury of information Yum’s shortcomings.
can open the sources.list file in any text about packages and your system. For Just as apt-get in Debian provides
editor. The sources.list file points to all the example, users with access to the functionality of
online repositories that apt-get and dpkg dpkg, so do DNF and Yum act as wrap­
use. Each repository is listed on its own apt-cache showpkg <packagename> pers for rpm, the basic command for
line according to a simple system. The RPM package management. The main
entry for each repository begins with deb shows which version you have installed, difference is that, whereas dpkg resolves
if it is a repository of binaries and deb-src the latest version available in the reposi­ dependency problems on its own, rpm
if it is a repository of source packages. tories you are using, and the reverse de­ does not. That functionality resides en­
This information is followed by the repos­ pendencies of the packages (i.e., which tirely in DNF and Yum.
itory URL, name, and subsections. packages depend on it). DNF shares a common structure
Sources are disabled with a hash sign (#) Similarly, the commands with Yum. Like apt-get, Yum has a
at the start. Typically, hash symbols also consistent basic format: the basic
are used to add comments that humans apt-cache dump command (dnf or yum), any options,
can use to identify the source. apt-cache stats the sub-command (what you are
When you add or remove a repository doing), and the packages involved.
from sources.list, you must then run list all the packages you have installed The main difference is in the list of
and offer information such as the num­ sub-commands involved.
apt-get update ber of installed packages and the total The sub-command that you will prob­
number of dependencies. An especially ably use most often is install. For in­
or useful option is stance, if you plan to install the Book
typeface for the free Gentium font, the
apt update apt-cache search <packagename> basic command in Fedora would be:

to change the repositories that are in which tracks down the exact name of a dnf install 7
use. Otherwise, the package system con­ package or packages that you might sil-gentium-basic-book-fonts
tinues to use previously identified repos­ want to install.
itories. Editing and then updating takes a When you enter the command, DNF de­
few minutes to complete each time but Fedora and Related termines the dependencies (Figure 3).
has the advantage of ensuring that you Distributions In the example above, DNF would note
know precisely which sources you are In RPM-based distributions such as Fe­ that it requires the package sil-gentium-
using. Some users prefer enabling all re­ dora, Red Hat, and CentOS, the main basic-fonts-common, which is needed

LINUX SHELL HANDBOOK- 2023 EDITION 61


MANAGEMENT Package Management Tools

with any weight of Gentium you install. mand to see what is available before move, followed by the name of the
It then lists the amount of hard drive installing anything. Or, you might pre­ group. For instance
space needed both to download and in­ fer to specify particular packages to
stall the packages. upgrade instead. dnf group KDE
Once you press y (for “yes”) to con­ All of these basic sub-commands are
tinue the installation process, DNF be­ available for use on multiple packages. The would add all the files in the KDE group
gins to download the necessary pack­ simplest way to handle multiple packages to your system.
ages, showing the progress of each is to enter them in a space-separated list at All packages or groups installed can be
download and of the overall process the end of the command. Alternatively, removed using the erase sub-command.
(Figure 4). After the downloads are com­ you can use regular expressions. If you do, Besides these basic commands, DNF
plete, DNF installs each package and check carefully the summary provided by includes several that provide informa­
summarizes what it has done. If it is suc­ DNF before proceeding, because you might tion or help you maintain your system.
cessful, a succinct Complete! displays get unexpected results. The most basic sub-command, list, is
just before DNF exits. Some repositories organize packages completed by descriptions of the infor­
To install a newer version of a pack­ into groups. In Fedora, for example, mation you want. For instance
age, you can also use install, but a bet­ the package groups include Games and
ter choice is the upgrade sub-command, KDE. These groups serve much the dnf list installed
because it can handle the removal of same function as metapackages on dnf list available
any obsolete dependencies - an ability Debian systems, allowing you to install
that is especially useful when you are multiple packages without having to displays a complete list of installed and
switching from one version of a distri­ remember them or edit them sepa­ available packages.
bution to another. rately. Groups have a series of special When you want more specific informa­
If you are cautious, you might pre­ sub-commands that include groupin- tion about a package, the sub-command
fer to use the check-update sub-com­ stall, groupinfo, grouplist, and groupre- to use is info followed by the package
name (Figure 5).
Is this ok [y/N]: y The info command
Downloading Packages: provides basic infor­
(1/2): sil-gentium-basic-fonts-common-1.1-10 6.4 kB/s | 22 kB 00:03
(2/2): sil-gentium-basic-book-fonts-1.1-10.f 60 kB/s | 240 kB 00:04 mation about the
package: its architec­
Total 47 kB/s | 262 kB 00:05 ture; its version num­
Running transaction check ber and release;
Transaction check succeeded. whether it is installed
Running transaction test
or, if not, what repos­
Transaction test succeeded.
Running transaction itory it is in; its li­
Installing : sil-gentium-basic-fonts-common-1.1-10.fc20.noarch 1/2 cense; and its
Installing : sil-gentium-basic-book-fonts-1.1-10.fc20.noarch 2/2 homepage. Also, you
Verifying : sil-gentium-basic-book-fonts-1.1-10.fc20.noarch 1/2 will receive a single­
Verifying : sil-gentium-basic-fonts-common-1.1-10.fc20.noarch 2/2
sentence summary
Installed: and a slightly longer
sil-gentium-basic-book-fonts.noarch 1.1-10.fc20 description. The sub­
sil-gentium-basic-fonts-common.noarch 1.1-10.fc20 command groupinfo
provides similar in­
Complete!
formation for pack­
Figure 4: DNF installing a package. age groups.
A rarer but occa­
[ root@localhost -]# dnf info firefox II sionally useful sub­
Installed Packages 1 command is pro­
Name firefox vides, with which
Arch i686
you can find the
Epoch 0
Version 38.0.5 package that includes
Release l.fc20 a particular file or
Size 116 M feature (Figure 6).
Repo ^System For example, the
Summa ry Mozilla Firefox Web browser command
URL http://www.mozilia.org/projects/firefox/
License MPLvl.l or GPLv2+ or LGPLv2+
dnf provides firefox
Desc ription Mozilla Firefox is an open-source web browser, designed for
standards compliance, performance and portability.
returns exactly
Figure 5: The info sub-command gives you all available information about a package. which package ver-

62 LINUX SHELL HANDBOOK - 2023 EDITION


Package Management Tools MANAGEMENT

sion is available or installed, as well as ularly powerful maintenance tool is You will only inconvenience yourself if
the versions found in the repositories. clean, which, like list, is completed by a you run it casually.
Another means of tracing references to description of the information source Most of the time, you can use DNF
a specific package is the search sub-com­ you want to remove. However, with the without any options. A few options pro­
mand. This function will locate all pack­ exception of the command vide useful information to help you ad­
ages and dependencies related to the minister software installation. A great
search term, followed by a brief descrip­ dnf clean packages many more enable or disable informa­
tion. search can be useful for finding tion for various purposes. Some options,
packages when you lack an exact name which removes packages that were such as -v (--verbose), which increases
or are reasonably sure that a function downloaded but not installed, using the amount of information DNF pro­
must be available somewhere. clean is an act of desperation. Running vides, are useful mainly for program­
All of these information sub-com­ clean followed by any other option - mers who are debugging.
mands frequently give dozens, even such as metadata, dbcache, or all - re­ Other options are for users who want
hundred, of lines of output. For this rea­ moves information that DNF requires to use DNF with a minimum of fuss, such
son, consider piping them through the to operate. as -quiet, which causes DNF to run with­
less command by adding | less to the end The next time you start DNF after run­ out reporting what it is doing. Its frequent
of the command so that you can scroll ning clean with these completions, DNF companion is -assumeyes, which as­
through at your leisure. will rebuild what was deleted, but re­ sumes that the answers to all questions
DNF sub-commands also include a building could take a few minutes de­ are Yes - including the question of
number of utilities that can help you pending on your machine. For this rea­ whether you want to proceed after DNF
maintain and troubleshoot your system. son, you should only run the clean sub­ finishes its initial calculations. In much
command when you are having trouble the same way, -nogpgcheck disables
dnf makecache with DNF. Unlike apt-get's clean and au­ package verification, and -allowerasing
toclean, DNF’s clean is not for routine permits DNF to erase installed packages
downloads the information for all pack­ maintenance, but for major problems. without asking to resolve any depen­
ages in all enabled repositories, which
you can use if the information is cor­ [ root@localhost -]# dnf provides firefox
rupted or outdated or if you have re­ firefox-38.0.5-1.fc20.i686 : Mozilla Firefox Web browser
cently changed repositories. Similarly, Repo : @System
for the rare time that problems emerge,
reinstall lets you try again, whereas firefox-25.0-3.fc20.i686 : Mozilla Firefox Web browser
Repo : fedora
downgrade lets you revert to a specific
version to avoid the current program
firefox-38.0.5-1.fc20.i686 : Mozilla Firefox Web browser
that is causing problems on your system. Repo : updates
When problems occur, the sub-com­
mand history can help you review recent Figure 6: If you wonder about the origins of files or applications, dnf provides can give you the
package activity on the system. A partic­ information.

IT Highlights at a Glance
LINUX Linux Update
UPDATE
ADMIN Update
ADMIN HPC

Keep your finger on the


ifti _.m»Ul|
pulse of the IT industry.

Too busy to wade through press releases and chatty tech news sites?
Let us deliver the most relevant news, technical articles, and tool tips - straight to
your Inbox.

Admin and HPC: https://bit.ly/HPC-ADMIN-Update


Linux Update: https://bit.ly/Linux-Update
MANAGEMENT Package Management Tools

dency problems. Such options save time; using universal packages, although changes, which lists all the snap-re­
however, use them cautiously to avoid users should note that combining tradi­ lated actions performed on the system,
unpleasant surprises. tional package managers with universal as well as list, which displays all the
Other options are less likely to cause ones complicates system care and secu­ snap packages on the system. For
trouble. The matched pair -enable-repo= rity. However, both traditional and uni­ more information, see the Snap project
and disable-repo= specify which reposi­ versal packages have mostly the same website [6].
tories to use. Also, you can use -ex­ functionality, as well as the same sub­ The success of universal packages, or
clude = to prevent packages that could commands. how they compete with each other, are
cause a conflict from installing from The first universal package system was still unanswered questions. The most
any source. Applmage [3]. It remains by far the sim­ common use on the desktop appears to
Another option that might keep you plest. With Applmage, you download a make new versions of applications avail­
out of trouble is -skip-broken. If you use compressed image that includes all the able quickly.
it after DNF reports a missing depen­ necessary dependencies, change its per­
dency, it might just allow you to resolve missions to make it executable, and then Conclusion
the difficulty. In some cases, packages run it. No installation is required beyond Other package managers also exist, no­
installed with this option will not work, downloading. To remove an Applmage tably Arch’s pacman, openSUSE’s Zyp-
but you can make sure they do not form package, delete it as you would any per, and Gentoo’s Portage. However,
a bottleneck that keeps DNF from work­ other file. although the details differ, once you
ing. Once they are installed, you can Developed by Red Hat, Flatpak is de­ have used a couple of package manag­
then delete them normally. signed primarily to install software on ers, you will find that all have the
the Gnome desktop. Its online reposito­ same basic set of commands. These
Universal Packages ries are called remotes. You can see a list commands include commands for
Most package managers reflect a time of remotes using the command flatpak managing repositories, searching for
when disk memory was scarce. Having remotes. Other commands are equally packages, and installing and removing
applications share the same library made simple, with immediately recognizable packages. Often, the sub-commands
economic use of space. However, for sub-commands like search, update, and are identical.
over a decade, disk space has become repair, followed by the package name. To Whatever package manager your
much larger and is less of an issue. At install a package, you can either specify distribution uses, it is sure to make
the same time, a demand has developed a remote plus the package, or else the using software easier. Thanks to pack­
for delivering updates in a single pack­ URL of a flatpak.ref file; for example: age managers, you do not need to
age to containers and embedded sys­ search the Internet for software. Nor
tems. These changed conditions have led flatpak install flathub org.gimp.GIMP do you have to worry that the soft­
to the creation of so-called universal ware will be buggy or a security risk,
package managers like Applmage, or although you should investigate how
Flatpak, and Snap. your distribution handles security up­
Much has been claimed for universal flatpak install 7 dates to avoid problems.
package managers that has not been re­ https://flathub.org/repo/appstream/P These days, most distributions have
alized and probably never will. For in­ org.gimp.GIMP.flatpakref desktop applications for package man­
stance, they are often said to be more agement. However, these desktop man­
secure than traditional package man­ To run a package, specify its ID. For ex­ agers are almost always front ends for
agement systems, because they can de­ ample: command-line tools. Open up a terminal
liver updated versions more quickly. and get to know the tools that do the
However, the weak link is the packagers flatpak run org.gimp.GIMP heavy lifting, and you will have taken a
and system administrators, who may giant step toward learning how to ad­
not deliver or install updates immedi­ A complete list of commands is available minister your system. ■
ately. More importantly, many projects from the Flatpak website [4].
are not oriented to producing packages, Snap packages are developed by Ca­ INFO
having traditionally left making pack­ nonical, the company behind Ubuntu.
[1] APT: https://wiki.debian.org/Apt
ages to the distributions. In practice, Although designed for embedded sys­
too, distributions have their own way of tems, snap packages also rival Flatpak [2] DNF: https://fedoraproject.org/wiki/
managing packages, even when using on the desktop. Just as with phone DNF?rd=Dnf
the same manager, so one package for apps, snaps are available from an on­ [3] Applmage: https://appimage.org/
all distributions is more of a challenge line store [5], although you can also [4] Flatpak: http://docs.flatpak.org/en/
than might be assumed. use the command structure snap find latest/using-flatpak.html#
However, universal packages do offer < package > from the command line. basic-commands
advantages, such as the ability to install Installation uses the format snap in­ [5] Snap online store: https://snapcraft.
different versions of any package on a stall < package >; the refresh sub-com­ io/store
single system. As a result, many major mand is used to update a package.
[6] Snap: https://snapcraft.io/
distributions include the commands for Snap also includes the sub-command

64 LINUX SHELL HANDBOOK - 2023 EDITION


dd and mkisofs/genisoimage/xorrisofs MANAGEMENT

Creating images for CDs, DVDs, and flash drives

MIRROR IMAGE
Whether you are creating backups, rescuing data, or burning bootable
CD, DVD, flash or Blu-ray media, shell commands help you handle the
job in style. BY HEIKE JURZIK; REVISED BY BRUCE BYFIELD

he command line has applications tions, CDs, or DVDs. Also, dd supports re­ and writes them to the output file. If you

T for burning data CDs, DVDs,


flash, or Blu-ray disks. Before you

first need to create an ISO image - that is,


liable, blockwise reading and writing oper­
ations. Because dd does not process or in­
can actually burn a disk, however, youterpret these blocks, the underlying filesys­
tem is not important. In fact, dd isn’t even
select a larger block size, you can speed
up this process. For example, typing

dd if=/dev/sdal of=/dev/sdbl bs=2k


an archive file for your optical disk. ISO fazed by hard disks with errors (see the
images usually have the file extension “Rescuing with dd” section). The basic tells dd to copy the partition in blocks of
.iso. The name is taken from the ISO 9660 command syntax for dd is: 2KB (2048 bytes). If the last block is
standard, which is the standard filesys­ smaller than the specified block size, dd
tem for managing files on CD-ROMs. ISO dd if=<source> of=<target> will not pad it:
images can also contain a UDF filesystem
used by DVDs and Blu-ray disks. The if option tells dd where to read the $ dd if=/dev/sdal of=/dev/sdbl bs=6k
Regardless of the filesystem, you can source data (input file), and the of op­ 16059+1 records in
create ISO images using one of two tools. tion defines the destination (output file). 16059+1 records out
The first is the dd command, which gen­ The source and target are often devices, 98670592 bytes (95 MB) copied P
erally allows copying from any source, such as hard disk partitions or CD/DVD 13.801482 s,6.9 MB/s
as well as the creation of ISO images. drives. Alternatively, you can use an
The command is especially useful for equals sign to point to a file. To copy the The output tells you that dd has copied
rescuing data on a dying hard disk. hard disk partition /dev/sdal bit for bit 16059 blocks of 6144 bytes each with
Alternatively, you can create an ISO to /dev/sdbl, you could type: one remaining block of 4096 bytes.
image with mkisofs, genisoimage, or xorr- Besides block size, you can specify
isofs. Which of these tools is available to dd if=/dev/sdal of=/dev/sdbl how many blocks dd reads. To copy
you depends on your distribution. Be­ 40MB, just write bs = IM count = 40.
cause of licensing issues, few if any distri­ You can also use dd in the shell to copy a The count option specifies the number
butions still use mkisofs, although it is CD or DVD quickly. To create an ISO of blocks. This makes sense if you want
still available as part of CDRTools. How­ image, for example, use the command: to save a hard disk boot sector; for ex­
ever, because of licensing issues with ample, entering
mkisofs, Debian uses genisoimage. Also, $ dd if=/dev/srO of=myimage.iso
genisoimage has not been updated for 1529961+0 records in dd if=/dev/sda of=bootsector P
several years, so distributions like Ubuntu 1529960+0 records out bs=512 count=l
and Linux Mint use xorrisofs. All these 783339520 bytes (783 MB) copied, 7
tools do the same job and understand al­ 90.6944 s, 8.6 MB/s will just copy the first 512-byte block.
most all of the same options. You can use
any of them to back up your data auto­ When you are using dd, you do not need Rescuing with dd
matically, and even to exclude individual to mount the medium to perform a quick If you are faced with the daunting task of
files if necessary. copy: Just replace the /dev/srO drive desig­ rescuing data from damaged filesystems,
nator with the device name for your drive. dd is essential. Before you repair the
Converting and Copying The ISO image is written to a file called damage, you first should create a backup
with dd myimage.iso in the current directory. You copy. To do so, use dd to create a 1:1 copy
= The dd tool does far more than create ISO can rename the file as necessary. of the damaged system and then use the
° images. It really should be called cc - for copy for your rescue attempt.
3 convert and copy. However, because this Optimizing dd Options Because dd excludes defective sectors
name had already been assigned to the C The dd tool also has a number of options. from the copy by default, you need to
£ compiler, the developers just chose the One practical option that speeds up the enable the conv = noerror,sync option,
| next letter in the alphabet when naming it. program considerably is bs (for “block
| The dd tool creates exact copies of size”). By default, dd uses 512-byte dd bs=512 conv=noerror,sync P
" media, whether they are hard disk parti­ blocks; that is, it reads 512 bytes at a time if=/dev/sda of=/dev/sdb

LINUX SHELL HANDBOOK- 2023 EDITION 65


MANAGEMENT dd and mkisofs/genisoimage/xorrisofs

which tells dd to continue reading and genisoimage P Creating Bootable Media


storing data, even if it discovers defec­ - V "Backup, 29th of June" ... A bootable medium can be used to start
tive sectors. The noerror tag tells dd not a computer. To create bootable media,
to stop on errors, and sync pads unread­ For more detailed output, you could en­ just add the Isolinux bootloader [1],
able sectors with zeros. able the -v (verbose) option. The oppo­ which works hand in hand with geniso­
site of the verbose option is -quiet. If you image or xorrisofs:
Generating ISO Images prefer to avoid seeing status messages in
The mkisofs command used to be the your terminal window but don’t want to genisoimage -J -R -o booted.iso P
most common for creating ISO images in do without the information these mes­ - b isolinux/isolinux.bin P
Linux. Because of licensing issues and sages provide, use - c isolinux/boot.cat -no-emul-boot P
some conflicts within the developer com­ -boot-load-size 4 7
munity, genisoimage emerged as a fork of genisoimage ... -log-file log.txt ... - boot-info-table /folder/data
the mkisofs codebase. Another tool called
xorriso offers a range of ISO creation and to pipe the output of the genisoimage The additional genisoimage options in the
manipulation features. The xorrisofs com­ command to a logfile. preceding command are: -b to name the
mand launches xorriso in mkisofs emula­ boot image and -c to specify the boot cat­
tion mode. The result is that mkisofs, gen­ Creating Backups alog. The -no-emul-boot parameter tells
isoimage, and xorrisofs all have very simi­ Genisoimage and xorrisofs have a number the program not to create an emulation
lar features and command-line options. of practical options for creating regular when installing from this CD; instead, it
Check your own Linux distribution to see backups. For example, the -m option lets writes the contents of the image file to
which of these commands is available you exclude files from an image. The file disk. The -boot-load-size 4 option speci­
(they might not all be present). Debian, name arguments follow the option. Gen­ fies that the BIOS should provide four
Ubuntu, and other Debian-based alterna­ isoimage can even handle wildcards and 512-byte sectors for the boot file. Finally,
tives ship with genisoimage, which will multiple names. For example, to ex­ the -boot-info-table option stipulates that
be used in the following examples. The clude all HTML files from your ISO the layout information of the medium
basic syntax for all three is: image, just use the following structure, should be read at boot time. Note that
changing the command as necessary: this information must be stored in the
genisoimage <parameter> P isolinux directory below /folder/data.
- o <myfile>.iso /<directory>/<data> genisoimage ... -m *.html -m *.HTML P
- o backup.iso /home/huhn Testing Images Before
The -o flag lets you define the target Burning
file name. This is followed by the data The -x option lets you exclude whole direc­ The mount utility gives you a practical
you want to store in the image. As an tories; multiple arguments are supported: approach to testing ISO images before
optional parameter, you can tell the burning them to CD. To test your image,
tool to enable Rock Ridge extensions genisoimage ... -x /tmp -x /var P just mount it on your filesystem, specify­
by setting the -r option, which is useful - o backup.iso / ing the -o loop option:
chiefly for enabling longer file names.
To set privileges and file ownership, When you use these parameters, make mount -o loop myfile.iso /mnt/tmp
you could specify -R. The Joliet exten­ sure you avoid using wildcards when
sion, which enables the support of specifying the files you want to write to The mountpoint must exist, and you do
non-Latin characters, is enabled by the the image. For example, the command need root privileges for this command.
-J flag: After completing the test (Figure 1), you
genisoimage ... -m *.html -m *.HTML P can unmount the ISO image again by en­
genisoimage -J -R P -o backup.iso * tering amount /mnt/tmp.
- o <myfile>.iso /<directory>/<data> Some distributions also include the
tells the shell to resolve the final wild­ isoinfo tool. You can access all sorts of
The -V option lets you specify a name card, adding all your files to the image. information with it. To do so, specify the
(volume ID) for the CD/DVD. If the If you want to exclude files with typi­ image file name after -i; -d outputs the
name includes blanks, special charac­ cal backup extensions, such as files end­ report to the terminal.
ters, or both, don’t forget to use double ing in ~, #, or .bak, just specify the -no- If you want to find out which files are
quotation marks: bak option. included in the ISO image, use -I instead
of -d. Figure 1 shows the “content” of
root@jessie: “/test the Blu-ray image that was created with
root@jessie:~/test# isoinfo -1 -i blu-ray-test .iso genisoimage-udf. ■
Directory listing of /
d....... 0 0 0 2048 Jun 30 2015 [ 267 02] .
d------- 0 0 0 2048 Jun 30 2015 [ 267 02] .. INFO
........ 000 3976200192 Apr 27 2015 [ 26800] DEBIAN_8_0_0_AMD64_DVD_1.ISO;1
........ 0 0 0 459570267 Apr 22 2015 [1941772 00] LINUXMINT_17_l_CINNAM0N_64B.IS0;l
root@j essie:-/test#
[1] Isolinux:
http://syslinux.zytor.com/iso.php
Figure 1: The isoinfo tool prints a list of files in an ISO image.

66 LINUX SHELL HANDBOOK - 2023 EDITION


Networking Tools COMMUNICATION

Tools for configuring and troubleshooting network connectivity

CONNECTIONS
The Linux command line provides a powerful collection of utilities for running kernels newer than 2.0. The if­
config command is still available as part
configuring and troubleshooting network connections. This article of the net-tools package, though, and in
rounds up some new and old networking commands. all likelihood, it is automatically installed
on your system.
BY JAMES MOHR, JOE "ZONKER" BROCKMEIER, NATE DRAKE, On newer Linux systems, you also get
FERDINAND THOMMES, AND JOE CASAD the ip command. More than just a
newer version of ifconfig, ip is the
workhorse of the new generation of net­
inux and other Unix-based sys­ later login when a different device is work tools. Not only does it integrate

L tems often offer several alterna­


tives for solving a single problem.

ception to this practice. You’ll find an


added or removed.

mon
The networking tool collection is no ex
Version 197 of the systemd startup dae­
­ unveiled a new method for naming
devices. Instead of assigning consecutive
the functionality of several older tools,
but ip also provides a unified syntax
across all the various functions. In con­
trast, the utilities provided by the net-
array of useful tools - some overlapping device numbers to network devices, sys­ tools package are a patchwork collec­
and some unique - for configuring, man­ temd assigns a predictable network de­ tion of tools that were developed indi­
aging, and troubleshooting network vice name based on identifying informa­ vidually over many years.
connections. tion about the device itself, such as: The ip command is part of the iproute
In this article, we highlight some fa­ • Information provided in the BIOS package. The similarity between the
vorite tools in the networking collection. • The physical location of the hardware tools in this package enables you to mas­
Of course, a full description of the com­ • The interface’s MAC (hardware) ter the configuration of your network
plete TCP/IP networking environment address more quickly because you do not need
could fill up a very long book. Here, we The system uses this information to as­ to learn different syntax options for dif­
assume you have some basic knowledge sign a unique (and reproducible) num­ ferent functions. Furthermore, you don’t
of TCP/IP networking concepts such as ber for the device. This number is then need to remember which utility does
routing, addressing, and name combined with a two-character prefix, what because, for the most part, ip inte­
resolution. such as en for wired Ethernet or wl for grates the capabilities of ifconfig, route,
wireless LAN. For instance, an Ethernet and arp into a single tool.
Interfaces adapter might have a logical name like The generic usage is
The old method for naming Ethernet enp0s31f6 and a wireless network inter­
e adapters and other network devices is face might have the logical name wlp4s0. ip [OPTIONS] <OBJECT> [COMMAND]
£ with a prefix (indicating the device type) The examples in this article use the in­
8 followed by a device number. For in- terface name enp0s31f6 - if you try these where OBJECT is something like ip for
5 stance, the first Ethernet adapter discov- commands, change enp0s31f6 to the log­ your IP configuration, link for a network
| ered by the system took the name ethO, ical name of your own network adapter. interface, addr for your IP address, route
| the next one is ethl, and the third is The ifconfig command was, and still is for routes, and so forth. (The ip command
eth2. This method worked well in most on many systems, the default tool for also supports several other objects - see
| cases; however, it sometimes causes configuring network interfaces. However, the ip man page for more details.)
| complications. For instance, the same ifconfig is often considered obsolete, in In the context of the ip command, a
- device could have a different name at a that newer tools are provided for systems “link” is a network device, real or virtual.

LINUX SHELL HANDBOOK- 2023 EDITION 67


COMMUNICATION Networking Tools

To display the details of a specific inter­ • jcasad@>Thinkie: -


face, you might enter the following: File Edit View Search Terminal Help
jcasad@Thinkie:~$ ip addr show dev enp0s31f6
ip addr show dev enpOsSlfS 2: enp0s31f6: BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast sta
link/ether 54:ee:75:a4:ea:b3 brd ff:ff:ff:ff:ff:ff
inet 10.0.O.121/24 brd 10.0.0.255 scope global dynamic enp0s31f6
This command might give you some­ valid_Lft 2415sec preferred_lft 2415sec
inet6 fe80::2cf8:b850:3274:fcde/64 scope link
thing like the output shown in Figure 1. valid_lft forever preferred_lft forever
jcasad@Thinkie:~$ |___________________________________________________________________ -
In most cases, the default argument is
show, which displays the basic parame­ Figure 1: Output of the ip addr command.
ters of the given object. The default be­
havior is to display the information for for your Linux distribution - the tool If you enter the ip route command
all objects if none is specified. For exam­ typically asks you to specify a default without any modifying arguments, you
ple, ip addr will show (i.e., display) the gateway and the rest of the routing hap­ are shown the list of configured routes.
address information about all network pens automatically. However, for com­ Although this is not any simpler than
interfaces. If you want, you can use list plex network configurations, such as running route, we think the output is a
instead of show. computers with multiple network inter­ little more useful. For example, the out­
This form of the ip addr command is faces or routed networks with multiple put for the default route shown by ip is:
composed of three parts: show dev paths, you might occasionally have the
enp0s31f6. One could say that the com- need to add information directly to the default via 192.168.2.1 dev enp0s31f6
mand-within-a-command is show with routing table - for configuration, optimi­
dev enp0s31f6 acting as arguments. zation, or troubleshooting purposes. If whereas the output for route is more
If you want to add a virtual interface your system loses or doesn’t have a de­ elaborate (Figure 2).
called enp0s31f6:l, the command would fault route and it isn’t a gateway, then With the use of route and ip, you can
look like this: you’re not going to be delivering any hand-configure routes aside from the
packets. gateway. Say you have two interfaces on
ip addr add 192.168.1.42 P The traditional method for adding and your machine and want to ensure that
dev enp0s31f6:l managing routes is the route command. the enp0s31f6 interface is used for the
The ip route command is a more recent 192.168.42.0/24 network:
In this case, you can think of alternative with similar functionality.
192.168.1.42 dev enp0s31f6:l as argu­ Adding a route with route will look route add -net 192.168.42.0 7
ments to the add command. The exam­ something like this: netmask 25S.2S5.255.0 7
ple here adds the IP address gw 192.168.1.254 dev enp0s31f6
192.168.1.42 to the device enp0s31f6:l. route add -net 192.168.42.0/24 7
With the ip command, you can also gw 192.168.1.99 Now traffic headed to 192.168.42.0 will
enable and disable interfaces (i.e., bring go through enp0s31f6. One caveat - this
them up or down): The same thing with the ip command all goes away when you reboot. Static
would look like: routes set by hand are not persistent by
ip link set up dev enp0s31f6 default. The kernel will “forget” every­
ip route add 192.168.42.0/24 7 thing unless you make this permanent.
In this example, the command is set; set via 192.168.1.99 How do you make them permanent? Dif­
and view are the two options the link ferent distributions set their network
object accepts. As you can see, the format is basically configurations differently - and have dif­
The ifup command is another option the same as when you added IP ad­ ferent tools for configuring the network
for starting up a network interface. As dresses. In this case, the object is a configuration.
you would expect, there is also an if- route and the command is add. Note If you’re using Red Hat or Fedora,
down command, which is a symbolic that both commands add the route for you’ll find networking scripts under/etc/
link to ifup. a range of IP addresses (192.168.42.0/ sysconfig/network-scripts, whereas
24 - in CIDR format), and this route is Debian-based systems keep their informa­
Routing assigned to a router address - with the tion under /etc/network/interfaces. If
The need to define network routes man­ gw (“gateway”) argument in the route you’re using a desktop system, you might
ually has decreased through the years. command and the more intuitive via want to use Network Manager to make
Most home and office networks today with ip route. changes rather than using text files.
provide dynamic IP address assignment
through DHCP, which includes informa­ Kernel IP routing table
Destination Gateway Genmask Flags Met ric Ref Use Iface
tion on the default gateway for the 192.168.2.0 0.0.0.0 255.255.255.0 U 0 0 0 ethO
network. 169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 ethO
Even if you explicitly define your net­ 127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo
0.0.0.0 192.168.2.1 0.0.0.0 UG 0 0 0 ethO
work configuration - at installation or
through the resident configuration utility Figure 2: The route command displays routing table entries.

68 LINUX SHELL HANDBOOK - 2023 EDITION


Networking Tools COMMUNICATION

Users on openSUSE or SUSE Linux En­


Shorthand
terprise Systems should use YaST2 to
make changes. Bottom line, if you need One interesting and useful aspect of the ip command is that, when specifying an object,
to set up persistent routes, you’ll proba­ you do not need to type the entire object name. A number of the objects described in
bly want to consult your distribution’s this article are abbreviations for the actual objects; for example, address is the object
documentation. and addr is just an abbreviation, neigh is an abbreviation for neighbor, and so forth.
The command ip / will show you the configured links just as ip link would. Note, how­
Names to Numbers and Back ever, that in a couple of cases multiple objects start with the same letter-for exam­
The Address Resolution Protocol (ARP)
ple, address and addrlabel. If you input just ip a, you are shown the addresses rather
relates a host’s IP address to the hard­
than the address labels. In general, the more common objects are recognized first.
ware address (or MAC address) as­
Also, you can use abbreviations for commands as well as objects.
signed to your network adapter. Histor­
ically, the ARP tables were read and
managed by the arp command. You Both commands output the IP address send as fast as the system can with the -f
might not often need to touch arp, but (192.168.2.67), the MAC address (lladdr (flood) option. Note that only root can
it’s handy to know you have the option 00:80:77:b8:lf:f6), and the network in­ use the flood option. To specify the inter­
of monitoring and managing the way terface (enp0s31f6) that connects to this val, use ping -i NN where NN is the in­
your system handles address address. terval. This can be a fraction of a sec­
resolution. ond, so if you want to send a ping every
Note that you only have ARP infor­ Troubleshooting half second, use:
mation about “neighbor” hosts on your Once you have finished configuring the
local network. If you have a private network, you might need to check to en­ ping -i O.S 192.168.1.99
192.168.1.0/24 network, you can use sure that packets can reach remote
arp 192.168.1.71 and get something like hosts. The ping command verifies that Another option, short of using flood, is
Figure 3. the networking system can successfully to preload the number of packets to be
If you haven’t pinged or interacted support communication with another sent. This option will send a predeter­
with the host previously, you won’t computer on the network. You can spec­ mined number of packets without wait­
have anything in the cache, so you can ify either the hostname or the IP ing for a response. To send more than
have two machines sitting next to one address: three, you’ll need to use sudo or be root.
another on the network that have no The preload option is specified with -I,
ARP cache entries for their neighbors. ping 192.168.1.99 like so:
If you ping the machine, you’ll be able
to get the ARP entry, which will in­ The output shows a report for each ping -1 NN 192.168.1.99
clude the MAC address under the packet in an unending list that includes
HWaddress column. information on whether the attempt was Replace NN with the number of packets
Not surprisingly, the ip command pro­ successful or not, along with the re­ that you’d like to send.
vides a replacement. The object, in this sponse times. Although this continuous Finally, you might want to change the
case, is neigh, for “neighbor. ” (See the output can be useful for testing pur­ Time To Live (TTL) option using the -t
“Shorthand” box.) poses, it is easily ended with Ctrl + C. To option. TTL is the maximum number of
The arp output for a specific host limit the number of packets, use the -c routers that a packet can travel before
might look something like (count) option. being thrown away.
You might want to ping using a spe­ Admins sometimes have the need to
192.168.2.67 P cific interface to try to troubleshoot net­ check the route a packet takes to its des­
ether 00:80:77:b8:lf:f6 C P working problems. For example, if you tination. Just because you can’t reach a
enp0s31f6 have a server with two or more inter­ site doesn’t mean the problem is on your
faces, you can specify the enp0s31f6 in­ network or the destination network -
where the output from ip neigh would terface to use with ping -I enp0s31f6 (re­ sometimes the problem is somewhere in
look like: place enp0s31f6 with the name of the in­ between.
terface you’d like to use). For example, say you can’t reach
192.168.2.67 dev enp0s31f6 P The ping command also allows you to Woot.com for some reason. It could be
lladdr 00:80:77:b8:If:f6 P set the interval between packets. The de­ that Woot.com is down, or that you have
REACHABLE fault is one second for each packet, or to a networking issue on your side. Or it
might be that the problem lies between
your network and Woot. com’s network,
and one way to figure this out is by
using utilities to trace the path that pack­
ets are taking.
The traceroute command and the newer
Figure 3: The arp command maps IP addresses to hardware addresses. tracepath utility provide this information.

LINUX SHELL HANDBOOK- 2023 EDITION 69


COMMUNICATION Networking Tools

tracepath is part of the iputils package Naturally, you’ll want to replace the IP your host and the destination and pro­
that also includes ping. Although tracer­ address with the appropriate address. If viding an interactive display similar to
oute is the older utility, it has many the path of the packets is inefficient or Figure 4.
more options than tracepath. In es­ unexpected, route or ip route will show
sence, the only thing you can pass to you what routes are configured. Note Troubleshooting DNS
tracepath is a destination port number. that you only see the route configured The Domain Name System (DNS) trans­
On the other hand, traceroute allows from the local machine; it is very possi­ lates the familiar alphanumeric domain
you to specify time-to-live values, maxi­ ble the problem might lie elsewhere. names used in email addresses and web
mum hops, a specific interface to use, Possibly a given router is explicitly URLs (such as linux-magazine.com or
and many more options. configured not to provide any details. whitehouse.gov) to and from the numeric
The basic syntax is simple enough: So, for example, tracepath might report IP addresses necessary for TCP/IP net­
Use traceroute host and you’ll see a list­ “no reply. ” This situation does not working. As long as your system knows
ing of the hosts between your computer mean you cannot connect to the target the location of a DNS server, this name
(or the system you are running tracer­ (which you can verify with ping); it resolution process happens invisibly; how­
oute on) and the final destination. Be­ simply means the intermediate router is ever, sometimes some troubleshooting is
cause you’re using traceroute to check not responding to the request from tra­ necessary. Also, sometimes for informa­
for overall latency and problems, if a cepath (or traceroute). tional purposes, it is important to know
host returns * * * but the packets are The tracepath documentation specifies the IP address associated with a domain
reaching their destination, this is OK. that it is not a “privileged program” and name or the domain name associated with
The maximum TTL (number of hops) can be executed by anyone. Although an IP address. A pair of classic Linux utili­
is usually set to 30. You might have more this is true, we have never had any trou­ ties that allow you to query the DNS sys­
than 30 hops between yourself and the ble running traceroute as a normal user, tem are nslookup and host, both of which
final host. To change this, use the -m except that it is usually not in a normal are part of the bind-utils package, ns­
option, like so: user search path. lookup provides more functionality and
Other troubleshooting utilities include more extensive output than host; however,
traceroute -m 35 linux-magazine.com the netstat command (which outputs in­ nslookup is considered outdated and less
formation on connections, routing ta­ able than some more modem equivalents.
This line would increase the number of bles, and interface statistics) or the A powerful and popular DNS tool in
hops to 35. Adjust as necessary. newer ss utilities. Although ss is part of use today is dig, which is short for “do­
You might need to use traceroute to the iproute package, its syntax is differ­ main information groper. ” Basically, dig
debug specific interfaces on a machine. ent from ip. See the ss man page for performs a DNS lookup and then shows
To do this, you can use -i (interface), -5 more information. the results. The most basic use is
(source address), or both options. A ma­
chine could have two or more IP ad­ Combining ping and dig <hostname>
dresses without actually having more traceroute with mtr
than one interface, or each interface A newer utility is mtr, which also has a which should return quite a bit of out­
might have its own address. Therefore, if GTK + front end called xmtr. Depending put, including an answer section with
you want to specify an IP address on a on the distribution you’re running, mtr the hostname and (by default) the IP ad­
system’s second Ethernet interface, use: might or might not be installed, mtr is a dress associated with the hostname.
cross between ping and traceroute. It But dig can tell you much more. For
traceroute -i enpOsSlfG -s 7 combines ping and traceroute functions example, if you want to see what DNS
192.168.1.100 by sending a number of packets between servers the domain uses, run dig NS
hostname - this command will return a
list of DNS servers responsible for trans­
lating the domain name to an IP address.
In the output, you also see what DNS
server(s) dig has used to perform its
lookups. Here, I’m using Google’s DNS:

;; Query time: 40 msec


;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Fri Feb 4 17:01:16 2011
;; MSG SIZE rcvd: 138

The SERVER is 8.8.8.8 - one of Google’s


public DNS servers. If you can’t look up
a hostname with your default DNS serv­
ers, you can try using a different server
Figure 4: Running an mtr guery on www.linux-magazine.com. by specifying it like this,

70 LINUX SHELL HANDBOOK - 2023 EDITION


Networking Tools COMMUNICATION

dig @8.8.4.4 www.linux-magazine.com The iw utility used to be the leading update_config=1


tool for text-based wireless configura­
which tells dig to use the second Google tion in Linux, but iw only works with Next, start wpa_supplicant as a daemon
DNS server to look up the IP address for the unsafe and obsolete Wired Equiv­ in the background and define the wire­
www. linux-magazine. com. alent Protocol (WEP). Most Linux sys­ less interface and the configuration file:
Finally, you can use dig to find any tems today use WPA Supplicant [1]
kind of DNS record. Want to see what with the wpa_cli front end for termi­ wpa_supplicant -B -i wlanO -c P
the MX (mail) hosts are for a given do­ nal sessions. A new tool called the /etc/wpa_supplicant/P
main? Use the MX directive: iNet Wireless Daemon (iwd) is a wpa_supplicant.conf
smaller and simpler tool that could
dig MX linux-magazine.com one day replace WPA Supplicant as Next, start wpa_cli. Figure 5 shows how
the standard option for command-line to check the status of the program. You
wireless configuration. can scan for available networks with scan
Putting It All Together and show the results with scan_results.
The ping utility is the simplest way of WPA Supplicant Use add_network to connect to a network
ensuring that you can reach a remote Most distributions come with wpa_sup- from the results, or if you already know
computer. If ping works, you can usu­ plicant preinstalled. The standard con­ the SSID, you can enter the details. The
ally assume the network is configured figuration file is found in /etc/wpa_sup- networks are indexed numerically, so the
correctly (or at least correctly enough plicant/wpa_supplicant.conf. If you first network is number 0:
for the packets to arrive at their destina­ don’t have this file, Ubuntu users can
tion) . To be sure things are configured find an example in /usr/share/doc/wpa_ > add_network 0
properly, check whether you can reach supplicant/examples. Use
the remote machine with either the Finally, you can add and save your net­
hostname or the IP address. If you can­ sudo gunzip -k P work credentials:
not reach it using the hostname but you wpa_supplicant.conf.gz
can it reach with the IP address, the > set_network 0 ssid "CROCODILE"
problem is most likely with DNS, so use to extract the compressed file, and > set_network 0 psk "crocodilel23"
the dig utility to try that out. then move it with the mv command to > enable_network 0
Interestingly enough, if you can reach the /etc/wpa_supplicant directory. > save_config
it with the hostname, but not with the IP The configuration file normally con­ > quit
address, this often indicates a DNS prob­ tains information about the control inter­
lem as well (the entry for that host face (/var/mn/wpa_supplicant). Some To set the credentials, enable the net­
points to the wrong IP address). distros also define a group like netdev or work, and then save your configuration.
If you cannot connect with either the wheel, which means that members of
hostname or IP address, the simplest ap­ those groups may execute the wpa_cli wpa_passphrase
proach is to start with the local machine front end. Uncomment or add this line to Included in the WPA Supplicant package
and work your way outward. give the wpa_cli front end permission to is wpa_passphrase, which modifies the
The first question is whether the IP modify the file: configuration file and offers an alternative
is configured correctly on the local sys­
tem. To check the IP configuration, use root@nate-VirtualBox:~# wpa.cli
wpa_cli v2.4
ip addr (or ip a to be even lazier). Copyright (c) 2004-2015, Jouni Malinen <j@wl.fi> and contributors
Then ping the default gateway to en­
This software may be distributed under the terms of the BSD license.
sure that you are connected to it, and, See README for more details.
if that works, ping another address be­
yond the local network to ensure that Selected interface 'wlanO'
the router is forwarding packets suc­
Interactive mode
cessfully. If you still haven’t identified
the problem, traceroute or tracepath > status
wpa.state=INACTIVE
should provide clues about where the p2p_device_address=84:16:f9:le:f3:7b
packets are getting lost. address=84:16:f9:le:f3:7b
uuid=49ed77bd-8baa-5f98-a2ff-53c6317ff12e
> add.network 0
Wireless Networking 0
In recent years, wireless connectivity has > set_network 0 ssid "CROCODILE"
OK
become nearly automatic, with a few > set_network 0 psk "crocodilel23"
connection settings handled mostly OK

through the GUI interface. However, it is


certainly still possible to search for wire­
less networks and initiate connections at
the command line. Figure 5: Use wpa cli to scan and connect to wireless networks.

LINUX SHELL HANDBOOK- 2023 EDITION 71


COMMUNICATION Networking Tools

1.12.0 on can use iwd as their back end.


Listing 1: /etc/wpa supplicant/wpa supplicant.conf
Iwd also works with alternatives such as
home network; hidden (E)SSID asteroid
ConnMan and systemd-networkd. And
network={
recently, a small GUI was released for
ssid="CROCODILE"
users who want to do without Network-
#psk="crocodilel23"
Manager or ConnMan. You can also ac­
psk=8S5fSa29‘480‘465b0e54S62dd9693435C108c314551d693cd0e36118f9c5d95d5
cess iwd from the command line using
}
the iwctl command.
If iwd is not on your Linux, you’ll
Listing 2: First Steps used to be. However, need to take some preliminary steps
many experts believe that (Listing 2). Line 1 in Listing 2 checks if
01 $ systemctl status iwd.service
Linux wireless support is iwd is already installed. You’ll need to
02 Unit iwd.service could not be found.
due for some reinvention. install iwd and then remove Network-
03 $ sudo apt install iwd
WPA3 has taken wireless Manager (line 4) and disable WPA
04 $ sudo apt purge network-manager security to a deeper level, (lines 5-7). Finally, enable iwd (lines 8
05 $ sudo systemctl stop wpa_supplleant .service but the complications in and 9) and check to see if everything is
06 $ sudo systemctl disable wpa_supplleant.service implementing a reliable working (line 10).
07 $ sudo systemctl mask wpa_supplleant solution underscored the It is a bad idea to remove the wpa-
08 $ sudo systemctl enable iwd.service inherent complexity and supplicant package after the prelimi­
09 $ sudo systemctl start iwd.service ungainliness of the WPA nary work is complete, instead of just
10 $ systemctl status iwd.service Supplicant codebase. disabling it. On Ubuntu, removing
That complexity, along wpasupplicant would also remove the
with many dependencies, ubuntu-desktop metapackage due to
to wpa_cli. You can use this command to also means that WPA Supplicant is ill- many dependencies. On Debian, Net­
connect to a network with an (E)SSID suited for mobile devices and Internet workManager would be removed as
you already know: of Things configurations. The need to well - which might be a benefit in
simplify and provide a better solution some cases.
wpa_passphrase CE0D0CILE P for these new technologies explains Once you have completed the neces­
secret_passphrase why efforts have been underway for sary steps, and assuming the status
several years to create a lean alterna­ query is positive, you can set up WiFi
The tool prints a network section as it is tive to WPA Supplicant. access. If you get a message about
used in the /etc/wpa_supplicant/wpa_sup- One alternative that has already ar­ rfkill blocking (Figure 6), call the
plicant.conf configuration file. The file may rived, although it still is not installed by command:
contain several of these blocks to define default on most Linux systems, is the
connections for more than one network iNet wireless daemon (iwd) [2] [3]. Intel sudo rfkill list wifi
and various security policies, including has been leading the development of
pre-shared keys (Listing 1). To add the out­ iwd. In October 2019, the stable 1.0 ver­ If Soft blocked shows up as yes, pressing
put of the previous wpa_passphrase com­ sion was released, and iwd continues to Fn + F5 might help to switch off flight
mand to the configuration file, use the evolve. NetworkManager versions from mode. If this does not help, use:
> > operator:

wpa_passphrase asteroid P trjiwd: S systemctl mask wpa supplicant


secret_passphrase >> P Created symlink /etc/systemd/system/wpa supplicant.service - /dev/null.
ftQiwd: $ systemctl start iwd.service
/etc/wpa_supplleant/P fttaiwd: $ systemctl enable iwd.service
ftJiwd: $ systemctl status iwd.service
wpa_supplicant.conf • iwd.service - Wireless service
Loaded; loaded (/lib/systemd/system/iwd.service; enabled; vendor preset: enabled)
Active; active (running) since Sat 2026-09-12 10:38:58 CEST; 22min ago
Main PID: 6294 (iwd)
Make sure you use > > rather than > to Tasks: 1 (limit: 4508)
add the output to the configuration file; Memory: 1.0M
CGroup: /system.slice/iwd.service
otherwise, you will overwrite the existing >-6294 /usr/libexec/iwd

file. For help configuring your network 12 10:38:58 iwd systemdd] : Starting Wireless service...
Seo 12 10:38:58 iwd iwd[6294]: Wireless daemon version 1.8
connections, check out the wpa_suppli- 12 10:38:58 iwd systemd[l] : Started Wireless service.
12 10:38:58 iwd iwd[6294]: station: Network configuration is disabled.
cant man page or refer to the wpa_suppli- -■ 12 10:38:58 iwd iwd[6294]: Wiphy: 0, Name: phy0
cant. conf example file if you have one. 12 10:38:58 iwd iwd[6294]: Permanent Address: 10:0b:a9:23:6f:8c
r-J 12 10:38:58 iwd iwd[6294]: Bands: 2.4 GHz 5 GHz
Sep 12 10:38:58 iwd iwd[6294]: Ciphers: CCMP TKIP
Sep 12 10:38:58 iwd iwd[6294]: Supported iftypes: ad-hoc station ap
iwd Sen 12 10:38:58 iwd iwd[6294]: Error bringing interface 4 up: Operation not possible due to RF-kill
WPA Supplicant has seen many im­ 1 $1
provements through the years, and, in Figure 6: Once WPA Supplicant is shut down, and if iwd always launches at boot time, the
general, it is much easier to connect status query reports an active service. However, the last line indicates that the device
Linux to a wireless network than it interface cannot be enabled.

LINUX SHELL HANDBOOK - 2023 EDITION


Networking Tools COMMUNICATION

sudo rfkill unblock wifi Now launch an interactive shell as a Iwd can also be used without an interac­
normal user with the iwctl command. tive shell; you just have to prefix each
Check if this worked with rfkill or a new Typing help lists all the available op­ command with iwctl.
status request for iwd. service. tions. To exit the shell, press Ctrl + D. Use device list to discover the name
the system is using for the interface (Fig­
Fl ft@>iwd2:/etc/iwd Q = □ x ure 7). If the interface goes by the name
ft@)lwd2: -/Download... ft(®iwd2: /etc/iwd ft@)iwd2: /etc/iwd ▼
of wlanO. The command
ft@iwd2: $ iwctl
[iwd]# adapter list device wlanO show
Adapters

delivers more details about the network


phy9 on Intel Corporationwireless 7260 (Dual
interface card (Figure 8). Now scan by
typing station wlanO scan before using
[iwd]# device list
station wlanO get-networks to display the
available networks (Figure 9).
Enter the following command:
wlanO 5c:Sl:4f:92:40:28 on phyO station

[iwd]# | station device_name P


connect network_name
Figure 7: The adapter list command displays the available network interface cards with their
names and manufacturer IDs. to enable the connection. The requested
password is stored in /var/lib/iwd when
R ft(®iwd: - input with the .psk suffix.
ftfttlwd: - If needed, check the functionality
ft@iwd:-$ iwctl again by typing:
[iwd]# device list
Devices status device_name get-networks

A check mark, hardly visible against the


wlanO 10:0b:a9:23:6f:8c on phy0 station
dark color scheme of the Ubuntu termi­
iwd]# device wlan0 show nal, indicates that the connection was
Device: wlan0 successfully opened. Then use ping to
check the status of the Internet connec­
tion or browse to a website. After reboot­
Name wlan0 ing the computer, iwd automatically re­
Mode station
Powered on
establishes the wireless connection.
Address 10:0b:a9:23:6f:8c If the connection fails, or if problems
Adapter phy0 occur when roaming through changing
iwd]# | networks, create a /etc/iwd/main. conf file
with the content from Listing 3. The con­
Figure 8: Use the device list command to determine the name and state of the interface. figuration causes iwd to hand over name
resolution to systemd-resolved. resolvconf
m ft@)iwd: -
is also available as an alternative. ■
ft (®iwd: ~

:t@iwd:~$ iwctl Listing 3: main.conf


Twd]# station wlan0 get-networks
Available networks [General]
EnableNetworkConf iguration=true
[Network]
FlitzIBox psk **** NameResolvlngService=systemd
DIRECT-4PC43X Series psk ****
SLIDER-WIFIEXT psk **
WLAN-193375 psk ***
heimnetz psk ** INFO
Arcor home psk *
[1] WPA Supplicant: https://en.
Xiaomi_llA4 psk *
ArcorGuest D psk * wikipedia.org/wiki/Wpa_supplicant
Arcor psk * [2] iwd: https://git.kernel.org/pub/scm/
TelekomFON open ***
network/wireless/iwd.git
iwd]# | [3] Kernel.org iwd page: https://iwd.
wiki, kernel, org/
Figure 9: After a scan, station wlanO get-networks displays the available networks.

LINUX SHELL HANDBOOK- 2023 EDITION 73


COMMUNICATION Internet Tools

Tools for working with the Internet

ONLINEHELPERS
The Linux environment provides command-line tools for many common Internet tasks, such as checking
email, surfing the web, and even searching on Google.
BY BRUCE BYFIELD, CHARLY KUHNAST, HARALD ZISLER, AND JOE CASAD

or many users, the modern In­ Bash commands are also easy to inte­ where URL is the URL of the page you

F ternet is synonymous with lush


graphical web browsers and

of the things you do everyday on the


grate into scripts, which means you
can automate the download process
and schedule it using cron or another
desktop client applications, but many
automation tool.
wish to download. For example, to down­
load the homepage of Unux-magazine.com,
you would enter the command:

web are also possible from the com­ Curl (“Client URL”) is an application curl https://www.linux-magazine.com/
mand line. This article investigates for transferring files to or from a server.
some command-line tools for accessing It supports numerous protocols and will This form of the command basically
Internet content. either choose the protocol that seems simulates an HTTP GET request. The
most appropriate to the situation, or the URL doesn’t have to be just a domain
File and Page Downloads one specified in the command structure. name and can also specify the path to
Sometimes it is necessary to download a Curl can download or upload files from a file:
complete web page for later viewing. a server, as well as download HTML
This might be because you will be of­ pages, fill and submit HTML forms, and curl https://www.linux-magazine.com/P
fline and would like access to the infor­ read and write cookies. images/picture.jpg
mation while you aren’t connected. Or Curl (Figure 1) is not always installed
maybe some of the information on the by default, so if you don’t have it, you’ll Use the -I option to output headers only:
page is important for your records? Most need to install it with your system’s
web browsers offer some kind of Save As package manager. curl -I https://linux-magazine.com
option to save the current page locally as The most basic form of the command is:
an HTML file, but in many cases, it is This simple form of the command just
more efficient to use the command line. curl URL writes the output to stdout, which

bb@tlvarnes$: $ curl http://lnfo.cern.ch/


<htmlxhead></headxbody><header>
<title>http://info.cern.ch</title>
</header>

<hl>http://info.cern.ch - home of the first webstte</hl>


<p>From here you can:</p>
<ul>
<lixa href="http://info.cern.ch/hypertext/WWW/TheProject.html “>Browse the first website</ax/li>
<lixa href="http://ltne-mode.cern.ch/www/hypertext/WWW/TheProject.html">Browse the first website using the line-mode browser simulator
</ax/li>
<lixa href=“http://home.web.cern.ch/topics/btrth-web">Learn about the birth of the web</ax/li>
<lixa href=,,http://home.web.cern.ch/about,'>Learn about CERN, the physics laboratory where the web was born</ax/li>
</ul>
</bodyx/html> _________________________________________________________________________________________________________________________

Figure 1: Curl displaying HTML with embedded links.

74 LINUX SHELL HANDBOOK - 2023 EDITION


Internet Tools COMMUNICATION

normally means it prints it to the screen. speed, set the number of download at­ With wget, you can also log in to the site
The -o option saves the output to a file: tempts, and download in the back­ with a username and password in a
ground (Figure 2). single command:
curl -o homepage.html P The basic command looks a lot like curl:
https://www.linux-magazine.com/ wget —http-user=USERNAME 7
wget URL -http-password=PASSWORD 7
Or if you want to omit the local file https://linux-magazine.com
name and just give the file the same for example, as follows:
name it had on the original, use -O: If you just want the whole thing, the fol­
wget https://linux-magazine.com lowing command will let you download an
curl -0 7 entire website:
https://www.linux-magazine.com/3? To download to a file, you use
images/picture.jpg wget -m -k -p -P DIRECTORY URL
wget -o FILENAME URL
This command will download the file In the preceding command, the -m op­
to a file called picture.jpg on the local which looks like: tion tells wget to work recursively, and
system. Enter the -h. switch to output to only follow relative links. The -k op­
help information, including a summary wget -o homepage.html 7 tion converts any links in the original
of the most important command-line https://www.linux-magazine.com/ document back into links in the down­
options. loaded version, the -p tells wget to in­
Just as Curl can emulate an HTTP GET To use the same file name as the clude image files and other files needed
request, it can also emulate a PUT re­ original, use: to complete the page, and the -P lets you
quest, which means you can use it to specify a directory to recreate the direc­
write data to a website: wget -0 7 tory structure of the original site at the
https://www.linux-magazine.com/5? target location.
curl —request PUT https://www.URL images/picture.jpg
BitTorrent
Of course, you’ll need the necessary cre­ If you have a large file, you might want BitTorrent [1] is a protocol for peer-to-
dentials to write the data to a web server. to limit the download speed, so it peer sharing of files. Rather than
Another command for downloading doesn’t suck up all your bandwidth downloading from a single source, Bit­
web pages and writing to websites is and processor time: Torrent downloads files from multiple
wget. You often can use curl and wget sites or clients, thereby lessening the
interchangeably, and many readers wget —limit-rate=MBs URL load on any one site and often increas­
confuse the two. Strictly, however, curl ing the speed of the download. As well,
is intended for file transfer, and wget where MBs is the rate in MB per second. BitTorrent downloads can be inter­
specializes in the download of pages If you don’t want to wait around while rupted and resumed.
and entire sites, making it ideal for the download completes, use the -b op­ Several command-line interface Bit­
backups and the creation of mirrors. tion to download in the background: Torrent clients are available. However,
The two commands share many of the the most popular is aria2c [2], which
same features, but with small differ­ wget -b https:/linux-magazine.com supports not only BitTorrent but other
ences. For example, wget is aware only
of HTML, XHTML, and CSS pages, and Listing 1: Installing googler
it doesn’t support as many protocols as $ cd Downloads/
curl. Similarly, although both com­ $ wget -c https://github.com/jarun/googler/archive/refs/tags/v‘1.3.2.tar.gz
mands use the -o and -O options for $ tar -xvf v(4.3.2.tar.gz
naming file downloads, using the same
$ cd googler-a.3.2/
option for entire sites puts all the
$ sudo make install
source files into a single file. In addi­
$ cd auto-completion/bash/
tion, wget offers more control over
$ sudo cp googler-completion.bash /etc/bash_completion.d/
downloads, allowing users to limit the

bb@ilvarness: $ wget --limit-rate Im http://us.download.nvidia.com/tesla/396.37/nvidia-diag-driver-local-repo-ubuntul710-396.37_l.0-l_a


md64.deb
--2023-Q2-02 14:36:47— http://us.download.nvidta.com/tesla/396.37/nvidia-diag-driver-local-repo-ubuntul710-396.37_l.0-l_amd64.deb
Resolving us.download.nvtdta.com (us.download.nvtdta.com)... 192.229.211.70, 26O6:2800:21f:3aa:dcf:37b:led6:lfb
Connecting to us.download.nvtdia.com (us.download.nvidta.com)|192.229.211.70|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 111563998 (106M) [appltcatton/octet-stream]
Saving to: 'nvidia-dtag-driver-local-repo-ubuntul710-396.37_1.0-l_amd64.deb'

nvidta-diag-drtver-l 37%[===========> ] 39.91M 1.00MB/S eta 67s |

Figure 2: One of the advantages of wget is its control over download settings, such as the download speed.

LINUX SHELL HANDBOOK- 2023 EDITION


COMMUNICATION Internet Tools

news, videos, and more. You can think


of Googler as a command-line client for
accessing the Google API. It was origi­
nally built on the assumption that ad­
mins working on text-based servers still
needed to use Google to search for trou­
bleshooting information. Since then,
however, googler has evolved to a point
where some users actually prefer it, be­
cause it delivers noticeably faster results
and includes some options that are un­
available with the Google homepage.
Many distributions have the tool in
their package repositories, but you can
install it manually with a few commands
(Listing 1).
Figure 3: The hits for the search term "Linux" are displayed in a numbered list with googler. In the simplest case, you can start a
keyword search on Google by calling:

googler TERM

The result for the keyword Linux is


shown in Figure 3. You can see that
googler numbers the search results. If
you type the number for a search result,
googler passes the address to the default
web browser to open. If this does not
work for you, that means that googler
cannot determine the appropriate
browser. You then need to pass in the
name of the program with the
-url-handler parameters, for example, as
-url-handler lynx (or whatever you use).
By default, googler always returns 10
search results; the number can be in­
creased or reduced with the -n NUMBER
parameter. One useful parameter is -t
Figure 4: If needed, googler lets you restrict the search to a single website. 12m. This command will only show hits
that are at most 12 months old - which
download protocols, such as FTP/ If the torrent file is located somewhere is quite handy, because if you’re looking
SFTP, HTTP, and Metalink. on the Internet, torrentJile_name will for a particular error message, you are
BitTorrent uses the concept of a torrent actually be a URL with a fully qualified naturally more interested in recent re­
file, which is a file containing metadata path to the torrent file. You can also use sults than ancient ones.
describing the various locations where the -T option to specify the torrent file’s It is also often useful to limit the
the content resides. Torrent files have the location: search to one website. For example, if
.torrent file extension. The BitTorrent cli­ you only want to see results from Wiki­
ent downloads the torrent file and uses it aria2c -T URL pedia, use the -w option. The example in
to initiate the download. Figure 4 shows hits for the term “Linux”
To start a download with aria2c, enter In this case, the -T is not required, but it that come from the Wikipedia website.
is sometimes useful just to add clarity.
aria2c torrent file name Should aria2c not suit your needs, you Listing 2: Mutt
could also try alternative Configuration Settings
Table 1: Mutt Command-Line Options BitTorrent clients such set realname = "NAME"
-a FILE Attach a file as webtorrent-cli or stig. set from = "YOUR EMAIL ADDRESS"
-b ADDRESS Add a blind carbon copy (BCC) set use_from = yes
-c ADDRESS Add a carbon copy (CC) recipient
googler set envelope_from = yes
Another command-line
-iFILE Include a file in the body of the email set editor = "EDITOR"
tool, googler [3], lets you
-s SUBJECT Add the subject of the message search Google web,
set charset = "CHARACTER-CODE"

76 LINUX SHELL HANDBOOK - 2023 EDITION


Internet Tools COMMUNICATION

If you do not want to leave any data configuration files by adding com­ If you are using an IMAP server, add:
traces when searching the web, take a mands and a few fields.
look at ddgr [4]. The ddgr utility comes To begin configuring, create the basic set smtp_url = "EMAIL-ADDRESS:PORT/"
from the same author as googler, supports directories and the configuration file: set smtp_pass = "PASSWORD"
(almost) the same parameters, but uses set imap_pass = "PASSWORD"
DuckDuckGo and is therefore far more mkdir -p ~/.mutt/cache/headers set folder = "PATH:PORT"
careful in terms of data handling. mkdir ~/.mutt/cache/bodies set spoolfile = "+INB0X"
touch ~/.mutt/certificates set record = +Sent
Email with Mutt mailboxes = +INB0X
Linux has no shortage of email clients The configuration file, muttrc, can have bind index imap-fetch-mail
that run from the command line. One several locations that are detected auto­
of the most common is Mutt [5]. First matically: ~/.muttrc, ~/.mutt/muttrc, For folder, use the directory where mes­
release in 1995, Mutt is one of the old­ and $XDG_CONFIG_HOME/mutt/mut- sages are stored; spoolfile is where Mutt
est email clients available for Linux. trc, each with or without -MUTT_VER- looks for incoming mail. The port is only
Fully controlled from the keyboard, it SION appended. Use touch, to create the needed if the folder is not local. The plus
also has the option for a GUI-like side- muttrc file with the path of your choice. sign indicates that any subdirectories
bar, as well as extensive configuration For example, you can use: will be used as necessary.
options and a choice of external editors Finally, set the mbox type and the struc­
for email composition. Mutt is often touch ~/.mutt/muttrc ture for receiving messages as follows:
the choice of those who want wide­
spread customization, or, because of If you want to place muttrc in a nonstan­ set mbox_type=Maildir [or Mbox]
its small footprint, its relative security. dard place, set the location by adding to set folder=~/mail
Mutt is configured in /etc/Muttrc, muttrc the line: set spoolfile=+/
which, among other things, contains set header_cache=~/.cache/mutt
the senders name and email. source /path/to/other/config/file
In deference to its age, Mutt is in­ where spoolfile should be the same as
cluded in the repositories of most dis­ Next, open the newly made muttrc in a the spool file set for IMAP; header_cache
tributions. Preparing it for use con­ text editor. Add the settings in Listing 2 stores email headers to increase the
sists primarily of editing its to set up Mutt’s environment. speed in which headers are displayed.

[ utt-nanday-1000-5293-7860455411086450003 (Modified)(mail) Row 6 Col 8


Hi, John:

Do you still have the rose-breasted cockatoo you advertised recently? Qf so,
what is your asking price?

Thanks

Figure 5: Mutt can use any command-line editor, including Vim, Emacs, nano, or JOE (shown here).

n: nail
1870 Dec 06 Cron Daemon 1 KU Cron <root@nanday> /usr/lib/prey/prey.sh >/var/log/prey.l|
1871 0 Dec 07 Anae ron : i) Anacron job 'trim.weekly' on nanday
1872 0 Dec 14 Anacron : i) Anacron job 'trim.weekly' on nanday
1873 0 Dec 19 Anae ron : 23) Anacron job 'cron.monthly' on nanday
1874 0 Dec 21 Anacron : i) Anacron job 'trim.weekly' on nanday
1875 0 Dec 28 Anacron : i) Anacron job 'trim.weekly' on nanday
1876 0 Jan 04 Anacron : i) Anacron job 'trim.weekly' on nanday
1877 0 Jan 11 Anacron : i) Anacron job 'trim.weekly' on nanday
1878 0 Jan 15 Cron Daemon : 4) Cron <root@nanday> /usr/lib/prey/prey.sh >/var/log/prey.l
1879 0 Jan 18 Anacron : i) Anacron job 'trim.weekly' on nanday
1880 0 Jan 19 Anacron : 23) Anacron job 'cron.monthly' on nanday
1881 N + Jan 20 Mail Delivery S : 45) Mail delivery failed: returning message to sender
1882 N Jan 25 Anacron : i) Anacron job 'trim.weekly' on nanday
1883 N + Jan 25 Mail Delivery S : 46) Mail delivery failed: returning message to sender
1884 N + Jan 25 Mail Delivery S : si) Mail delivery failed: returning message to sender

---Mutt: /var/mail/bb [Msgs:1884 New:4 0ld:1878 3.6M]—(threads/date)--------------- --------------- (end)—

Figure 6: Mutt can run from the command line, or, more conveniently, through a keyboard-navigated text interface.

LINUX SHELL HANDBOOK- 2023 EDITION 77


COMMUNICATION Internet Tools

y:Send q:Abort t:To c:CC s:Subj a:Attach file d:Descrip ?:Help


From: bb <bb@nanday.nanday*
To: bruce.byfield@gmail.com
Cc:
Bcc :
Subject: Test
Reply-To:
Fee: ~/sent
Mix: <no chain defined*
Security: None

-- Attachments
|- I 1 /tmp/mutt-nanday-1000-5293-7860455411086 [text/plain, 7bit, us-ascii, 0.2K]|

-- Mutt: Compose [Approx, msg size: 0.2K Atts: 1]

Figure 7: Before you send an email, Mutt gives you one last chance to edit the headers and displays a summary of the email.

dd@vm-ubu1710d-x64: -
Before you go The sort file determines whether
File Edit View Search Terminal Help
» Linux Magazine (pl of 11) any further, send a aliases are listed by alias or address,
Link:
Link: tnage_src message to check while reverse_alias set to yes displays
[IMG]
whether you have the long name if one is given. Adding
search: search______________ basic functional­ the source allows Mutt to autocom­
* News
* * Features ity. If you made plete when you enter an alias for the
* * Blogs
* * White Papers any typos during To: field. If the alias you enter is non­
* * Archives
* * Special Editions setup, it will be existent, a list of all aliases displays.
* * DigiSub easier to trouble­ If you want a more sophisticated ad­
* * Shop
* Desktop
* Development
shoot before you dress book, you can use an external ap­
* Hardware
* Security
add more to your plication, such as Abook, GooBook, or
configuration. Khard.
* Programming
* Operating Systems Store account To create a signature that is added au­
* Software
passwords inter­ tomatically to the end of every message,
Figure 8: Links2 in text mode on the Linux Magazine website. nally with: add the following line to muttre:

set my_pass = "PASSWORD" set signature="PATH"


Link: canoi
Link: image sre
The prefix my_ is used for any variables where Path points to a file that contains
that you define. However, muttre is un­ a signature that is added automatically
encrypted, so it makes your password to the end of every email you send. To
newsletter: email______________ visible to anyone. The simplest alterna­ avoid any conflict between Mutt’s use of
search: search_______________
* News
|_ J tive is to enter the password each time UTF-8 for a character set and the editor
* * Features
* * Blogs
you log in. in which you write emails, you should
* * White Papers Mutt has two ways of setting up an ad­ also add:
* * Archives
* * Special Editions dress book. The first is to create aliases
* * DigiSub
* * Shop for each contact in a new file, one alias set send_charset="utf-8"
* Desktop
* Development per line, with the structure:
* Hardware You can also set up encryption for sent
* Security
* Server alias NICKNAME LONGNAME ADDRESS mail. If you have not already done so, cre­
* Programming
* Operating Systems ate ~ /.mutt/gpgre, then copy to it the file
* Software
* Networking The optional LONGNAME is the con­ /usr/share/doc/mutt/samples/gpg. re, and
* Administration
Home tact’s full name. In Mutt, you use the add the following line to muttre:
Login NICKNAME to send an email to the
contact. Pressing a when an address is source ~/.mutt/gpg.rc
entered in the To: field will also create
a new file when aliases are set up in With this setup, you can press p when
muttre with the lines: composing to use basic GnuPG options.
The muttre man page [6] lists additional
Shielded set alias_file = "PATH" encryption options.
E_____________ set sort_alias = alias All emails sent from Mutt are in text
Figure 9: LinksZ in graphic mode on the set reverse_alias = yes form for security. If you want an HTML
Linux Magazine website. source $alias_file email message, either compose it in a

78 LINUX SHELL HANDBOOK - 2023 EDITION


Internet Tools COMMUNICATION

Table 2: Links2 Options


Task Option Note
Use graphic mode -g Without: Text Mode
Driver for graphics mode -driver xlsvgaliblfbldirectfb Not necessary in GUI
Redirect formatted page to file -dump -
Redirect unformatted website to file -source -
Specify proxy -http-proxy HostllP:Port -
Different download directory -download-dir folder_name -
Anonymous mode -anonymous No download, no listing of files
Rendering HTML frames -html-frames 1 -
Number links -html-numbered-links 1 Links can be called quickly using the numeric keys
Specify browser as Firefox -http.fake-firefox 1 -
Send "Do-not-track" -http.do-not-track 1 -
Specify referer -http,referer 011121314 0: no referer, 7: requested URL as referer, 2. freely defined
referer, 3: real referer, 4: real referer only on the same server
Fake referer value -http.fake-referer Referer -
Fake user agent value -http.fake-user-agent Browser -
Additional information for HTTP headers -http.extra-header Specify -

separate email editor or add the tags described as the attachment of a file this article, the web browsers are the
manually. stored in /tmp/mutt (Figure 7). Press y least functional when compared to their
You can send an email message di­ when you are ready to send the graphical counterparts.
rectly from the command line with the message. A brief introduction to a couple of
following command: the command-line browsers will give
Web Browsers you an indication of what they are like,
mutt OPTIONS "RECIPIENT-OR-ALIAS" Several web browsers are available for but keep in mind that the idea of a
the Linux command
See Table 1 for a summary of important line, notably Lynx [7], Table 3: Links2 Control
command-line options. w3m [8], Links2 [9], Task Key
When you press the Enter key, Mutt and ELinks [10]. All Switch on menu [F9] or [Esc]
asks for confirmation of the options and four of these browsers
File menu [F10]
then opens in the default editor so that use the same basic
Next link [arrow down]
you can type the message (Figure 5). command structure:
Previous link [arrow up]
The -R option lets you open a mailbox
and select a message to reply to. If you command URL Next page Page Down
are unsure of the available mailboxes, Previous page Page Up
typing -y will provide a list of available All, too emphasize text Next frame [Tab]
ones. If necessary, -f MAILBOX sets the and are designed for Scroll downwards [Del]
current mailbox. those who want to read Scroll upwards [Ins]
An easier way to use Mutt is to type the text-heavy pages such Scroll right Right ]
basic command mutt, which opens a text­ as Wikipedia rather Scroll left Right [
based interface (Figure 6). The interface is than use images or
Top of page [Home]
entirely mouse driven, with a list of avail­ sound. As well, many
Bottom of page [End]
able actions along the top, and a summary command-line web
of the current mailbox along the bottom. browsers do not support Input Enter key
When Mutt runs from the command line, JavaScript or the latest Search (forward) /
pressing m to start a message runs you HTML standard. You Search (backward) 7

through a series of prompts for the headers can navigate all of these Next hit n
and then opens Mutt’s default editor. browsers using the Previous hit N
When you are finished writing your arrow keys. Do not ex­ Reload page [Ctrl]+[Shift]+[R]
message in the editor, save the file and pect command-line web Goto new URL g
quit the editor (the exact commands for browsers to have the
Goto URL G
doing so depend on the editor). A screen complete functionality
Download D
appears in which you can make last min­ of a desktop browser. Of
View Source code/formatted \
ute changes, using the options listed at all the command-line In­
the top of the page, with the message ternet tools described in Quit program Q

LINUX SHELL HANDBOOK- 2023 EDITION 79


COMMUNICATION Internet Tools

Table 4: w3m Options Table 5: W3m: Operation


Task Option Task Key
Line numbers in output -num Show URL c
Only IPv4 addresses -4 Show URL on the cursor u
Only IPv6 addresses -6 Enter URL U
Use as newsreader -m Refresh page R
Direct complete website to standard edition -dump
Previous page B
Only direct headers to standard output -dump_head
Next link [Tab]
Using the POST method with a file -post date
Previous link [Esc]+[Tab]
Start in interactive mode -v
Next word w
Combining empty lines -s
Previous word W
Show more options -show-option
Character-based navigation arrow keys
Specify another option -o option
Follow hyperlink [Enter]
graphical interface, with its images and is operated via a Top of page [Home]
bright colors, is baked into the whole few keys (see Bottom of page [End]
design of the World Wide Web, so re­ Table 3), which Load bookmark [Esc], b
ducing the format to a command-line are easy to re­ Save bookmark [Esc], a
tool introduces some limitations. member. Press F9
Download S
The Links2 browser rose from the To call a menu.
Quit program Q
ashes of the Links project. Links2 sup­ While w3m [4]
ports both text and graphics mode, mak- is a robust and
ing it equally suitable for the console and lean text web browser, it also performs displaying large text files, even within
the GUI. You select the mode at launch other tasks. As a replacement for the a pipe. If you install w3m on Debian or
time. For graphics mode, call the program less utility, w3m (Figure 10) offers Ubuntu via the w3m-img package, it
with Unks2 -g, and append the URL of the search and control options for will also display images if you are
desired web page to the command. using it from an X terminal (Figure 11).
Figure 8 shows the rendering of a nor­ A series of switches (see Table 4) lets
mal web page by Links2, using the ex­ you customize w3m at startup. The
ample of the Linux Magazine homepage. options in Table 5 help you to control
Graphics mode (Figure 9) only works the running program. For example, the
when the display is redirected or when program lets you open several web
working in a graphical user interface. pages in tabs. Also, w3m supports
See Table 2 for some important op­ bookmarks, but it does not support
tions for calling Links2. The browser JavaScript. ■

INFO
[1] BitTorrent: https://en.wikipedia.org/
wiki/BitTorrent
[2] aria2c: http://aria2.github.io/manual/
en/htm l/aria2c.htmi
[3] googler: https://github.com/jarun/
googler
[4] ddgr: https://github.com/jarun/ddgr
[5] Mutt: http://www.mutt.org/
[6] muttrc man page: https://linux.die.
net/man/5/muttrc
[7] Lynx: https://invisible-mirror.net/
archives/lynx/
[8] w3m: https://w3m.sourceforge.net/
[9] Links2: http://atrey.karlin.mff.cuni.cz/
~clock/twibright/links
Figure 10: w3m in text mode on the internal Figure 11: w3m with graphic display on the
[10] E Li nks: http://elinks. or. cz/
test page. Linux Magazine website.

80 LINUX SHELL HANDBOOK - 2023 EDITION


SSH Tool COMMUNICATION
is- ' ,C*. >'
-

FnbiSSfe i
Secure connections with SSH
?

TUNNEL BUILDER
Manage your server from a distance with this convenient and secure remote access toolkit.
BY JORG HARMUTH, DMITRI POPOV, HEIKE JURZIK, AND JOE CASAD

he SSH client/server architecture Open sshd_config for editing using your spoofing a genuine login to your ma­

T is based on TCP/IP. The SSH


server (sshd) runs on one ma­
favorite editor as root and change the
Port value (e.g., Port 1777). Then, restart
chine, where it listens for incoming con
nections on TCP port 22. The client sim­
the­ SSH server using the
chine. If you were to confirm the secu­
rity prompt and enter your password,
the attacker would then own your pass­
word; thus, some caution is recom­
ply uses this port to connect to the /etc/init.d/ssh restart mended. If the host key changes, the
server. When a connection is established, client will refuse to connect when you
several things happen in the background. command as root. This simple trick log in later. Figure 2 shows the output
The server and client exchange informa­ makes the lives of potential intruders from the SSH client.
tion about supported protocol versions to slightly more difficult, because many ma­ The only thing that will help is to re­
use for communications. Currently, SSH1 licious port scanners check the default move the offending fingerprint from
and SSH2 are available, but SSH2 is stan­ port 22 and move on if it’s not open. Of your $HOME/.ssh./known_hosts file
dard today because of its better security. course, this doesn’t make your server and accept the new key after contacting
Details - including details of encryp­ completely secure, but every bit helps. the administrator on the remote
tion - are given in the “SSH Protocol Ver­ To connect to the server via SSH, you
sions” box. The server and client then also need to install the OpenSSH client SSH Protocol Versions
negotiate the algorithm, followed by the on your machine using apt-get install SSH1 uses the insecure DES or the secure
key that both will use for the data trans­ openssh-client as root. To establish an Triple DES ODES). The Blowfish algorithm
fer. The key is used once only for the cur­ SSH connection, open the terminal and provides a fast and - so far - secure en­
rent communication session, and both run the ssh user@remotehost command cryption technology. Version 2 includes
ends destroy it when the connection is (replace USER with the actual username the AES algorithm and others.
broken. For extended sessions, the key on the server and HOST with the IP ad­ Vulnerabilities in the SSH1 protocol
will change at regular intervals, with one dress or domain name of the server). If make it possible to hack the encryp­
tion. Version 1 relies on encryption of
hour being the default. you changed the default SSH port, then
data with a random number that has
To get started with SSH, you need to you need to specify the port parameter been encrypted with the server's pub­
install an SSH server on the target ma­ explicitly: lic key. This method is open to brute
chine - and you can’t go wrong with force attacks that give the attacker the
OpenSSH, which is by far the most pop­ ssh -p 1777 user@remotehost plaintext key.
ular SSH software on Linux. To install Protocol 2 relies on a Diffie-Hellman ex­
the OpenSSH server on Debian and On first log in, the client will not know change that never transmits the key over
Ubuntu, run the the server’s host key and will prompt you the wire but allows server and client to
generate the same key independently.
to confirm that you really do want to es­
apt-get install openssh-server tablish a connection with the remote ma­ Other enhancements to version 2 include
E the software's ability to check the data in­
chine. After confirming, the program gen­
tegrity with cryptographic hashes (the
a command as root. erates the fingerprint (Figure 1). Message Authentication Code method)
4 Once the installation is completed, the To check the key fingerprint, contact rather than the unreliable Cyclic Redun­
j= server is ready to go. Although it runs the administrator of the remote machine. dancy Check (CRC) method. Support for
* perfectly well with the default configura- This prevents man-in-the-middle at­ multiplexing is also improved. All of the
S tion, you might want to change the de- tacks, in which an attacker reroutes net­ examples in this article use SSH2, al­
though some will work with SSH1.
g fault port 22 the server is running on. work traffic to his own machine while

LINUX SHELL HANDBOOK- 2023 EDITION 81


COMMUNICATION SSH Tool

debian:-# ssh sector program will need to enter the password for the SSH
The authenticity of host 'sector (192.168.10.10©)' can't be established.
then tell you key to copy the data - so much for au­
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes where it has tomated copying.
Warning: Permanently added 'sector, 192.168.10.1O0' (RSA) to the list of known host
Password: stored the data Typing SSH commands like
Last login: Tue Sep 27 14:45:53 2005 from 192.168.10.254
and will display
the fingerprint ssh -p 1777 pi@192.168.101
Figure 1: On initial login, SSH imports the host key. for the new key.
In the example can become a nuisance if you have to do
debian:-# ssh sector
here, the soft­ this several times a day. Fortunately, you
WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! ware generates can solve this problem by defining SSH
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! an RSA keypair aliases for often-used SSH connections in
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed. (-t rsa) with a the ~/.ssh/configii\e:
The fingerprint for the RSA key sent by the remote host is
length of 2048
Please contact your system administrator. bits (-b 2048). Host alias
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending key in /root/.ssh/known_hosts: 1 For security rea­ HostName ipaddress
RSA host key for sector has changed and you have requested strict checking.
Host key verification failed. sons, the key User username
length should Port portnumber
Figure 2: If the host key changes, the SSH client will refuse to connect. not be less than
2048 bits. To be Replace alias with the desired alias
machine. To configure this behavior, absolutely safe, you can use a key length name, ipaddress with the IP address or
use the StrictHostKeyChecking variable of 4096 bits. The key length has no influ­ domain name of the server, username
in ssh_config. ence on the data transfer speed because with the actual username, and port­
If you do not want to use your current the program does not use this key to en­ number with the appropriate port
account name to log in to the remote ma­ crypt the data. number:
chine, the -I login_name option can help. Next, copy the public key to the
For example, the command $HOME/.ssh/ authorized_keys file on Host raspberrypi
the remote machine from, for example, HostName 192.168.1.101
ssh -1 tuppes sector a floppy disk: User pi
Port 1777
logs you in to the remote machine as mount /media/floppy
user tuppes. SSH also accepts the syn­ cat /media/floppy/id.rsa.pub P You need to specify the Port parameter
tax ssh tuppes@sector. To run a single > > $H0ME/.ssh/authorized_keys only if the SSH server is running on any
command on the remote machine, you amount /media/floppy port other than 22.
simply append it to the command line
(Listing 1). Certainly you should avoid transfer­ File Transfer
If you get tired of typing your pass­ ring the key by an insecure method, The SSH package includes two more
word, public key authentication providessuch as email or FTP. Figure 3 shows useful programs: Secure Copy (scp) and
an alternative. This technique uses en­ the fairly unspectacular login with the Secure FTP (sftp). You can use scp and
cryption methods such as those used by new key. sftp to copy and transfer files over a se­
GnuPG. Before you can use the public Passwords protect keys for interactive cure connection, scp was developed as
key approach, you first need to run sessions; otherwise, anybody with a secure version of the classic file copy
ssh-keygen to generate a pair of keys: physical access to your computer could command cp. sftp is a secure version of
use your keys to log in to the remote the File Transfer Protocol (FTP) utility,
ssh-keygen -b 2048 -t rsa machine. Key-based, password-free log­ which was used for many years to post,
ins are often used to automate copying download, and move files on the Inter­
The software will tell you that it has of files to remote machines. net and other TCP/IP networks. The
created a keypair with a public key and For example, if you back up your data sftp command lets you use FTP over a
a private key on the basis of the RSA every evening and want to copy it auto­ secure SSH connection.
approach. When prompted to enter a matically to a remote machine, keys To copy test.txt from your home direc­
password, press Enlter twice. The without passwords are a useful ap­ tory on the remote machine to your cur­
proach. If the key rent working directory using scp, enter:
Listing 1: Running Commands on the was password pro­
Remote Machine tected, you would scp RemoteComputer:test.txt .
jha@scotti:~$ ssh sector "Is -1"
Password: debian:-# ssh sector
Last login: Wed Sep 28 13:36:22 2005 from 192.168.10.254
insgesamt 52 SECTOR;|
Drwxr-xr-x 3 tuppes users 4096 2005-08-26 12:38 .
Drwxr-xr-x 16 root root 4096 2005-09-07 13:47 .. Figure 3: Public key authentication makes the login more user friendly
-rw-rw-r— 1 tuppes users 266 2005-04-12 12:00 .alias
by removing the password prompt.

82 LINUX SHELL HANDBOOK - 2023 EDITION


SSH Tool COMMUNICATION

Depending on your authentication an FTP session. To use sftp to retrieve mget and mput to retrieve or send multiple
method, you might need to enter your the sample file from the remote machine files at once using wildcards. To shovel all
password; however, the colon is manda­ in automatic retrieval mode, type: the files in a specific remote directory onto
tory in all cases. It separates the name of your local machine, you would type:
the remote machine from the path name. sftp user@RemoteComputer:test.txt .
Also, you need to specify the local path. sftp> mget *
The easiest case is your current working where user is the name of the user ac­
directory, which is represented by the count. If you add remote_test.txt to the Of course, you can be more precise if
dot at the end of the line. To copy multi­ end, the program will give that name the you like; for example,
ple files, just type a blank-delimited list local copy of the file.
of the file names: Typing sftp RemoteComputer opens an sftp> mget *.tar.gz
interactive, encrypted FTP session on the
scp BemoteComputerA:testl.txt P remote machine, and the server will then will download all files with the .tar.gz
RemoteComputerB:t est 2.txt . accept FTP commands. Alternatively, extension.
you can add the username to the Enter bye, exit, or quit to quit sftp.
If you use the standard login approach, command: sftp also supports several of the stan­
the client will prompt you to enter your dard file management commands used
password for each file you copy. If you sftp user@RemoteComputer in the Bash shell. You can create a di­
use the public key method discussed rectory with mkdir (or Imkdir for the
previously, you don’t need to type a To discover the current directory on the local system) and remove files and di­
password. The command remote computer, enter pwd (print work­ rectories with rm and rmdir. See the
ing directory) as in Bash; to learn the article elsewhere in this issue on “File
scp RemoteComputerA:test.txt 7 current directory on the local computer, Management.” Also, see the article on
RemoteComputerB: enter Ipivd. The familiar Is command “Users, Groups, and Permissions” for
outputs a current directory listing on the more on changing file permissions
copies the file from remote computer A remote system; Ils shows a list of files in (chmod), changing file ownership
to remote computer B. To copy a file as the current directory of the local system. (chowri), and changing group member­
tuppes from /home/tuppes/files to your Use cd [directory] to change directories ship (chgrpi), which are also possible
local directory, type: on the remote computer, cd.. climbs up using sftp.
one level in the directory tree, and cd / The / character lets you execute a
scp tuppes@RemoteComputer: takes you to the root directory on the shell command on the local system. If
files/test.txt . FTP server. On the local computer, you Bash is your local shell, you can actu­
can change directories with led. ally execute almost any of the com­
The program assumes you are copying Once you have navigated to the de­ mands in this issue from within an sftp
from the user’s home directory if the path sired remote directory, use the get com­ session if you precede the command
after the colon doesn’t start with a slash/. mand to copy a file from the remote sys­ with /. For instance, suppose you want
If you want to specify a location that isn’t tem to the local system. The command: to upload the file OdeToBash.txt, but
in the user’s home directory, use an abso­ you aren’t sure which subdirectory of
lute path beginning with a slash. For in­ sftp> get mammoth.txt your home directory it is in. You could
stance, if you want to copy a file from the find the exact location of the file while
/etc/cups directory of the remote machine: downloads the mam.moth.txt file from the inside an sftp session by typing:
current remote directory to the current
scp tuppes@)RemoteComputer: 7 local directory. You can specify the target sftp> (find ~ -name OdeToBash.txt
/etc/cups/file_name.txt . file name as well as the source file:
Alternatively, enter / on a line by itself to
Unlike SSH, you do not specify the -I user- sftp> get mammothl.txt mammoth2.txt escape to a local shell session. From
name option. Copying in the other direc­ there, you can work normally at the
tion - local to remote - is just as easy: The preceding command copies the file Bash command line and then type exit to
mammothl.txt from the remote directory return to the sftp session.
scp ./test.txt 7 and names the file mammoth2.txt on the For a complete list of sftp commands,
tuppes@RemoteComputer:files local system. type help or ? at the sftp prompt.
The put command moves files from
scp copies the test.txt file from your cur­ the local system to the remote server: Conclusions
rent working directory to /home/tuppes/ The SSH package includes a collection of
files on the remote machine. Again, sftp> put mastodon.txt important programs that make working
watch out for the closing colon. sftp> put mastodonl.txt mastodon2.txt on networks far more secure. The feature
The sftp tool supports an automatic re­ scope covers anything from basic en­
trieval mode, which is similar to scp, and Some (but not all) sftp implementations let crypted connections, through tunneling
an interactive mode, which behaves like you use the alternative FTP commands and port forwarding, to Xll forwarding. ■

LINUX SHELL HANDBOOK- 2023 EDITION 83


COMMUNICATION Rsyn

Synchronizing data with rsync

STAYING Rsync lets you synchronize your data - on either a local or

IN SYNC remote computer. The tool works unidirectionally and keeps


your data safe thanks to SSH. BY HEIKE JURZIK

sync is the perfect synchroniza­ $ rsync dirl/* dir2/ timestamps - that is, information on the

R tion tool for keeping your data in


sync. The program manages file

data, and it is perfect for transferring


skipping directory foo
skipping directory bar
properties and uses SSH to encrypt your
skipping non-regular file "text.txt"
last access time (atime), the last status
change (ctime), and the last modification
(mtime).
Additionally, administrators can bene­
large volumes of data if the target com­ As the output shows, rsync would trans­ fit from parameters that preserve owner
puter has a copy of a previous version. fer normal files but leave out subdirecto­ and group data and support device files.
Rsync checks for differences between ries and symbolic links (non-regular To retain the permissions, just specify
the source and target versions. The tool file). To transfer directories recursively the -p option; -t handles the timestamps,
that has been developed by the Samba down to the lowest level, you should and -g keeps the group membership.
team [1] uses an efficient checksum­ specify the -r option. Using the -I flag ad­ Whereas any normal user can specify
search algorithm for comparing data; ditionally picks up your symlinks. Of these parameters, the -o (keep the owner
rsync only transfers the differences be­ course, a combination of the options is data) and -D (device attributes) flags are
tween the two sides and therefore saves also possible: available only to root. The complete
time and bandwidth. command line with all these options
rsync -Ir dirl/* dir2/ could look like this:
In Sync
The generic syntax for rsync is rsync Rsync has an alternative approach to rsync -rlptgoD /home/huhn backup/
[options] source target, where target can handling symlinks. If you replace -I with
be a local target on the same machine or -L, the program will resolve the link, and Don’t worry - you don’t have to remem­
a remote target on another machine. The your former symlinks will end up as ber all these options. Rsync offers a prac­
choice of source and target is critical; de­ “normal” files at the target. tical shortcut and a special option that
cide carefully in which direction you will Be careful with the slash - appending combines these parameters for this case.
by synchronizing to avoid loss of data. If a slash to a directory name influences Instead of -rlptgoD, just type -a.
you’re not sure that you’re using the cor­ the way rsync handles an operation (see
rect options or the correct source/target, the “Common Rsync Traps” box). Exclusive
you can run rsync with the -n flag to tell Rsync has another practical option that ?
the program to perform a trial run. Addi­ As You Were allows you to exclude certain files from |
tionally, you can increase the amount of If you will be using rsync to create back­ the synchronization process. To leverage 2-
information by defining -v and switching ups, it makes sense to keep the attri­ this feature, specify the -exclude = op- |
to verbose output. butes of the original files. By attributes I tion and a search pattern and define the
To mirror a directory dirl on a local mean permissions (read, write, execute, files to exclude. With this option, you t
machine, for example, type: see the “Access Permissions” article) and can use wildcards:

84 LINUX SHELL HANDBOOK - 2023 EDITION


Rsync COMMUNICATION

rsync -a —exclude=*.wav P that those files are no lon­


"/music backup/ ger wanted.
All -delete options have
This example excludes large WAV files basically the same goal:
that end in .wav from the backup of a to keep an exact copy of
music collection. If you need to exclude the original. If you don’t
MP3s as well, just append another ex­ use the switch, you will
clude statement and a pattern: have to clean up manu­
ally; otherwise, the files
rsync -a —exclude=*.wav 7 that you’ve decided are
--exclude=*.mp3 ... useless will remain. Use
these options with care
To save time, you can store your exclu­ (see the “Common Rsync
sions in a text file. To do this, you will Traps” box).
need a separate line for each search pat­
tern. Specify the -exclude-from = file_ Tuning Rsync
with._exclusions parameter to parse the Several options increase Figure 1: The rsync -z option to compress data is shown in
file. rsync’s performance. the Grsync graphical front end.
Often, I use the -z switch
Tidying Up to compress data when I sync data over rsync -avz --progress —partial P
Rsync offers various parameters for de­ a network connection. Figure 1 shows remote.server:/home/huhn/mus ic/P
leting data that is no longer needed or this using Grsync, the graphical front folk "/music/
wanted. To get rid of files in your backup end to rsync [2]. If the connection is receiving file list ...
that no longer exist in the source, type very slow, you can also define a band­ 42 files to consider
-delete. Rsync’s default behavior is to width limit. To transfer data with only
delete files before the transfer is fin­ 20KBps, for example, use: 12_Moladh_Uibhist.mp3
ished. Alternatively, you can define -de­ 1143849 4% 339.84kB/s 0:01:10
lete-after to delete files of the target after rsync . .. —bwlimit=20
all the syncing is done. At the other end of the connection, the
Additionally, you can tell rsync to de­ Rsync is perfect for transferring large partial file is hidden in the target direc­
lete files that you have excluded (see the volumes of data. If you specify the -par­ tory at first. Typing Is -a reveals a file
previous section). For example, imagine tial parameter and the transfer is inter­ called 12_Moladh_Uibhist.mp3.7rUSSq.
you’ve decided that you no longer want rupted for some reason, you can pick up The dot at the start of the file name
the MP3s in the backup and you’ve the transfer from the point at which you keeps the file hidden, and the arbitrary
started to exclude them with -ex­ left off. Specifying the -progress option extension removes the danger of over­
clude = *.mp3. Now you can define -de- gives you a progress indicator to let you writing existing files.
lete-excluded, and rsync will recognize keep track of the transfer operation: When the transfer completes, the
file gets its original name back. If the
Common Rsync Traps transfer is interrupted, you can restart
Some rsync options could cause trouble if If a transfer is interrupted and you're by specifying the --partial option
you don't use them with caution. Being using the —partialflag, rsync saves parts again. Alternatively, you have a short­
aware of these common mistakes can of the file under the same name as the cut: If you want to use a combination
help. original, which is not always helpful. of --partial and --progress, simply use
• Most users find the final slash for direc­ Imagine that you're using rsync to up­ -P. For the downside of using the
tories confusing at first. For example, if date a large and existing ISO image of --partial flag, again see the “Common
you call rsync -a source/folder target/, your favorite distribution (like a Release Rsync Traps” box.
rsync will transfer the directory called Candidate). The transfer of the new ver­ Rsync keeps your data up to date and
folder and its contents to the target di­ sion gets interrupted after just a few helps you stay on top of confusing ver­
rectory. If the directory folder does n't sion changes. Its options help you man­
bytes. Rsync will overwrite your original
exist, rsync will create it. If you append a
file with the smaller part of the ISO age file properties, and it works well
slash to source/folder/ rsync will only
transfer the contents of folder. That image from the server, and you'll have with SSH. When you need to transfer
means a file source/folder/foo.txt 'is lost your current file and have to start large volumes of data, rsync comes to
being transferred to target/foo.txt in­ from scratch. your rescue. ■
stead of target/folder/foo.txt. To avoid loss of data in this scenario,
• An absolute classic troublemaker is the you can create a hard link before calling INFO
option —delete. If you get source and tar­ rsync. If the transfer fails now, you won't
lose the ISO image; instead, the partial [1] Rsync website:
get mixed up, -delete will happily delete
https://rsync.samba. org
several original files. To be on the safe file will be given a new name without de­
side, remember to use -n in a test run. stroying the original. [2] Grsync: http://www.opbyte.it/grsync/

LINUX SHELL HANDBOOK- 2023 EDITION 85


AUTOMATION Cron and At

Cron and At keep your tasks on task Users who are not listed in at.allow there­
fore receive the message You do not have
permission to use at.

ON THE DOT
The cron and at utilities help automate processes on a Linux system.
A cron for All Seasons
If you are looking for a way to handle reg­
ularly recurring tasks, repeatedly running
At is not recommended. Instead, you
BY HEIKE JURZIK should investigate the other option that
Linux gives you. Cron also runs in the
he Linux environment includes output by default (e.g., rm, mv, or cp), you
background and runs jobs at regular inter­

T a number of utilities that allow


you to schedule tasks. Two clas­
sic Bash scheduling tools are the At
program, which lets you schedule tasks
can enforce an email message. To do so,
set the -m flag, as in at -m 13:31.

Displaying and Deleting Jobs


vals. Again, the cron program just needs
the machine to be up because it “remem­
bers” scheduled jobs when you reboot
your machine. In fact, the two programs
right now, and Cron, which handles Scheduled At commands are stored in
have even more in common: just like at,
recurring jobs. A daemon runs in the the queue, and you can display the
cron mails the owner account to confirm
background to ensure the tasks are per­ queue onscreen by calling at -I or atq:
that a job has completed successfully.
formed according to the schedule and
(Remember that this requires a working
checks for new jobs once a minute. The $ atq
mail server and at least local delivery.)
daemon for At is named atd, and the 2 Tue Nov 9 16:22:00 2010 a huhn
Individual tasks are referred to as
Cron daemon is called cron(d). 3 Tue Nov 10 17:08:00 2009 a huhn
cronjobs, and they are managed in the
Systemd has introduced a new method 4 Tue Nov 10 17:10:00 2009 a huhn
crontab. This is a table with six columns
for scheduling tasks in Linux: a Systemd
timer. Like many features of the Systemd Unfortunately, at is not very talkative; it that defines when a specific job is to be
landscape, timers are relatively new, and just tells you the job number, date and performed. Each command in the
many users still prefer to schedule tasks time, queue name (a), and username. crontab occupies a single line. The first
the old way. This article focuses on the The list does not tell you what jobs are five fields describe the time, whereas the
classic Cron and At tools. See the article scheduled. Additionally, you only get to sixth field contains the program to be
on Systemd (elsewhere in this issue) for see your own jobs as a normal user; only run, including any parameters.
more on scheduling events in Systemd. the system administrator gets to see a full As a normal user, you can create a
list of scheduled jobs. crontab at the command line by running
At Your Service If you want more details on what the the crontab program with crontab -e,
To perform a job, call at with the time at future holds, become root and change to where the -e parameter indicates that
the command line, type commands in the the At job directory below /var/spool, for you will be editing the table.
shell, and quit by pressing Ctrl + D: example /var/spool/atjobs/ (for open­ As the system administrator, you can
SUSE) or /var/spool/cron/atjobs/ (for additionally modify the crontabs of any
$ at 07:00 Debian and Ubuntu). The text files tell user by specifying the -u parameter and
warning: commands will P you exactly what commands will be run. supplying the account name:
be executed using /bin/sh Here you can also learn the user and
at> oggl23 -zZ /home/huhn/music/* group IDs (see the “Users and Groups” crontab -u huhn -e
at> <E0T> article) and the username of the one
job 1 at Tue Nov 10 07:00:00 2009 who started the at command. Usually, this calls the Vi editor - if you
To delete an At job, enter at -d or atrm, prefer a different text editor, just set your
This tells the oggl23 command-line specifying the job number: $EDITOR environmental variable to re­
player to wake you on the dot at 7am by flect this, as in:
playing a random selection of songs in $ atrm 2 3
shuffle mode from the /home/huhn/ $ atq export EDIT0R=/usr/bin/gedit
music/ directory - of course, this as­ 4 Tue Nov 10 17:10:00 2009 a huhn
sumes your computer is switched on. To make this change permanent, add
Table 1 gives an overview of the most Access Privileges this line to your Bash configuration file,
common notations for time. Note that at Two files, /etc/at.allow and /etc/at.deny, and reparse the configuration file by en­
is persistent; that is, it will keep running control who is permitted to work with At. tering source ~/.bashrc.
after you reboot your machine. Most distributions tend just to have an
After completing a task, At sends email at.deny file with a few “pseudo-user” en­ Well Structured
with the job status to the job owner as to tries for Ip (the printer daemon) or mail Crontab lines are not allowed to contain
whether the job completed successfully or (for the mail daemon). If you create an line breaks. Six fields contain the follow­
not. Therefore, you need a working mail at.allow file as root, you need entries for ing information in this order: (1) minutes
server configuration (at least for local de­ all users who are permitted to run At (0 to 59 and the * wildcard), (2) hour (0 to
liveries). For commands that do not create jobs - at.deny is not parsed in this case. 23 or *), (3) day (1 to 31 or *), (4) month

86 LINUX SHELL HANDBOOK - 2023 EDITION


Cron and At AUTOMATION

To delete individual entries, launch the ed­


Table 1: at Time Formats
itor with crontab -e; if you intend to delete
Format Meaning
the whole table, run crontab -r instead.
16:16 16:16 hours today (or the next day, if it is past that time).
07:00pm 19:00 hours today (if you do not specify am or pm, am is assumed).
Global cron Tables
now Right now
Cron not only handles user-specific lists,
tomorrow Tomorrow
it helps the root user with administration
today Today
tasks. Working as root, look at the /etc/
now+ 10min In 10 minutes time; you can also specify hours, days, weeks, and months.
crontab file, which shows which jobs cron
noon tomorrow At 12:00pm the next day; also, teatime (=4:00pm) or midnight.
handles. Depending on the distribution,
6/9/10 June 9, 2010; or, for example, 6.9.10 and 6910.
the global crontab can vary; Debian and
Ubuntu have the entries shown in List­
(I to 12, Jan to Dec, jan to dec, or *), 0 7 * 1-4,7,10-12 mon-fri ...
ing 1. In contrast to normal user crontabs,
(5) weekday (0 to 7, where both 0 and 7
the global crontab has a seventh field with
mean Sunday, Sun to Sat, sun to sat, or *), The values 1-4,7,10-12 in the fourth field
the name of the user and the privileges for
(6) < command > (the command to run, (month) means “January to April, July,
whom the command will run (typically
including options; also, this can be the October to December.” A slash followed
root). This list tells you that the cron
name of a script with more commands). by a number defines regular periods of
daemon runs run-parts -report /etc/cron,
If you want your computer to wake time (e.g., */2 in the second column =
hourly with root privileges once an hour
you at 7am every morning, enter: “every two hours” and 1-6/2 = “1,3,5”).
at 17 minutes past the hour, and at 6:52 am
User cron tables are stored in the /var
07*** oggl23 -zZ /home/huhn/music/* on the first day of each month, cron runs
directory, but distros take different ap­
run-parts -report/etc/cron.monthly. Cron
proaches when sorting the tables: Debian
The values in the individual fields can be takes care of the daily chores (the execut­
and Ubuntu store them in /var/spool/
separated by commas: To keep your able scripts in /etc/cron. daily) at 6:25am,
cron/crontabs/ and sort by username;
alarm from ringing on Saturdays and Sun­ including the logrotate script, which ro­
openSUSE uses /var/spool/cron/tabs/. As
days, add this to the fifth weekday field: tates, compresses, and sorts logfiles.
a normal user, you do not have read per­ If you do not run your computer 24/7,
mission, but you can display your cron modify these entries and specify times
0 7 * * 1,2,3,4,5 Oggl23 -Zz 7
table by running the crontab program: when you know your computer will be up:
/home/huhn/mus ic/*

$ crontab -1 7
A combination of times can also be useful. 25 17 * * * root
10 8 * * mon-fri oggl23 -Zz 7
You can specify a range with a dash (1-5), test -x /usr/sbin/anacron || 7
/home/huhn/mus ic/*
but weekday names are easier to read: ( cd / && run-parts --report 7
/etc/cron.daily )

Cron Alternatives
Several GUI-based tools will help you cre­
ate a cron table. Gnome users have Gnome
Schedule (packagegnome-schedule), an
easy-to-use program that lets you put to­
gether at and cron tasks with a few mouse
clicks. The KDE tool is KCron (System Set­
tings | Startup and Shutdown | Task Sched­
uler.) . KCron lets you modify the system-
wide crontab, as well as cron and At sched­
ules for certain user accounts (Figure 1).
In the end (and as in most cases), the
command line gives you much more flex­
ibility, and you can type entries much
faster than if you were to click and point.
Alternatives such as Anacron and Fcron
Figure 1: KDE provides a convenient dialog for managing cron and At settings. are available online or through your dis-
tro's package manager. Some of
these tools provide enhanced
scheduling features and even
offer a way to "catch up" by exe­
cuting tasks that were scheduled
to run when the system was
turned off. ■

LINUX SHELL HANDBOOK- 2023 EDITION 87


AUTOMATION Bash Scripting

Getting started with Bash scripting Input File


The next incarnation of the script changes e

CUSTOM SCRIPT
how it is run slightly (Listing 2). The first £
command argument is assumed to be the 2
name of a file containing a list of directo- |
ries to back up. Additional arguments are q
A few scripting tricks will help you save time by automating common treated as literal items to be backed up. °
tasks. BY /ELEEN FRISCH DIRS and OUTFILE are variables used «
within the script. I’ll use the convention
of uppercase variable names to make
hell scripts are a lazy person’s best The second command runs the script, them easy to identify, but this is not re­

S friend. That may sound strange,


because writing a shell script pre­
and many messages from tar will follow.

sumably takes work, but it’s true. Writing


a shell script to perform a repetitive task
So far, the user has reduced the work
required to create the tar archive from
typing 75 characters to typing eight char­
quired. The first command in the script
places the contents of the file specified
as the script’s first argument into DIRS.
This is accomplished by capturing the
requires some time up front, but once the acters. However, you could make the cat command output via back quotes.
script is finished, using it frees up the time script slightly more general - and poten­ Back quotes run the command inside
the task used to take. In this article, I will tially more useful - by putting the items them and then place that command’s out­
introduce you to writing shell scripts with to be saved on the command line: put within the outer command, which
Bash. I’ll describe Bash scripting in the then runs. Here, the cat command will
context of several common tasks. Because $ ./mytar /home/chavez P display the content of the file specified as
this is an introductory discussion, some /new/pix/rachel /jobs/proj5 the script’s first argument - the directory
nuances are glossed over or ignored, but I list - and place it in the double quotes in
will provide plenty of information for you This command backs up a different set of the assignment statement, creating the
to get started on your own scripts. files. The modified script is shown in List­ variable DIRS. Note that line breaks in the
ing 1 and illustrates several new features: directory list file do not matter.
Hello, Bash • The tar command now uses I/O redi­ Once I’ve read that file, I am done
In its simplest form, a shell script is a file rection to suppress non-error output. with the first argument, so I remove it
with a list of commands. For example, a • The tar command is conditionally exe­ from the argument list with the shift
user created this script to avoid having to cuted inside an if statement. If the test command. The new argument list con­
type a long tar command every time she condition in the square brackets is true, tains any additional directories that were
wanted to back up all her pictures: the commands that follow are exe­ specified on the command line, and $@
cuted; otherwise, they are skipped. will again expand to the modified argu­
#!/bin/bash • The if condition determines whether ment list. This mechanism allows the
tar cvzf /save/pix.tgz /home/chavez/pix P the number of argument specified to script user to create a list of standard
/graphics/rdc /new/pix/rachel the script, indicated by the $# con­ items for backup once, but also to add
struct, is greater than 0. If so, then the additional items when needed.
The script begins with a line that identi­ user lists some items to back up. If not, The third command defines the vari­
fies the file as a script. The characters then the script was run without argu­ able OUTFILE using the output of the
are pronounced “shbang,” and the full ments and there is nothing to do, so the date command, which is known as com­
path to the shell follows: In this case, the tar command won’t run. mand substitution. The syntax is a vari­
Bash executable. The remainder of the • The script’s command-line arguments ant form of back quoting: 'command' is
script is the tar command to run. are placed into the tar command via equivalent to $ (command). The final
One more step is necessary before this the $@ construct, which expands to command runs tar, whre the items from
script can actually be used. The user the argument list. In this example, the the first argument file and any additional
must set the executable file permission command will become: arguments are the items to be backed up.
on the file so that the shell will know Note that when you want to use a vari­
that it is a runnable script. If the script tar czf /save/mystuff.tgz 7 able within another command, you pre­
file is named mytar, the following chmod /home/chavez /new/pix/rachel 7 cede its name by a dollar sign: $DIRS.
command does the trick (assuming the /jobs/projB >/dev/null
file is located in the current directory): Adding Checks
Placing command-line arguments into Listing 2 is not as careful as the previous
$ chmod u+x mytar the tar command allows the script to example in checking that its arguments are
$ ./mytar back up the necessary files. reasonable. Listing 3 shows the beginning

88 LINUX SHELL HANDBOOK - 2023 EDITION


Bash Scripting AUTOMATION

Listing 2: Specifying an Input File


#!/bin/bash

DIRS="'cat $1'" # DIRS = contents of file in 1st argument


shift # remove 1st argument from the list
OUTFILE="$( date +%y%m%d )" # create a date-based archive name
tar czf /tmp/$OUTFILE.tgz $DIRS >/dev/null

of a more sophisticated script that restores than the specified patterns (i.e., other the script’s first argument followed by 1:
this checking and provides more flexibility. than n, b, f, d, or:). The commands to ${1}1. The syntax also enables variables
This version uses the getopts feature built process the various options differ, and to be isolated from surrounding text: If the
into Bash to process arguments quickly. each section ends with two semicolons. value of ANIMAL is cat, then $ {ANI­
The first two commands assign values From the commands, you can see that -n MAL }2 expands to cat2, whereas $ANI-
to DEST and PREFIX, which specify the di­ specifies the archive name prefix (over­ MAL2 refers to the value of the variable
rectory where the tar archive should be riding the default set in the script’s sec­ ANIMAL2, which is probably undefined.
written and the archive name prefix (to be ond command), -b says to use bzip2 Note that periods are not interpreted as
followed by a date-based string). The rest rather than gzip for compression (as part of variable names (as shown later).
of this part of the script is a while loop: shown later), -/‘specifies the file contain­ The :0:l following the variable name
ing the list of items to be backed up, and extracts the substring from OPTARG be­
while condition-and; -d specifies the destination directory for ginning at the first position (character
commands the archive file (which defaults to /save numbering starts at 0) and continuing
done as before via the first command). for 1 character: in other words, its first
The destination directory is checked to character. The if command checks
The loop continues as long as the condi­ make sure that it is an absolute pathname. whether this character is a forward
tion is true and exits once it becomes false. The construct ${OPTARG:0:1} deserves slash, displaying an error message if it is
Here, the condition is getopts "f:bn:d:" special attention. The most general form of not and exiting the script with a status
OPT. Conditional expressions are enclosed $ substitution places curly braces around value of 1, indicating an error termina­
in square brackets (as seen in the preced­ the item being dereferenced: $1 can be tion (0 is the status code for success).
ing and following if statements), but full written as ${1}, and SCAT as ${CAT}. When an option requiring an argument
commands are not (technically, the square This syntax is useful. It allows you to ac­ doesn’t have one, getopts sets the vari­
brackets invoke the test command). Com­ cess positional parameters beyond the able OPT to a colon and the correspond­
mands are true while returning output, ninth; ${11} specifies the script’s 11th pa­ ing option string is put into OPTARGS.
and false when their output is exhausted. rameter, for example, but $11 expands to The penultimate section of the case state-
The getopts tool returns each com­
mand-line option, along with any argu­
ments. The option letter is placed into
the variable specified as getopts’ second
argument - here OPT - and any argu­
ment is placed into OPTARG. getopts’
first argument is a string that lists valid
option letters (it is case sensitive); letters
followed by colons require an argument
- in this case, f, n, and d. When speci­
fied on the command line, option letters
are followed by a hyphen.
The command inside the while loop is
a case statement. This statement type
checks the value of the item specified as
its argument - here, the variable OPT set
by getopts - against the series of pat­
terns specified below. Each pattern is a
string, possibly containing wildcards,
terminated by a closing parenthesis. Or­
dering is important because the first
matching pattern wins.
In this example, the patterns are the
valid option letters, a colon, and an as­
terisk wildcard matching anything other

LINUX SHELL HANDBOOK- 2023 EDITION 89


AUTOMATION Bash Scripting

able WHEN as the fourth field of that out­


Listing 4: Restoring Checking (continued)
put (the most recent login time), extracting
01 if [ -z $DIRS ]; then # Make sure you have a valid item list file it with awk (you don’t have to understand
02 echo "The -f list-fileoption is required."
everything about Awk to use this simple
03 exit 1
04 elif [ ! -r $DIRS ]; then
recipe for pulling out a field).
05 echo "Cannot find orread file$DIRS." This command runs when $? equals 0.
06 exit 1 $? is the status code returned by the most
07 fi recent command: grep, grep returns 0
08 when it finds a match and 1 otherwise.
09 DAT="$( /bin/date +%d%m%g )"
Finally, the script displays an appropriate
10 /bin/tar -${ZIP-z} -c -f /$DEST/${PREFIX}_$DAT.${EXT-tgz} 'cat $DIRS' > /dev/null
message with the user’s status, as in kyrre
has been logged in since 08:47.
ment handles these errors. The final sec­ uses some conditional variable dereferenc­
tion handles any invalid options encoun­ ing - for example, ${EXT-tgz}. The hyphen while and read
tered. If this happens, getopts sets its following the variable name says to use The following script illustrates another use
variable to a question mark and places the following string when the variable is of while and read: processing successive
the unknown option into OPTARGS; the undefined. EXT and ZIP are defined only lines of output or a file. The purpose of
wildcard pattern will match and handle when -b is specified as a command-line this script is to send mail messages to a list
things if this event occurs. option (as tbzandj, respectively). When of (opted-in) users as separate messages:
This argument handling code is not they have not been defined earlier in the
bulletproof. Some invalid option combi­ script, then the values z and tgz are used. #!/bin/bash
nations are not detected until later in the /bin/cat /usr/local/sbin/email_list |7
script (e.g., -f-n: -f’s argument is miss­ Numeric Conditions while read WHO SUBJ; do
ing, so -n is misinterpreted as such). I’ve now shown examples of both condi­ /usr/bin/mail -s "$SUBJ" $WH0 < $WHAT
The remainder of the script started in tions involving string comparisons and echo $WH0
Listing 3 is shown in Listing 4. file characteristics. Listing 5 introduces done
The if statement checks for two possi­ numeric conditions; the script is de­
ble problems with the file containing the signed for a company president’s secre­ The script sends the content of the files to
directory list. The first test checks tary who wants to check whether some­ the while command; the condition used
whether the variable DIRS is undefined one is logged in. here is a read command specifying three
(has zero length), exiting with an error This script first checks whether any ar­ variables: read processes each successive
message if this is the case. The second gument was specified on the command line from while’s standard input - the out­
test, following elif (for “else-if”) makes line. If not, that is, if the number of argu­ put of the cat command - and assigns the
sure the specified file exists and is read­ ment is less than 1, then it prompts for first word to WHO, the second word to
able. If not (the exclamation point in the the desired user with the read command. WHAT, and all remaining words to SUBJ
expression serves as a logical NOT), the The user’s response is placed into the (where words are separated by white space
script gives an error message and exits. variable WHO. Continuing this first case, by default). These specify the email ad­
The final two commands create the if WHO is zero length, then the user dress, message file, and subject string for
date-based part of the archive name and didn’t enter a username but just hit a car­ each person. These variables are then used
run the tar command. The tar command riage return, so the script exits. On the to build the subsequent mail command.
other hand, if an argu­ This script uses full pathnames for all
Listing 5: Adding Numeric Conditions ment was specified on external commands, a practice you should
01 #!/bin/bash the command line, adopt (or you can include an explicit PATH
02 then WHO is set to that definition at the beginning of the script to
03 if [ $# -It 1 ]; then # No argument given, so prompt value. Either way, avoid the security problems of substituted
04 read -p "Who did you want to check for? " WHO
WHO ultimately holds executables). Unfortunately, the script is
05 if [ -z $WH0 ]; then # No name entered
06 exit 0 the name of the user to quite sanguine about trusting emailjist to
07 fi look for. include properly formatted email ad­
08 else The second part of dresses. If such a script is meant for use by
09 WH0="$l" # Save the command line
the script in Listing 5 someone other than the writer, addresses
argument
10 fi uses two command must be carefully checked. Consider the
11 substitutions. The first effect of a username like jane@ahania.
12 L00K=$(w | grep "A$WH0") of these constructs com; /somewhere/run_me in the list.
13 if [ $? -eq 0 ]; then # Check previous command status searches the output of
14 WHEN=$(echo $L00K | awk '{print $4}')
the iv command for the Loops
15 echo "$WH0 has been logged in since $WHEN."
16 else desired username, stor­ The next two scripts illustrate other kinds
17 echo "$WH0 is not currently logged in." ing the relevant line in of loops you can use in shell scripts via the
18 fi LOOK if successful. The for command. Listing 6 prepares a report
19 exit 0 second defines the vari­ of total disk space used with a list of direc-

90 LINUX SHELL HANDBOOK - 2023 EDITION


Bash Scripting AUTOMATION

tory locations for a set of users. The files • The definition of TMPLIST uses com­ command include file mechanism. The
containing the list of users and the directo­ mand substitution to store the size field function is stored in functions.bash.
ries to examine are specified explicitly in (again via awk) from all lines of Is -IR The to_gb function in Listing 7 begins by
the script, but you could also use options. output corresponding to items owned by defining local variables. The function will
The script sets the path and incorporates the current user (identified by egrep). ignore any meaning the names might have
another file into the script via the so-called The Is command runs over the directo­ in the calling script, and their values also
dot command include file mechanism. ries specified in the ckdirs file and uses will not be carried back into the calling
A number of items are notable: the -block-size option to make its size script. The bulk of the function comprises
• The for command specifies a variable, display unit match that used by du (KB). arithmetic operations using $((... )). Bash
the keyword in, a list of items, and the TMPLIST is a list of numbers: one per provides only integer arithmetic, but I
separate command do. Each time file owned by the current user ($WHO). want to display a reasonably accurate size
through the loop (ending with done), • The second for adds numbers in TMP­ total in gigabytes, so I use a standard trick
the variable is assigned to the next item LIST to TSUM. The variable is N, and to extract the integer and remainder parts
in the list. WHO is assigned to each suc­ the list of items is the value of TMPLIST. of the gigabyte value and build the display
cessive item in the ckusers file. The con­ • The script twice provides built-in manually. For example, if I have 2987MB,
struct $(< file) is short for $(cat file). integer arithmetic via the construct dividing by 1024 would yield 2GB, so in­
• The definition of HOMESUM uses back $(( math-expression )). stead, I divide 2987 by 1000 (DI = 2) and
quotes to extract the total size of the us­ • The script uses the function to_gb to then compute 2987 - (2* 1000) (D2 = 987).
er’s home directory from the output of print each report line. Bash requires that Then, I print DI, a decimal point, and the
du. -s via aivk. eval makes du interpret functions be defined before they are first character of D2:2.9.
the expanded version of ~ $WHO as a used, so functions are typically stored in The printf command creates formatted
tilde home directory specifier. external files and invoked with the dot output. It requires a format string followed

Table 1: Bash Scripting Quick Summary


Arquments and Variables Constructing Conditions
$1 $2 ? $9 Command arguments -x file Tests whether file has condition indicated by
${nn} General format for argument nn code letter x. Some useful codes are: -s greater
$@ All command arguments: list of separate items than 0 length; -r readable; -w writable; -e exists;
$* All command arguments: a single item -d a directory; -f a regular file.
$# Number of command arguments file 7-nt file2 file 1 is newer than file2.
$0 Script name -z string string's length is 0.
$var Value of variable var -n string string's length is greater than 0.
${var} General format string 1 = string2 The two strings are identical. Other operations:
!-, >, <.
${var.p:n) Substring of n characters of var beginning at p
int1-eq int2 The two integers are equal. Other operations:
${var-val2} Return val2 if var is undefined
-ne, -gt, -It, -ge, -le.
${var+val2) Return val2 if var is defined ! NOT
${var=val2) Return val2 if var is undefined and set var=va!2 -a AND
${var?errmsg) Display "var. errmsg" if vans undefined -o OR
arr=( items) Define arras an array ( ) Used for grouping conditions.
${ardn]} Element n of array arr
${#arr[@]} Number of defined elements in arr Input and Output
getopts opts var Process options, returning option letter in var read vars Read input line and assign successive words to
(or ? if invalid, or: if required argument is each variable.
missing); opts lists valid option letters optionally read -p string var Prompt for a single value and place value en­
followed by a colon to require an argument tered into var.
(an initial colon says to ignore invalid options). printf fstring vars Display the values of vars according to the for­
Returns option's argument in OPTARG. mat specified in fstring. Format string consists of
literal text, possibly including escaped charac-
General Command Constructs ters(e.g., Itfortab, Infor newline) plus format
'cmd' Substitute output of cmd. codes. Some of the most useful are: %s for
$( cmd) Substitute output of cmd (preferred). string, %d for signed integers, %f for floating
$? Exit status of most recent command. point (%% is a literal percent sign). Follow the
$! PID of most recently started background command. percent sign with a hyphen to specify right align-
eval string Perform substitution operations on string and ment. You can also precede the code letter with
then execute. a number to specify a field width. For example,
. file Include file contents within script. %-5d means a five-digit integer aligned on the
exit n Exit script with status n (0 means success). right, %6.2f specifies a field width of six with two
decimal places for a floating point value.
Arithmetic
$(( expression)) Evaluate expression as an integer operation. Functions
+ -*/ Addition, subtraction, multiplication, division name () Use local to limit variable scope to the function
++ — Increment, decrement {
% Modulus commands
A Exponentiation }

LINUX SHELL HANDBOOK- 2023 EDITION 91


AUTOMATION Bash Scripting

by variables to be printed. Code letters The loop I starting value is the first script An array can be defined by enclosing its
preceded by percent signs in the format variable. At the end of each iteration, I is elements in parentheses. Specific array el­
string indicate where the variable content decreased by 1, and the loop continues ements are specified using the syntax in
goes. Here, %s indicates each location and as long as I is greater than 1. The body the second line: The array name is inside
that the variable should be printed as a of the loop multiplies F (set to 1 initially) the curly braces, and the desired element
character string. The \t and \n within the by each successive I. is specified in square brackets. Note that
format string respectively correspond to a element numbering begins at 0. Under
tab and newline, which you must include Generating Menus normal circumstances, the number of ele­
explicitly when you want the line to end. The final script illustrates Bash’s built-in ments in an array is given by ${#a[@]}.
Here is sample output from the script: menu generation capability via its select PKGS is defined as an array consisting of
command (Listing 8). Setup for the select the second field in each line in the file.
USER GB USED command happens in the definitions of The select command uses the contents
aeleen 80.S PKGS and MENU. The select command re­ of MENU as its list. It will construct a
kyrre 14.3 quires a list of items as its second argu­ numbered text menu from the list items
ment, and MENU will serve that purpose. and then prompt the user for a selection.
Another kind of for loop, similar to that It is defined via a command substitution The item selected is returned in the vari­
found in many programming languages, construct. Here, I add the literal string able specified before in (here WHAT),
supplies a loop variable, its starting value, Done to the end of the list. and the item number is returned in the
a continuation condition, and an expres­ The definition of PKGS introduces a variable REPLY.
sion indicating how the variable should be new feature: arrays. An array is a data The script will use the value of REPLY
modified after each loop iteration structure containing multiple items that minus 1 to retrieve the corresponding
can be referenced by an index: package name from the PKGS array in
F=1 the variable PICKED (I use $REPLY-1, be­
for (( I=$l ; I>1 ; I— )); do a=(l 2 3 4 5) cause menu numbering begins at 1, al­
F=$(( $F*$I )) $ echo ${a[2]} though array element numbering begins
done 3 at 0). The select command exits when
the user picks the Done item.
Listing 6: Reporting on Disk Space The following is an example run:
01 #!/bin/bash
02 1) CD/MP3_Player 3) Photo_Album
03 PATH=/bin:/usr/bin # set the path 2) Spider_Solitaire 4) Done
04 . /usr/local/sbin/functions.bash # . f => include file f here
#? 2
05
Installing package spider ... 7
06 printf "USER\tGB USED\n" # print report header line
07 for WHO in $(</usr/local/sbin/ckusers); do Please be patient!
08 H0MESUM='eval du -s ~$WH0 | awk ’{print $1}’' many more messages ...
09 TMPLIST=$( Is -1R —block-size 1024 $(</usr/local/bin/ckdirs) | #? 4
10 egrep "A................ +[0-9]+ $WH0" | awk ’{print $5}’ )
11 TSUM=0 Conclusion
12 for N in $TMPLIST; do
13 TSUM=$(( $TSUM+$N ))
You can use the techniques described in
14 done this article to build your own Bash scripts
15 TOT=$(( $HOMESUM+$TSUM )) for automating common tasks. Be sure to
16 to_gb $WH0 $TOT check out Table 1 for a quick reference on
17 done
Bash scripting terms. ■

Listing 8: Generating Menus


01 #!/bin/bash
02
03 PATH=/bin:/usr/bin
04 PFILE=/usr/local/sbin/userpkgs # entry format: pkgname menu_item
05
06 PKGS=( $(cat $PFILE | awk ’{print $1}’) ) # array of package names
07 MENU="$(cat $PFILE | awk ’{print $2}’) Done" # list of menu items
08
09 select WHAT in $MENU; do
10 if [ $WHAT = "Done" ]; then exit; fi
11 !=$(( $REPLY-1 ))
12 PICKED=${PKGS[$I]}
13 echo Installing package $PICKED ... Please be patient!
14 additional commands to install the package
15 done

92 LINUX SHELL HANDBOOK - 2023 EDITION


Images and PDFs AUTOMATION

ImageMagick and PDF tools File Info


Before you edit, you might want to ex­
amine a file’s characteristics. The tool

IMAGE MAKERS for gathering information is identify.


As the name suggests, it shows basic
information about a file. In its most
You can use the command line to modify images and create PDFs. simple form, identify is followed by a
file name, but the -verbose option re­
BY BRUCE BYFIELD AND TIM SCHURMANN veals more.
Figure 1 reveals a JPEG file with a reso­
efore graphical desktops were the image formats - from standard formats lution of 3264x2448 pixels, in which each
norm, many Linux users ran com­ like JPEG, GIF, and PNG, to the RAW for­ color channel contains 8 bits of color in­
mand-line programs to process mat for major brands of digital cameras. formation. The use of three color chan­
their images. Although it might seem para­ The ImageMagick tools let you process a nels (red, green, and blue) results in a
doxical to use a non-graphical environ­ number of images easily. The suite com­ color depth of 24 bits. The last value
ment to process graphical files, in many prises 11 commands (Table 1) that share gives file size information and is followed
cases, the command line is the easiest a common structure and - mostly - the by the metadata, with several screens of
place from which to operate. On another same options. detailed information, including the color
front, Linux users now have a number of The syntax of ImageMagick commands model, channel statistics, and compres­
tools for creating and modifying PDFs. is similar to most Bash commands, ex­ sion mode.
cept they are not prefixed with two hy­ Another way to gather file information
ImageMagick phens, just one: is to use the compare command, which
ImageMagick [1] is one of the oldest can be useful if you have different ver­
and most widely used tool suites for command -options inputfile outputfile sions of the same image or keyframes in
graphics editing. The cross-platform an animation sequence. The compare
tools work with more than 100 different The choice of options varies with the com­ command requires two input files and
mand. Although you an output file. Entering
can use an option un­
related to a command compare masthead.old.jpg 7
to edit on the fly (e.g., masthead.png masthead-compare.png
specifying the output
image size while com­ results in an image in which pixels that
positing images), differ between files are colored red. To see
sometimes an option the comparison on your desktop, use:
does not work with a
command. To avoid compare ./masthead.old.png 7
confusion, you might ./masthead.old2.png x:
prefer to avoid on-the-
fly editing and stick to Once you are finished looking, you can
convert or mogrify, the right-click on the display on the desktop
main commands in­ and select Quit from the contextual menu
Figure 1: Discover detailed information about your photo, includ­ tended for detailed ed­ to close it.
ing resolution, color, and file size. iting.
Screenshots
Table 1: ImageMagick Commands One way to get graphical material is to use
Command Action the import command as a screen capture
animate Plays a sequence of images. utility. Just enter the command followed
compare Compares images and creates a file showing the pixel-by-pixel differences. by the file in which to save the screen cap­
composite Lays one image over another. ture. When you press the Enter key, a
conjure Interprets and runs an Magick Scripting Language (MSL) script [2]. crosshairs cursor appears, and you can ei­
convert Converts between formats and comprises the primary editing commands. ther click in a window or choose a section
Writes changes to a new file. of the screen to capture. If you want to
display Displays an image. capture the entire screen, the command is
identify Provides information about an image file.
import Creates screen shots. import -window root capture.png

mogrify Like convert, but it writes over the original file.


Should you need a delay to get the termi­
montage Combines images into a panorama, a poster, or an overview.
nal out of the way, add the -delay [sec­
stream Extracts pixel components a row at a time to a storage file.
onds] option at the end of command.

LINUX SHELL HANDBOOK- 2023 EDITION 93


AUTOMATION Images and PDFs

Editing Commands to use -annotate or -draw. To add cap­ you have a large number of files, this
The basic editing commands in Im­ tions, you first need a file with the font shell command lets you convert them all
ageMagick are convert and mogrify. The you want to use, preferably in a Tru­ at once:
main difference between the two is that eType format [.ttf). The @ symbol be­
convert produces a new output file, fore the file name in Listing 1 tells con­ for i in *.jpg; P
whereas mogrify writes over the original. vert that it is dealing with a TrueType do convert $i P
The available options each have their font. The rest of the command places the $(basename $i .jpg).tiff; P
own set of possible values [3]. Some op­ text Vacation in the mountains (with done
tions, like -debug and -verbose, provide -draw) at position [100, 150) in black.
troubleshooting information and help you with a point size of 20 pixels [-pointsize For each file ending with .jpg, the shell
keep track of what you are doing, but most 20) in the font.ttf font. removes the extension, replaces it with
options are editing functions comparable The color specified after -fill [black) .tiff, and calls convert with the results.
to those you would find in a desktop can also be entered as the corresponding To convert all of your vacation photos
graphics editor. For instance, you can use RGB values in decimal triplet, rgb(0,0,0), into thumbnails, use:
-border [geometry] and -bordercolor [color] or hexadecimal notation, ”#000000".
to place a border around an image. The command for i in *.tiff; P
Other options are -contrast to improve do convert $i P
its appearance, -crop [geometry] to shear convert -list color -resize 800x600 P
it, -flip to reverse its sides, or -size [width] $(basename $i .tiff).png; P
x[height] to alter its dimensions. lists all the known color names and their done
ImageMagick even has a limited num­ RGB values.
ber of filters to distort an image by adding Scaling. Monster images do not fit on The command reduces the size of the
interesting effects. For example, you can most monitors; plus, they eat up disk images to a monitor-friendly 800x600
use -blend [percent] to overlay one image space. The command pixels and simultaneously converts them
over the top of another, -paint to simulate into the space-saving PNG format.
an oil painting, or -sepia-tone to make an convert -resize 200x200 P
image resemble an old photograph. photo.tiff small-photo.png Graphical Interface
Additional options range from those that To see the changes you have made to
anybody can use to those requiring a strong reduces photo, tiff to 200x200 pixels - or an image, you can use the display
knowledge of color theory. The following rather, it tries to. To prevent distortions, command, which puts an image on
sampling of commands should give you a convert confines itself only to the dimen­ your desktop. By default, all the files
good idea of the power of ImageMagick. sions specified. An image that was origi­ indicated in the command are dis­
File conversion. Like all of its com­ nally 3264x2448 pixels ends up at 320x100 played at their full size in separate
panions in the ImageMagick package, pixels. If it is imperative that the image windows, but you can also view them
convert independently detects the target measure 200x200 pixels, even if it turns in a single window with a command
file format by its extension. Each appli­ out distorted in the end, place an exclama­ such as
cation knows that a photo named tion mark after the size [-resize 200x200!).
image.jpg is a JPEG photo. If the con­ Alternatively, you can work with percent­ composite 'vid:*.png'
verted file needs an exotic ending for age values (e.g., -resize 75%)
some reason (e.g., exot.exo), simply put which displays all the files in the current
the format at the beginning of the file Compositing directory that have a PNG extension.
name (e.g., TIFF:exot.exo). Moving beyond basic editing, the com­ If you click on a window created for a
Rotation. The -rotate option, of course, posite command overlays one image on single image, a floating window with a
rotates images. For example, the command another, which could also be used as a menu opens (Figure 3), providing easy
way to watermark your photos: access to the options that most users are
mogrify -rotate "90>" image.tiff likely to want.
composite parrot.png P Almost every major programming lan­
rotates image, tiff clockwise 90 degrees. painting.png combined.png guage has implemented a slightly more
Note that if you do not use the quotation sophisticated interface [4], ranging from
marks, the shell will interpret the angle If you want to position parrot.png more C’s MagickWand to Java’s JMagick and
bracket as a redirect and delete image, tiff. exactly, you could add the -gravity Ruby’s RMagick. If you are curious, you
Captions. The -caption option just [value] option, which takes values such can see an example of PeriMagick at Im­
makes a metadata entry, so if you want a as Center, East, or Southwest (Figure 2). ageMagick Studio [5].
caption under or on the image, you need Thumbnails provide an overview of
Batch your images so you can locate specific
Listing 1: Adding a Caption Processing photos easily. The command
convert -font (ffi/home/tim/fonts/font.ttf -pointsize 20 A real strength of the
-fill black -draw "text 100, 150 'Vacation in the command line is montage -label '%f' *.png P
mountains'" image.tiff caption.tiff
batch processing. If -frame 5 overview.png

94 LINUX SHELL HANDBOOK - 2023 EDITION


Images and PDFs AUTOMATION

create the PostScript file, then Ghostscript gs -sDEVICE=pswrite 7


or the related ps2pdf script [9] can create -sOutputFile=adclresses.ps 7
the PDF. Because PDF is a subset of the -dBATCH -dNOPAUSE addresses.txt
PostScript language, converting from one
to another is both accurate and quick. Here, -sDEVICE defines a printer - or, in
From the command line, a2ps, short for this case, a virtual printer - for creating
“all to PostScript,” is particularly useful for PostScript files; -sOutpuiFile identifies the
image formats. By calling on other stan­ name of the file to which Ghostscript will
dard utilities, such as ImageMagick, for write a PostScript version of addresses.txt,
the conversion of image files, a2ps seam­ called addresses.ps. While not strictly
lessly converts most of the common file need, -dBATCH exits the Ghostscript com­
formats to PostScript. Although it cannot mand line when the command has com­
handle the Open Document Format or pleted, and -dNOPAUSE eliminates the
Figure 2: Composite with -gravity Southwest Rich Text Format, it will work on most need for verification when a problem
ensures that the first file is positioned in the graphics formats, as well as plaintext files. arises. You can also specify additional
bottom left corner. Assuming your system’s default printer input files, each separated by a space, to
supports PostScript, the basic command is: be merged into the single output file.
collects your photos, adds a border to Once you have the PostScript file, the
every preview image, writes the file a2ps —output=OutputFilename P command format for creating the PDF
name at the bottom {-label '%f'~), and InputFilename version is exactly the same, except the
packs the finished candidates into the value of -sDEVICE is pdfwrite, the exten­
overview.png file. The result is a large Unless you specify the output file, a2ps sion of the output file is .pdf, and the ex­
poster of your thumbnails. prints to the default printer on your system tension of the input file is .ps.
(Figure 4); also, you can choose to send Of course, you can specify far more if
Help the output to another PostScript printer by desired, such as output resolution, with
If you want to know the valid values adding the -print = [PrinterName] option. -rfresolution] to produce a higher quality
for an ImageMagick option, run the -list By default, a2ps is set to verbose PDF or, if the dimensions of the resolu­
option to see a summary of available mode. The -q option suppresses all feed­ tion vary, with -rXfresolution]
commands. Then you can run -list [com­ back, but running a2ps verbosely is usu­ Y[resolution]. Alternatively, you can use
mand] to see the possible values. The ally a good idea because it saves opening -dPDFSETTINGS = [configuration] to set
ImageMagick website also offers practi­ the output file to see the results. the output to one of the predetermined
cal examples of complex commands [6]. To get the desired output, you might need settings, including /screen for low resolu­
to specify format options. The possibilities tion (online use), /ebook for medium
PDFs are far too numerous to list here, but, for resolution, and/printer or/prepress for
You can create PDFs from the command example, you could specify -portrait or higher resolutions. See the Ghostscript
line using PDF-specific scripts like -landscape to change the page orientation. man page for additional options. ■
chm2pdf or wkhtmltopdf. Some command­ If necessary, you can also specify:
line tools, such as LaTeX, also create PDFs. INFO
For plaintext and common graphic for­ —lines-per-page=Number [1] ImageMagick:
mats, creating a PDF at the prompt is a —characters-per-page=Number http://www.imagemagick, org/
two-step process: First, you create a —copies=Number
[2] MSL: http://www.imagemagick.org/
PostScript file, and then you create a script/conjure.php
PDF file from the Ghostscript
[3] ImageMagick command-line options:
PostScript file. As an alternative to a2ps, you can work h ttp://www.imagemagick, org/script/
The a2ps tool [7] or directly with Ghostscript to create both command-line-options.php
Ghostscript [8] can the PostScript and the PDF files. Be
[4] ImageMagick APIs: https://im-
warned, though, Ghostscript has a for­ agemagick. org/script/develop.php
Figure 3: The display midable array of options [ 10]. Luckily,
[5] Perl Magick: https://imagemagick,
command includes a in creating PDFs, you are generally
org/script/perl-magick.php
graphical menu from working with only a small subset of
[6] ImageMagick examples:
which you can access those options. In fact, in many cases,
http://www.imagemagick.org/Usage/
some of ImageMagick's the basic command structure is all you
[7] GNUa2ps:
most common options. will need:
http://www.gn u. org/software/a2ps/
nanday:/home/bruce# a2ps emacs.txt [8] Ghostscript: http://en.wikipedia.org/
[emacs.txt (plain): 1 page on 1 sheet]
wiki/GhostScript
request id is BWPrinter-818 (0 file(s))
[Total: 1 page on 1 sheet] sent to the default printer [9] ps2pdf: http://www.ps2pdf.com/
Figure 4: Unless you specify an output file, a2ps prints directly to the [10] Ghostscript options: http://www.
printer. gnu. org/software/gv/man ual/gv.html

LINUX SHELL HANDBOOK- 2023 EDITION 95


INDEX

BASH COMMAND INDEX


:P.........................................................7 burning DVD/CD.........................65 echo................................................. 20
Bash Command Index
/proc virtual filesystem............. 26 bzip2............................................... 10 edit-sources, APT......................... 61
Symbols____________ /run/systemd/system/.............. 46 bzipcat.............................................11 egrep................................................ 91
'.................................. 18, 88, 91 /sys virtual filesystem............... 26 bziprecover....................................11 elif....................................................90
enable-repo, DNF.........................64
........................................................ 91 :t......................................................... 7
........................................... 7, 90, 91 /usr/lib/systemd/system/.......46 c env................................................. 19,44
cal....................................................36 erase, DNF......................................62
(...)......................................... 91,92
eval...................................................91
[•••]................................................ 92 A case................................................. 89
ExecReload, systemd.................. 48
{ ... }....................................... 18, 92 a2ps................................................ 95, cat.................................................... 11
ExecStartPost, systemd.............. 46
adduser...........................................40 cd.................................................. 7, 8
&...................................................... 57 ExecStartPre, systemd........ 46, 48
alias...................................... 7, 21, 37 ~.................................................. 7
it.......................................... 21 ExecStart, systemd............... 46, 50
Applmage.......................................64 . (dot command)....................... 7
#!...................................................... 88 ExecStop, systemd...................... 48
apropos............................................. 8 .. (dot-dot command).............. 7 execute permissions................... 40
%..................................................... 92
apt.............................. 58, 59, 60, 61 changing group membership... 42 exit.................................................43,91
> ..................................................... 21
apt and apt-get table of com­ check, APT.................................... 60 Exponentiation.............................91
1:1 copy......................................... 65
mands............................................ 59 check-update, DNF.....................62 export...................................... 19, 86
$.......................................... 19, 88, 91
apt-cache...................................... 61 chgrp.............................................. 42 ext3/4.......................................32-33
$!.......................................................91
apt-get...................... 58, 59, 60, 61 chmod..................................... 41, 88
$?..................................................... 91
aria2c...................................... 75, 76 +, -, =......................................41
F
$(...)..................18, 88, 89, 91,92 fdisk........................................ 30-31
arp.................................................... 67 chown............................................. 42
$(< ...)..........................................91 fg...................................................... 57
at.............................................. 86, 87 clean, APT......................................60
${ ... }.............................. 89, 91,92 file............................................ 10,11
atd.................................................... 86 clean, DNF.................................... 63
$@................................... 88, 89, 91 filesystems.............................32-33
atrm................................................. 86 cp.................................................. 7, 8
$*..................................................... 91 find...................... 10,12-13,22,24
autoclean, APT............................ 60 Parted........................................ 31 fixparts...........................................30
$#...................................... 88, 89, 91
autoremove, APT......................... 61 cpio..........................................10,11 Flatpak............................................ 64
$0..................................................... 91
awk............................ 23,24, 90,91 cron........................................ 86, 87 for............................................ 90, 92
-a.......................................................91
crontab.................................. 86, 87 foreground processes......... 56-57
.bashprofile..................................... 6 free........................................... 55-56
curl...................................................75
. (dot command).......................... 91 background processes........ 56-57 fsck...................................................33
Curl................................................. 74
/etc/apt/sources.list....................61 backups......................................... 66 fsck.vfat......................................... 33
cut......................................23,24,25
/etc/default................................... 28 bash_history..................................20 fstab........................................ 34, 35
/etc/group......................................39 bg..................................................... S7 D
/etc/passwd......................... 39, 47 block size.......................................65 data, rescuing............................... 65 G
date.................................. 36, 37, 38 gdisk................................................ 30
/etc/shadow..................................39 Btrfs...........................................32-33
dd...................................... 9, 65-66 genisoimage........................... 65-66
/etc/systemd................................ 29 btrfsck............................................ 33
Debian package manager......... 58 getopts............................................ 89
/etc/systemd/system.................. 50 btrfs-convert..................................33
Ghostscript
/etc/systemd/system/............... 46 Btrfs, resize................................... 33 debugfs.......................................... 33
gs...........................................95
delete software.................... 60, 62
:h.........................................................7 build-dep, APT............................ 60 GID...................................................39
delete user account.................... 40
-o.......................................................91 bunzip2........................................... 11 GNU Parted................................... 31
device............................................. 67
googler..................................... 76, 77
device files.................................... 34
GPT................................................. 30
device names................................ 34
grep.................................. 13,15, 90
df...................................................... 32
-E................................................ 15
dig.................................................... 70
groupadd........................................ 40
dig NS..............................................70
group commands, DNF.............. 62
disable-repo, DNF....................... 64 groupdel......................................... 40
disk partitions............................... 34 groupmod..................................... 40
DNF.........................................61, 62 groups command........................ 42
do..................................................... 91 gunzip.............................................10
done................................................ 91 gzip.................................................. 10
dot (.) command..........................28
downgrade, DNF.......................... 63 H
dpkg, APT......................................60 hardware configuration..... 26-29
dpkg-query, APT.......................... 60 hdparm...........................................26
du.............................................. 33,91 head........................................ 22, 23
history............................................ 20
E history, DNF..................................63
e2fsck............................................33 host................................................. 70
e4defrag........................................33 hwclock..................................36, 38

96 LINUX SHELL HANDBOOK - 2023 EDITION


INDEX

mkisofs................................... 65-66
mklabel, Parted............................. 31
rescue, Parted............................... 31
resize, Parted.................................31
u
IDE devices................................... 34 UEFI
mkpartfs, Parted.......................... 31 rfkill................................................. 72
if........................................................88 GPT.....................................30
mkpart, Parted.............................. 31 rm......................................7, 9, 10, 8
ifconfig............................................ 67 UID.................................................39
rmdir...................................... 7, 9, 8
ImageMagick mkswap......................................... 33
route................................................ 67 umask.............................................. 7,42
compare...............................93 modinfo......................................... 26
RPM packages.............................. 61 umount.............................34, 35, 66
composite................................ 94 modprobe....................................... 26
rsync....................................... 84, 85 uname............................................ 26
convert.............................. 93, 94 mount..................34, 34-35, 34-35
uninstall software................ 60, 62
display.......................................94 move, Parted.................................. 31 s uniq................................................. 24
identify......................................93 mtr...................................................70 s bit................................................. 41
units................................................ 46
import........................................ 93 mutt................................................. 79 sep....................................................82
universal package managers ... 64
mogrify..................................... 93 Mutt......................................... 77, 78 search, DNF................................... 63
select...............................................92 unset................................................ 19
montage.................................... 94 mv.........................................9, 10,11
Table of commands............... 93 select, Parted.................................31 update, APT.................................. 61

images set.................................................... 19 updatedb........................................ 13


backup..................................66 setuid/setgid bit........................... 41 update software.................... 61, 62
sftp............................................ 82, 83 upgrade, APT................................ 60
bootable.................................... 66
sgdisk............................................. 30 upgrade, DNF............................... 62
CD...............................................65
sh..................................................... 21
DVD............................................ 65 uptime..................................... 55-56
shift................................................. 88
ISO............................................. 66 useradd...........................................40
shopt................................................. 7
info........................................ 7, 8, 38 userdel............................................ 40
show, APT......................................60
info, DNF....................................... 62 usermod......................................... 40
OpenSSH.........................................81 showpkg, APT.............................. 61
init........................................... 46, 54 skip-broken, DNF........................ 64 users and groups.......................... 39
install, DNF................................... 61
p Snap................................................ 64
install software.................... 58, 61 package groups.............................62 sort............................................24, 25 V
ip...................................................... 67 parted..............................................31 source.......................................37, 86 VFAT......................................... 32-33
isoinfo............................................. 66 partitions........................................ 30 source, APT................................... 60 VFAT, corrupted........................... 33
isolinux...........................................66 partition table............................... 31 sources.list, APT.......................... 61
visudo............................................. 44
iw......................................................71 passwd............................................ 40 spaces in shell scripts................. 28
iwctl................................................ 72 password split................................................. 25
ss.......................................................70
w
encrypted............................ 39
w3m...............................................79,80
J paste................................................ 24 ssh............................................. 81-83
jobs................................................ 57 restart........................................ 81 wc.................................................. 22,25
PATH................................................ 20
join.......................................... 24, 25 perl...................................................16 ssh-keygen.................................... 82 WEP................................................ 71
journalctl.............................. 49, 50 permissions...........................39, 40 station............................................. 73 wget................................................ 75
Journald........................................ 49 block of three.......................... 41 status............................................... 71 whatis................................................8
hierarchy................................... 41 sticky bit........................................ 41 whereis........................................... 13
K octal, binary, letters...............41 su....................................... 43, 44, 45 which..............................................13
kill...................................................56 read, write, execute............... 40 root..................................... 43, 44 while............................................. 89,90
killall..............................................56 umask........................................ 42 sudo....................................... 44, 45,
whoami...........................................43
Pgrep...............................................57 sudoers file.................................... 45
WPA......................................... 71,72
ping................................................. 69 swapon...........................................33
pkill................................................. 57 sysctl...............................................28 wpa_cli.................................... 71, 72
Links2...................................... 79, 80
list, DNF......................................... 62 printf...................................... 91, 92 sysfs................................................. 26 wpa_supplicant............................71
In.........................................................9 procfs...............................................26 system.conf................................... 29 write permissions........................ 40
locate...............................................13 provides, DNF............................... 62 systemctl....29, 34, 47, 48, 52, 54
Logical Volume Manager......... 31 ps................................ 23,54, 55,56 daemon-reload....................... 29 X
logout............................................. 43 pstree...............................................54 systemd29, 46, 47, 48, 49, 50, 51, xargs................................................ 17
Is..... 7, 9, 10,11,14,16,19,91,8 purge, APT.................................... 60 54, 67 XFS............................................32-33
Isblk................................................. 26 pwd...............................................7, 8 systemd-delta.......................... 29
xfs_check.......................................33
Iscpu................................................26 units override.......................... 29
XFS, defragment.......................... 33
Ishw................................................. 26 systemd-analyze.......................... 52
xfs_fsr............................................. 33
options..................................... 27 read.......................................... 90, 91 systemd-mount.............................34
read permissions.......................... 40 systemd-run..................................53 xfs_repair.......................................33
Isof...................................................35
Isusb................................................26 Redirection tools systemd-umount.......................... 34 xmtr................................................. 70
LVM................................................. 31 <..........................................17 xorrisofs...................................65-66
>..........................................17, 18
>&.............................................. 17 Y
makecache, DNF.......................... 63 > >............................................ 17 Yum................................................. 61
man............................................ 7, 38 |............................................ 17, 18

man pages........................................ 8
Regular expressions .... 14,15, 16 top............................................. 54-55 z
Table of regex operators..... 15 touch............................................... 10
Master Boot Record.....................30 zcat................................................... 10
reinstall, DNF............................... 63 tput...................................................21
MBR................................................ 30 zemp................................................ 10
removable media.........................34 tr...................................................... 25
convert to GPT....................... 30 zdiff..................................................10
remove, APT..................................60 tracepath........................................ 69
metapackages....................... 58, 62 remove software................... 60, 62 traceroute................................ 69, 70 zegrep.............................................. 10
mkdir............................................ 7, 8 renice........................................ 55-56 tune2fs............................................ 33 zfgrep.............................................. 10
mkfs........................................32, 33 repositories, Debian................... 60 type....................................................8 zgrep............................................... 10

LINUX SHELL HANDBOOK- 2023 EDITION 97


SERVICE Contact Info

LINUX NEW MEDIA CONTACT INFO


THE PULSE OF OPEN SOURCE Editor in Chief
Joe Casad, jcasad@linuxnewmedia.com
Visit us today for high-tech insights with a practical edge:
Managing Editors
ADMIN Rita L Sooby, Lori White
https://www.admin-magazine.com Subscribe to these titles or shop for
Contributing Editors
one of our other publications at: Uli Bantie, Andreas Bohle, Jens-Christoph
Linux Magazine
Brendel, Hans-Georg EBer, Markus Feilner,
https://www.Un ux-magazine.com h ttps://shop. linuxn ewmedia. com/
Oliver Frommel, Marcel Hilzinger, Mathias
Linux Update Newsletter Huber, Anika Kehrer, Kristian KiBling,
https://bit.ly/Linux-Update Jan Kleinert, Daniel Kottmair, Thomas
Leichtenstern, Jorg Luther, Nils Magnus
Localization
AUTHORS Ian Travis
Copy Editors
Joe Zonker Brockmeier 39, 67 Hans-Peter Merkel 30 Amy Pettie, Aubrey Vaughn
Paul Brown 58 James Mohr 67 Layout
Bruce Byfield 6,9,19, 26,30,39, 43, Klaus Rehfeld, Lori White, Dena Friesen
Hal Pomeranz 22
58, 65,74, 93 Cover
Dmitri Popov 12,81 Lori White and Dena Friesen, paylessimages,
Joe Casad 3,12,34,39, 46, 67,74, 81 123RF.com
Nate Drake 67 Tim Schurmann 46,93 Advertising
/Eleen Frisch 88 Brian Osborn, bosborn@linuxnewmedia.com
Matt Simmons 39 Phone: +49 8093 7679420
Karsten Gunther 26
Martin Streicher 14,17 Marketing Communications
Jorg Harmuth 81 Gwen Clark, gclark@linuxnewmedia.com
Ferdinand Thommes 67 Publisher
Heike Jurzik 34,36,39,54,65,81,84, 86
Brian Osborn
Klaus Knopper 26 Nathan Willis 30,32
Customer Service / Subscription
Charly Kuhnast 74 Harald Zisler 74 For USA and Canada:
Email: cs@linuxnewmedia.com
Phone: 1-866-247-2802
(Toll Free from the US and Canada)
For all other countries:
Email: subs@linuxnewmedia.com
Linux New Media USA, LLC
4840 Bob Billings Parkway, Ste 104,
Lawrence, KS 66049, USA.
www.linux-magazine.com

While every care has been taken in the content


of the magazine, the publishers cannot be held
responsible for the accuracy of the information
contained within it or any consequences arising
from the use of it.
Copyright and Trademarks © 2023 Linux New
Media USA, LLC
No material may be reproduced in any form
whatsoever in whole or in part without the written
permission of the publishers. It is assumed that
all correspondence sent, for example, letters,
email, faxes, photographs, articles, drawings, are
supplied for publication or license to third parties
on a non-exclusive worldwide basis by Linux
New Media unless otherwise stated in writing.
All brand or product names are trademarks
of their respective owners. Contact us if
we haven't credited your copyright; we will
always correct any oversight.
Printed in Nuremberg, Germany by Zeitfracht
GmbH.
Distributed by Seymour Distribution Ltd,
United Kingdom
Linux Magazine Special (Online: ISSN 2832-9155,
Print: ISSN 1757-6369)
Linux Magazine Special is published by Linux
New Media USA, LLC, 4840 Bob Billings Parkway,
Ste 104, Lawrence, KS 66049, USA
Linux is a trademark of Linus Torvalds.
Represented in Europe and other territories by:
Sparkhaus Media GmbH, Bialasstr. 1a, 85625
Glonn, Germany.

98 LINUX SHELL HANDBOOK-2023 EDITION


Linux Magazine Subscription
Print and digital options
Linux Android Backup
Save smartphone data to a Linux PC
12 issues per year

LINUX ® ^SUBSCRIBE
I^MAGAZINE^f

Artificial^
Intelligence
Real-world
machine learning
shop.linuxnewmedia.com/subs
. :k I __
CircuitMess Nibble: Get started
- with microcontroller programming
Expand your Linux skills:
• In-depth articles on trending topics,
Bluetooth Tricks
Connect your Rasp Pi
including Bitcoin, ransomware, cloud
i
to a smartphone
SSH Front Ends Quantum
computing, and more!
|
|
Clean Code
Tips for better coding Computing
Raspberry Pi Tricks> | one • How-tos and tutorials on useful tools
*" Go wireless with Bluetooth

that will save you time and protect


LINUX
.... _
X I MAGAZINE H ----- your data
• Troubleshooting and optimization tips
jGeneratij deb-get: Easy repository for
third-party .debs

Insightful news on crucial developments


in the world of open source

faces: Computers teach Cool projects for Raspberry Pi, Arduino,


computers to lie
and other maker-board systems
Overlay Network „twi—
Keep the spies out of Find vulnerabilities before
your business an attacker finds them Go farther and do more with Linux,
Knowledge Management Build Your Own
with Logscq 30 Bingo Game
targets subscribe today and never miss
Make your Linux app FOSSPICKS
multilingual 10TERRIFIC FREE TOOLS!
another issue!

Follow us
@linux pro © Linux Magazine

©linuxpromagazine Qjj ©linuxmagazir


lazme
LINUX
UPDATE

Need more Linux?


Subscribe free to Linux Update

Our free Linux Update newsletter delivers


insightful articles and tech tips to your
inbox every week.
bit.ly/Linux-Update
|ruby-1.9.3-pl94| Homebase in
cd workspace

cd jockeyjs
git status
।ruby-1.9.3-pl94| Homebase in -/workspace
friend.memories steggybot
terminal-screenshots
apartmentlist inrkpvis
AutolayoutCoUectionViewIssue
Contentment
DynamicResizeUITextView
justANudge basb-lt-theme-screenshots
TestuserDefaults run.distance
drugs-and-booze-check
WhereTheHellAreYouiOS facebook_event_gcal
XcodeOocExpander

o . cd jockeyjs

,'SSter <| - ;« ««»


# On branch master
BASH
.««nte *r ”"

|f„b,-1.9.3-P 'desktop

Be an expert
Use Bash shell on a TUXEDO
With a TUXEDO, you get your Linux laptop delivered to your home
customized, and with the Linux Shell Handbook you have tons of tips
and tricks at your fingertips on how to further configure your TUXEDO
the way you like it.

100%
5
Year Lifetime Built in Germany Local
Linux Warranty Support Germany Privacy Support

IuXedo
tuxedocomputers.com

You might also like