LINUX SHELL
fa rN N D BOO 44 Payee Tat Gl
YOUR LINUX SKILLS
Vee aie
Monitor processes
Create custom scripts
LINUX NEW MEDIA
‘The Pulse of Open Source
WWW.LINUX-MAGAZINE.COMeo) sy) mel ar: VL
News « Careers ° Life in Tech
Skills * Resources
FOSSlife.orgBASH CLASS
Think like the experts; The powerful Bash shell provides a comprehensive collection
of utilities for configuring and troubleshooting Linux systems,
Eee N Nee MUS EUR ACen a ay a Sen iC eS
Pe SEs Oe SCN COM Reo eee
prefer to work from the keyboard, and many will ell you that
Con Rese a Mice Me Sue
Ree amt Sua fan Se
Orestes oa eee
Geemarc ees ema
found on most Linux systems.
Sea ure Cau cre
anemia
Crema Sse aoa
Sonar MUU a cmscu TU}
Tease Re)
au shee
Ger posite eeu hd
Delp eeree Recah (ae
Ores eer roe
evapo?
Dee ey ee ae
CE Ce)
Poeun ese Meee
Ie Rue CAT RU
er Mas eee FyGETTING AROUND
6 Introducing Bash 4
17
9 File
Management _
mae, |e »
manage our fle >
z
12 Search Tools
Handy tools like find, locate, and whereis help you chase
«down files and programs on your system,
Regular Expressions
Regular expressions work with other tools to filter data
and help you find the snippet you really need. We show
you how to match characters with regular expressions.
Pipes and Redirection
Leam hovr to direct the output of one command to
Customizing Bash
Get mote productive by customizing the command-line
environment.
Text Manipulation Tools
‘Why slow down for a mouse? You can use some simple
command-line tools to search, sor, cut, paste, join, and
split your text files to zero in on the information you need.
26 Hardware Configuration 32. Configuring Filesystems
Learn about some tools for configuring You can’t store files without a flesystem. Use these Bash
and managing hardware on commands for easy filesystem configuration,
your Linux system.
» © 34 mount and fstab
, disk, and parted = Most Linux distros mount storage media automatically,
Use these handy disk but someday you might need a classic command-line tool
partitioning utilities to
configure your hard drive 36 Time Tools
before you install a new operating These utilities let you set and keep time.
system. <1
LINUX SHELL HANDBOOK ~ 2022 EDITIONLUN SiulelLl
HANDBOOK
cto
39 Users, Groups, and Permissions
The shell comes with some simple commands for
managing users and granting acces to system
43 suand sudo
‘Why lg into the root account if you can avotd itt
46 systemd
Systemd has become the standard for starting
stopping, and managing services in
Linux,
54 Managing Processes
Monitor and manage the
processes running on your
system.
58 Package Management
Tools
Linux package tools help
you install and manage software. We show you some
package tools in Debian and RPM-based systems,
65 dd and mkisofs/genisoimage/xorrisofs
Create backups and bootable CDs with these handy
disk utilities
BEST BASH
COMMANDS
eT te Wate
67 Networking Tools
We show you some Bash utilities for configuring and
troubleshooting networks.
Tp SSH
Secure remote connections.
78 Rsync
Synchronize your data.
80 Wireless
Wireless networking requires some special tools.
AUTOMATION
84 cron and at
‘Automate and schedule common tasks.
86 Bash Scripting
We shovr you how to start writing your own Bash
91 Images and PDFs
Use these picture perfect commandt-ine tools to convert
and adapt your digital images.
LINUX SHELL HANDBOOK - 2022 EDITION 5Beyond all the splash screens, screen savers, and vivid rock-star
wallpaper is the simple yet powerful Bash shell. BY BRUCE BYFIELD
any desktop users approach the
command line as though armed
with a magic spell. They have a
command - complete with options - to
type or paste to get the desired results,
but they are unclear what else might be
going on. This approach is understand:
able; however, if you take the time to
understand something of the structure
of the command line, you can increase
control over your computing,
By default, most Linux distributions
run Bash (the Bourne Again Shell). Bash
isa command-line interpreter ~ a pro
{gram that runs macros and other utilities
These macros and utilities are the com-
‘mands that you enter at the prompt. They
include those built into Bash, such as ed,
and many others that are external, includ
ing most ofthe commands that you run,
However, from the end user’s perspective,
the difference between internal and exter:
‘nal commands is unimportant
Like other shells, Bash can run inter
actively or non-interactively. When act:
ing as a login shell for your account,
Bash runs non-interactively, reading in-
structions from the .bashprofite file in
your home directory. in many cases,
commands give you the option to create
a file and run it non-interactive.
Most of the time, though, Bash runs as
an interactive shell, meaning that you
can enter commands and scripts using
the keyboard, and Bash will process
your input and display output. You can
also fine-tune how Bash runs with a set
of options similar to any commands,
‘These options can be entered in a term
nal profile or in a script that you run
when opening a command line.
‘One of Bash's most common options
is +7, which places Bash in restrictive
mode. In restrictive mode, some actions,
such as using the ed command ot chang
ing environment variables, are disabled.
Some administrators place Bash in re
strictive mode in the hope of limiting the
damage that rash users can cause on a
network, but, more often, restricted
shells are used to sandbox - that is, to
run a command in isolation for test put
LINUX SHELL HANDBOOK ~ 2022 EDITION
poses. The option ~dlebugger is also used
10 log debugging information.
Getting Around at the
Prompt
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
cf graphical user interface. To reach,
the command prompt on a GUL-based
Linux system, you'll need to open a
terminal window. Systems that use the
Gnome desktop environment typically
include the Gnome Terminal applica
tion, On Ubuntu, you'll find the Term
nal application by searching the dash
for "Terminal" (Figure 2). KDE-based
‘openSUSE systems, on the other hand,
include the Konsole terminal program,
‘which you will find in the Applications
| System menu. Several other terminal
programs are also available for Linux
systems. Consult your vendor docu:
mentation for more on finding your
way to a command prompt
While in the shell, you can forget
about your mouse, but you can copy
and paste, as the Edit menu shows. To
‘communicate with your systemitrae
You can modify how Bash operates by
sing its built-in commands. For instance,
the umask command changes the default
permissions used when creating a file,
Whereas the alias command can be used
tochange the name used to runa specific
‘command ~for example, my Debian sys
tem comes with Is -color=autoliased to
5, s0 that directories and different fil.
types are all colored.
‘Another way to modify Bash is through
the shoprbuiltin Figure 1). The shopt
command includes @ number of interest:
Ing, if seldom used, possiblities. For ox
ruceenanday
ineeerns
papas
$ shopt = cdspell
reyes
eet |
Figure tz shopt is a command built in o Bash
that provides many interesting features.
Here, the cdspell option automatically cor-
rects errors when you type directory names.
through the keyboard, type a line, then
press Enter. Of course, modetn tools,
like Konsole or the Gnome Terminal
are not terminals in the old sense but
are actually terminal emulators. You
can close or minimize the terminal
‘window as you would any other win-
dow on your Linux system.
‘This handbook assumes you have
some basic knowledge of how to move
around in the Bash shell. If you are look:
ing for a very basic crash course, a few
simple commands will help you get fa-
miliar with the command prompt.
Most likely, the terminal will open in
your home directory. Type 1s to list the
Contents of the directory. You can use the
a (change directory) command to move
to another directory. You'll also need to
mention the path to the target directory:
$08 Mnome/berney tate
Bash shells let you use a dot () in the
path to represent the current directory.
In other words, a user named berney
could move from his home directory to
the Music subdirectory by typing:
$04 Masic
‘A double dot means “go up one level in
the directory path,” so if bermey wanted
to go from /home/berney/Music back to
/home/berney, he could type:
‘ample, shopt-s cdspell enables Bash to
correct minor misspelings in its default
directories when you use the cd com.
‘mand. Similarly, shopt s checkjobs lists
any stopped jobs that remain won you
close the shell.
‘These few examples of what you can do
with Bash should be sufficient to show
‘that Bash i far from the passive recipient
fof your commands. Instead, lke the com.
‘mands that it runs, Bash is full of options.
‘and can be customized to suit your needs.
You'l earn more about customizing the
Bash environment later in this issue
$a
‘The tilde character (~ ) represents the
hhome directory, so wherever you are, you
‘can return to your home directory with:
Ifyou start to get lost when you are navi
gating around in the directory structure,
you can always enter the pud command
(print working directory) to display the
name of the current directory.
‘To create a new directory, enter the
‘mkdir command and give the name of
the new directory
4 kai /hone oemey tusic/Beat es
r, if user bemey were already in his
‘Music directory, he could just type:
4 mkdir «Beatles
‘The ep command lets you copy files. The
syntax is as follows:
cp ceounce_filenane> >
‘Beat ination #llensne>
Figure 2: Finding the Terminal in Ubuntu.
LINUX SHELL HANDBOOK - 2022 EDITION
Introducing Bash GETTING AROUND
The default is to look in the current di-
rectory, however, you can include a
path with the source or destination to
copy from or to a different directory.
Of course, you must have the neces:
sary permissions to access the direc:
tory. To delete a file, use the rm com:
mand, and to delete a directory, use
the rm-r or rmdir command. (Need-
less to say, be careful how you use
these commands.)
‘A summary of these basic commands
appears in Table 1. Each of these com:
‘mands includes additional options that
you can enter at the command line. As
you will lam later in this article, you
can type man or ino, followed by the
command, for information on syntax
and usage. For example, to learn the var
ious options for the mkdir command,
you would enter:
In later articles, you will learn about
other Bash commands for modifying
text, managing users, overseeing
processes, and troubleshooting net
works,
History
Ifyou are doing repetitive commands in
Bash, you ean save time by using the
history forthe current account. Stored
in the bash_histony file in your home di
rectory is alist of commands you have
run, with the oldest numbered 1. You
can use the arrow keys to move up and
down or use te plain command history
to see a complete list of what is stored
in your history.
Ifyou are somewhat more adventur-
ous, you can use a number of shortcuts
to una previous command in the his
tory Inumber rans the command with
that numbee Similaty, number sets the
number of previous commands to revert,
to, and fring rans the frst command
that inludes that sting
When you are ether vey certain of
what you ae doing or willing to live
dangerously, you can enter string*
string2 to repeat the last command but
replace the frst string of characters with
the second. Another rick isto add ho
remove the last element ofthe path in
the command ort to remove the first el
ement. However, if you are uncertain of
the results, you ean add po prin theBread
Bash Commands
1s Ustcontents of the current
directory
fed Change directory
[pwd Show current working directory
mkdir Make directory
cp Copyii
m___ Remove file(s)
rmdir Remove directory
command that you find but not run it
(Figure 3).
Documentation
Bash and the individual commands as.
sociated with it add up to a lotto learn,
Fortunately, you don't have to remember
everything. Like other Unix-type sys
tems, GNU/Linux includes a number of
different help systems.
‘The most basic form of help is the
‘man page (Figure 4). Man pages are di
vided into eight sections (see Table 2),
but most of the time, you only need to
type the command man followed by the
command, file, or concept about which
you want information.
However, some topics have entries in
several sections. To go to the specific
section, place the number of the section
between the man command and the
topic. Thus, man man takes you to the
basic page about the man command in
section 1, but man 7 man takes you to a
section about the collection of macros
used to create man pages. Either way,
when you are finished reading, you can
GETTING AROUND Introducing Bash
PA
Description
General commands
‘System calls
Figure 3: You can use several keyboard
shortcuts to run commands in the history
with slight changes, Here, the string “bruce™
Is replaced with “trish” in the frst case,
‘then only the head ofthe path is preserved
Inthe second.
press Curl#Z followed by Curl+C to re
turn to the command line,
When you are doing deeper research,
consider using apropos followed by
topic to receive a list of all the applicable
‘man pages. The one drawback to apro
pos is that, unless you are very specific
you could get dozens of pages, only a
few of which are relevant to you.
By contrast, if all you need is a brief
snippet of information, use whatis fol
lowed by the command. For example, if
you enter whats fdisk, you receive the
line ftsk (8) ~ Partition table manipula.
tor for Linux. The (8) refers to the man
section where detailed information is
available. Similarly, if you need to iden-
tify a file type, use type then the fle.
For several decades, man pages have
been the standard help form. However,
‘more than a decade ago, the GNU Pro}
ect made info its official help format
But, instead of replacing man, info has
simply become an alternative (Figure 5)
Although some man pages today stress
that the full help file is only available
through info, in praet
ce, many develop:
=a ee)
i
Clibrary functions
‘Special files (usually devices
found in fdov) and drivers
3 File formats and conventions
6 (Games and screensavers
7 ‘Miscellanea’
@
‘System administration com
‘mands and daemons
ers simply maintain both info and man,
focusing on the command structure in
the man pages and on basic instruction
in the info pages. SUill, It can never hurt
to check both in the hope of finding the
most complete information,
Digging Deeper
{As experts will be quick to note, these
comments provce only the barestout-
line of subjects that have filled entire
books. Read on for more about working
inthe Bash shel, For adlitiona informa
tion, a good place to start isthe man
pages. Another important reference is
the online Bash Reference Manual (1).
Read this material with a Bash shel
‘open next othe text, s0that you can try
commands as you lear about them. i
I] Bash Reference Manual
hattpnnwgnuorgtsoftware/bash/
‘manualbashrof htm
Figure 4: The man page for the Is comman
Figure 5: The info page for the Is command.
LINUX SHELL HANDBOOK ~ 2022 EDITIONLearning file management commands
FILEPOWER
We give you an overview of commands for moving, editing
UR
Nv/tinux wets evertingasa
Geen
beamong yout is pts These
conan se yt emenbe be
eae the anes te ulster
tncot he acne for canes
Dasa fle manaenent commands
faint tne eter dey and
fe movement argon an edting
(an ptetsty more dangers) hn
tel estoy equals, an aly
tolotbng orth ast standard
pater oreo mallee
Moving and Editing
Directories and Files
“The most basic commang for moving di
rectores and files ip. Its sructre is
simple: cp
«ilesourefile>
‘target>. By default, cp overwrites any
files of the same name in the target
rectory, but you can be cautious and use
the-b option to back up any files tha are
overwritten or the -u option to overwrite
only files that are newer than the ones in
the target directory (Figure 1)
‘Aso, you cana ~preserve= mode to
choose to preserve file attributes, such as
Figure t: The ep command alos you to be both cautious and flexible. He
STW nae a lee a} a ano)
‘owner or timestamp, or ~no-preserve
‘= mode to have them changed in the
files’ new location, Whether or not you
preserve attributes is especialy important
‘when you are logged in as root and mov-
ing around files owned by another user ~
say, fora backup of the /home directory.
Sometimes, you might not want to
waste hard drive space on multiple cop-
ies of the same file, in which case you
‘might prefer to use in» file link to create
a symbolic link, or pointer, to the or
nal ile, which takes up much less space
(Figure 2). Later, if you copy these sym-
bolic links to a backup, you can use cp
-L to ensure that the original file, not the
link, is used
Alternatively, you might prefer to
move a file with mv, which takes many
of the same options as cp. Also, you can
use mp to rename a ile, giving it the
same directory path but a different final
name (Figure 3). For example, to change
the name of the file garden. png while
keeping it in the same directory, you
could use mv /garden.png ./sun-yarsen
sgardens.png,
‘As you copy or move files, you might
‘want to create a new directory with
‘mkdir. Although this isa relatively
straightforward command, you can fine.
tune it with ~mode~ octal permissions to
set permissions for the new directory or
Pores
‘ensures that fles with the same name as those being copied are not overwritten and that the
‘owner ofthe files does not chane
LINUX SHELL HANDBOOK - 2022 EDITION
GREE CLS La
create the directories immediately above
it by adding the -p (parent) option.
‘Todelete, 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 isto create a special
folder and move files to it instead of
using rm or rmdir.
By default, mm works only on files. To
delete directories with it, you have to
use the -r option. As you might imagine,
m--rean remove key system files when
used thoughtlessly; thus, some users
prefer to add ~preserve-oot when run-
ning the command anywhere near the
root directory. In comparison, rmdir is a
‘much safer option, because it works
only on empty directories (Figure 4)
‘Acompletely different approach to file
‘management is taken by dd, an old Unix
utility that copies bytes or blocks rather
than files. Used mainly by administra
tors, dé has a non-standard syntax.
Briefly, dd can be used for such tasks as
creating an ISO image from a CD/DVD,
wiping a disk by filling it with random
data, and duplicating a partition or mas-
ter boot record, Just remember to con-
struct your dd command carefully and
double-check it. Even more than rm, the
dd command can be hazardous to your
system if you are inattentive, For more
Information on di, see the “dd and gen-
isoimage” chapter.
Navigating and Editing
Directories and Files
You probably already know that you
move around the directory ree withthe
command ed ~ a command
so simple that it has no options. You
might not know, however, that cd has
several shortcuts: cd. moves tothe
rectory immediately above the current
‘one; e- returns you tothe previous di
rectory; and ed ~ returns you to your
home directory (Figure 5). Combined
withthe command history ina virtual
terminal, these shortcuts are enough to
give you the equivalent ofthe back and
forward buttons in a web browser.
‘Once you are ina directory, use ls to
view the contents. In many distributions,
you will ind that (sis actually an alias of
|b -color, which displays different types
of files in different colors. Sometimes, it
is an alia of ls ~color-~lassify, which
adds the use of symbols such as / to in-GETTING AROUND File Management
$n
screenshot.
Figure 2: Creating a symbolic ink with In sa space-saving way of having the same file in two
places atthe same time.
Figure
Cie arg
Pst OMT
cree
e mv command does double-duty, both moving files and r
waming them.
Brn
WN Ee ceca]
Figure 4: The rmdir command is much safer to use than rm, because it can't delete directo-
Hes that stl have files in them.
Rim ki kee
Option
-amin -atime
‘Action
Minutes/days since a fle was accessed,
‘min
Minutes/days since a fil’s status was changed.
‘mmin
Minutes/days since a fle was modified
‘group Files that belong to a particular user group.
user Files that belong to a particular user.
‘maxdlepth ‘The maximum love of sub-directories in which to search,
‘mindapth ‘The minimum level of sub-directories in which to search
‘perm Designated permissions.
"The changes the date
and the time that the file was created.
Also note that the time starts with the
last two digits of the year and ends with
the seconds,
Compressing and Archiving
Compression i less essential now than it
was inthe days of 100MB hard drives,
but it continues tobe important for ere-
ating backups or sending ies as email
attachments, The Bash shell includes
LINUX SHELL HANDBOOK ~ 2022 EDITION
four commands for compression: the
original tar, gzip, bzip2, and ~ more
rarely - epio.
‘When you exchange files with users
of other operating systems, use gzip so
they can open the archive. Gzip's basic
use is straightforward, with alist of
files following the command, but you
ccan use a variety of options to control
‘what happens.
‘To set the amount of compression,
you can use the parameter ~-best
‘ , oF to set the speed of com:
pression, you can use ~fastest . Both are measured on a scale of
1 (09. 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
* zeat displays files in a gzip archive.
‘= zemp compares files ina gzip archive,
+ clifflists differences between files ina
gzip archive
‘+ zgrep, zegrep, and zfgrep search for
text patterns in gzip-archived files.
One especially useful utility is gunzip,
‘which amounts to an alias for gzip be-
‘cause it uses most of the same options.
But, if you can’t be bothered learning
another command, you can simply use
the command gzip od.
By contrast, the bzip2 command pro-
duces archives that are 10 to 20 percent
smaller than those produced by gunzip.
But, although bzip2 and gzip serve simi:
lar purposes, bzip’s options are consider-
ably different, For one thing, you have to
specify sub-directories, because bzip2
lacks an option, For another, you use
the-z option to compress files and ~d to
decompress. To keep the original files
after the archive is created, use the -k
option.
Like gzip, bzip2 has some related utill-
ties for working with its archives:
Crerecnc ey ener aay
Bete en arery
(eee eee mete)
Figure 6:Many distributions create an alias
{or is, soit automatically displays different
filetypes with diferent colors.* bzipcat displays the contents of a file
in an archive, with the same options
as the cat command,
+ bziprecover helps recover damaged ar-
chived files.
+ bunzip2 decompresses files.
‘The differences between gzip and bzip2
can be hard to remember, so many users
prefer to rely on the far command. The
tar command not only has the advantage
‘of having options to use gzip and gunzip
(2) or bzip2 (j), but it also offers far
more control over exactly how you com=
press files.
In fac, tars options run into the doz-
fens ~ too many to detail here. For exat
ple, you can use ~exclude «file> to ex-
clude a file and -p to preserve the per
missions ofa file. If you want to preserve
a directory structure, use -p. To be safe
‘when decompressing, use -k to prevent
any accidental overwriting of files.
‘The tar command also includes its
own built-in utilities in many cases. To
add one archive to another, use the
format
‘append ctarfie2>
‘To update an archive with newer versions
of files with the same name, use the -u
option, of to compare the files in an ar-
chive with other files, use the format:
‘er --compares
‘The fourth compression command, cpio,
has fallen out of favor in recent years,
probably because its format is non-stan-
dard. For example, to create an archive
with contputfile.epio>
‘That said, epio has even more options
than far, including such powerful alterna-
aeronenc ny
Meter) ea rere tenia
Figure 7: The fle command identifies the format
helping you identity them.
rn
Teste)
eee een
cer)
Gireeae niece riteer
Figure 8: A few regular expressions increase the
ity of commands. Here, they greatly simplify finding files.
Omer
tives as the ability to archive an entire di-
rectory tree and create archives in multi>
ple formats (of which TAR isthe only one
that is widely used), as well as numerous
‘options to view and edit already-archived
files, However, unless you are a system,
administrator or an old Unix hand,
chances are you will rarely see cpio used,
Extending File
Management with Globbing
One reason shell commands are s0 pow
erful is that they can work with multiple
files, With many commands, the easiest
way to work with multiple files by enter-
ing a space-delimited list directly ater
the command. However, the most con
cise and efficient way to handle multiple
files is through file globbing
File globbing refers to the use of
regular expressions (often abbreviated
to regex), pattern matching, metacha-
racters, or wildcards. The terms are
not quite synonymous, although they
are mostly used as if they were. What
ever term you use, it refers to a string
of characters that can stand for many
different strings
The most widely used glob in the Bash
shell is the asterisk (*), which stands for
any number of unknovin character
“This glob is especially usefal when you
want to find files that share the same ex
tension, For instance, the command Is
* png ist all the PNG graphics inthe
current directory
By contrast, a question mark (?)
stands for any single character. Ifyou
enter the command Is ca,png, the ist of
matches wil include the files ca.prg
and eab.png but not the file card.png,
‘which contains two characters insted of
one after the ca.
From these simple beginnings, globs
can quickly become more elaborate. To
specify specific characters, you can use
square brackets, so that test{12].png lo-
cates files test.png and
test2.png, but not fest3 pg
(Figure 8). Also, you can
specity a search fra regex at
the start (*) or the end ($) of
4 line, Similarly, you can
search at the start of a word
with \eor the end of 2 word
with \>~ and these are sim:
ply afew common possbi
ties. Using globs is an art
form, and expert righty
of files,
Brrr]
LINUX SHELL HANDBOOK - 2022 EDITION
GCE UE CLS La
pride themselves on their ability to con-
struct elaborate and elegant globs.
But what if you want to work with a
metacharacter? Then you put a back-
slash (\) in front of it. For instance, \\ in
dicates that you are looking for a back:
slash, not a directory. The backslash is
known as an escape character, and it sig-
nals that the command should read what
follows literally, instead of as a glob.
Globs can be especially useful when
you want a selected list from a directory
full of files or when you are using one of
the grep commands to find content in-
side a file. However, you must be careful
about using globs with commands like
rm or me that change or rearrange the
content of your hard drive. Otherwise, a
‘command can have disastrous conse-
quences. To be safe, consider using a
newly constructed glob with the inocu:
fs fs command, so you can see what
files it might affect.
Learning that Pays
File management commands have a long
history in Bash, During the course of
their development, they have accumu-
lated options the way ships accumulate
bamnacles ~ constantly and apparently
haphazardly
However, often, the options are sim-
pler than they frst appear Fo example,
you can be fairly certain that most file
management commands will use-rto in
clude sub-directories and thelr contents
and-v to print a detailed description of
‘what they ae doing othe terminal
Similarly, to force a command to work
regartless of consequences, you gener
ally use Adding the option, how.
ever, means that every ation needs to
be confirmed by you before it happens.
Even with such hints, these commands
can take a long time to master,
In fact, for basic actions, they might
offer litte more than a graphical file
manager can. But, if you try to do some
{hing more intricate ~ such as specifying
how symbolic links are going to be
treated of excluding a file from an ar-
chive the file management tools easily
outclass their desktop equivalents. Ifyou
Team some of theless straightforward
options for these commands, you'll soon
understand why many experts prefer to
use the command line for fle manage:
rent over anything thatthe desktop has
woofer.
11ry
aT
Sarna.
Race Cuenca tits)
BUND eee CO
hen it comes to finding and
identifying files on your
system, you are spoiled for
choice. Linux offers a variety of tools
that can help you locate files and pro-
grams, including find, locate, whereis,
and which, These tools are not particu
larly difficult in use, and mastering them
can help you use your Linux system
more efficiently
Finding Files with find
The find tool lets you search for files by
name or a part of the name. By default,
find searches recursively, meaning it
looks for files through the entire direc-
tory tree. At the very minimum, find re-
quires two options: a path to the direc-
tory where the search should start and
the name of the file to look for. The
name of the file is specified with the
name switch, For example, the follow-
ing command will search for files whose
‘names start with Lin in the foo directory
and its subdirectories:
{As shown in this example, you can use
wildcards in the search string to broaden
the search. Because the find command
Is case sensitive, the previous command
line initiates a search for all file names
that start with Lin, but not those that
begin with lin, However, you ean in-
struct find to ignore case with the use
of the -iname switch
The find command lets you specify mul-
tiple starting directories, The following
command will search through the /usr,
12
‘/home, and /tmp directories to look for
all bin files
‘ind fase /bone /tmp -nane "nin
If you don’t have the appropriate per-
missions to search in the system direc-
tories, find will display error messages.
‘To avoid cluttering up the search re-
sults, you can send all error messages
to the nut file (Le., discard them):
‘ind /asr /oone /tmp 2
ane "48" 2>/de4/12
‘The find tool also supports the AND,
OR, and NOT Boolean operators, which
let you construct complex search strings.
For example, you can use the size pa
rameter to limit the search to fies that,
are larger than the specified limit
ind /ohotos 2
‘The command line above searches for NEF
files (Nikon raw files) that are larger than.
‘7MB. In similar manner, you can use the
1 (NOT) operator to find files that are larger
than 7MB but are not .NEF photos:
ind /aowmtoads -aize +701 2
‘The OR operator also can come in handy
when you need to find files that match
either of the specified criteria
‘ind /aowicads -size +74 2
Instead of searching for files by name,
you can use find to search for files by
LINUX SHELL HANDBOOK ~ 2022 EDITION
owner. For example, if you want to find
all files owned by root, you can use the
following command:
find . -user root
Ina similar manner, you can use find to
search for files owned by a specific group:
find. group wn
‘The type option is useful for specifying
the type of object to search for, such as
F (cegular file), d (directory), I (symbolic
link), and a few others. Do you want to
find the directory of photos from Berlin?
Here is the command for that
‘4nd verlin/ -type a
‘The find tool also offers several options
that can be used to find files by time,
including -mmén (last modified time
minutes), -amin (last accessed time in
minutes), time (last modified time in
hours), and ~atime (last accessed time
in hours). So, if you want to find photos
that were modified 10 minutes ago, you
ccan use the following command:
‘ina /photos nmin -10 -nane "*.1EF*
‘The -exec option is another rather useful
‘option that allows you to execute a com-
mand on every seatch. For example, the
following command searches for *.NEF
files in the photos directory and renames
the found file with the exiv2 tool:
ind /photos ~inane "*NER" 2
‘exec exive my 2
“= Marmara sane" 2
MEE OA:Search Tools GETTING AROUND
Note the {} \; at the end of the com-
‘mand. The {} symbol is a placeholder
for the name of the file that has been
found, whereas \; indicates the end of
the command. Instead of exee, you can
also use the -ok option, which asks you
for confirmation before the command is
executed.
Finally, you can use the -fprint option
{ind /none/aser -nane “Link 2
~fprint searen_neaults.tet
to print the search results toa text file.
Searching for Files with
locate and updatedb
Similar to find, the locate tool ets you
find files by their names But instead of
searching the system in real time, locate
searches the database of filenames,
‘which i updated daily. The key advan-
tage ofthis approach is speed; finding
files with locate is much faster than
with find. The use of locate is easy: Just
run the focate command with the name
of the file you want to find
locate backup. sh
‘To ignore the case, you can use the +
option:
rocate -4 paca
‘As with find, you can use wildcards in
your searches:
locate "*. joe"
If you want to see only a limited num-
ber of results, you can do so by using
the -n option followed by the number
of your choice:
oeate "*. jos" -n 6
‘As mentioned before, locate performs
searches by querying the database of
file names, which is automatically up-
dated every day, so if you have just
downloaded a batch of photos from
your camera, the locate command
‘won't see them until the database is
updated
Portunately, you don't have to wait
until the system updates the database;
‘with the updatedb command, you can
‘manually update the database at any
time. Just execute the updatedb com-
‘mand as root to force the system to up:
date the database.
whereis and which
I you need to find the path to an execut-
able program, its sources, and man
pages, the wherets tool can help. The fol-
lowing command, for example, returns
paths to binary, source, and man pages
for the Rawstudio application:
sreress roustudio
Using the available options, you can
limit your search to specific types. To
search only binaries, you can use the -b
option, oF use-m to search for man
pages and -s to search for source files.
‘Whereas the wheres tool lets you lo
cate program files and man pages, which
tells you which version of a command
‘will run Ifyou just type its name in the
terminal. For example, the which soffce
command returns the /ust/bin/soffice
path. This means that the soffice con
‘mand runs the application inthe /usr/bin
directory. If you want to find all the lo:
cations of the command, you can use
the -a option:
inion -a aoftice
‘With just these few, simple commands, you
can locate your files quickly and easily.
grep
‘The Bash command shell also has tools
that will let you search for a text string.
inside of a file. The most popular com:
‘mand for finding a search string is grep.
In its most basic form, grep searches a
file for text matching a specified pattern
and outputs every line of the file that
contains the string.
‘The syntax for the grep command is:
rep (options) pattern £126 name(e)
You can specify the search pattern ex
plicitly or use a regular expression. (See
the article elsewhere in this issue on reg
ular expressions.)
Several options help to refine the
search (see Table 1 for some exam-
ples). For example, if you don’t want
to output all the lines that match the
search string but only want to know
the number of matching lines, use the
output file redirects stdout, sending
the results of a command or a pipe
(but not the errors} to a named file. If
Mra eed
OL $ # Finst exanpl
02 § grep “1 “E ""Groueno® mary.txt |
(3 $ cat groucho.txt
4 Mate wet they call « eansty clause
8 $ # Second exanple
(8 1 started work on Mov 1 at 8.18 an
fant 99 tineoand txt
13 $ cat tineoard.txt
18 T Fintahed york on Nov 2 et & pa.
439 $ roby myapp.10 ¢ date >4 10g
LINUX SHELL HANDBOOK - 2022 EDITION
“5@
7
the file does not exist, itis created; if
the file exist, its contents are over:
written with the results,
>> output files similar to > but ap-
pends stdout to the named file. If the fle
does not exis, itis created however, if
the file exists, its contents are preserved
and amended with the results
>& output_file works like >, but it
‘captures stdout and stderr in the spec-
ified file, creating the file if necessary,
and overwriting the contents if it pre
viously existed
AA few examples are shown in Listing 2
In Listing 2, the first command
should look familiar. The addition of
> groucho.txt saves the output of the
command-line to the file groucho. tx.
The second command appends the
string I started work on Nov 2 at 9am. 10
the file imecard.tet. The third command
runs the Ruby script myapp.rb. Input is
taken from the file named data and the
stdout and stderr are captured in log
Advanced Use of Pipes
Consider the following command-line
combination:
§ fina /petn/to/sttee 2
“type € | xargs grep -H-1 2
“4 -n ateing
This command enumerates all plain
files in the named path, searches each
fone for occurrences of the given string,
and generates a list of files that contain
the string, including the line number
and the specific text that matched. The
find clause searches the entire hierar
chy rooted at /path/to/files, looking for
plain files (type f). Its output is thelist
of plain files.
The xargs clause is special: xargs
launches a command - here, grep plus ev
erything tothe end of the line - once for
each file listed by find. The options -H
and -n preface each match withthe fle
name and line number of each match,
17GETTING AROUND Pipes and Redirection
respectively. The option - ignores case.
(capital }) skips binary files.
‘Assuming thatthe directory /path/to/sre
contains files a,b, and c, using find in
combination with xargs i the equivalent of
4 find /pstn/to/are
ep “HI -i-n string a
4 grep “Hr i -n string »
$ grep “HT -i -n string e
In fact, searching a collection of files
so common that grep has its own option
to recurse a file system hierarchy. Use «d
recurse or its synonyms -R or -r. Forex:
ample, the command
rep “HI -i on oR string /oath/to/sre
works as well asthe combination of find
and xargs. However, if you need to be selec:
tive and pick specific kinds of files, use fin.
Bit Bucket
{As you've seen, most commands emit
‘output of one kind or another. Most com-
‘mand-line commands use stdout and
stderr to show progress and error mes-
sages, in that order. If you want to ignore
[ieee es
ois
2 f eat secret. tt
Of & cat secret-txt > /dev/aut
(08 £ cat socratea. txt > /oew/n01
8 & cat socentes.tat > /aey/aull
09 & ono Done,
[Rees aad
01 f eat secrete
(2 Anlein Skyaior 4 Darth Vader.
03 $ ep /dor/mali secret txt
8 § eat sooner txt
(05 # echo “the moon is nade of
09 & eat /aev/nait > secret txt
10 § eat secret. txt
12 § op /dor/mali newsooret. xt
33 § cat neweccret. te
15 $ echo Done,
that sort of output - which is useful, be-
cause it often interferes with working at
the command line ~ redirect your output
to the “bit bucket,” /dev/null. Bits check.
in, but they don't check out
Listing 3 shows a simple example. If
you redirect the standard output of cat
to /dev/nult, nothing is displayed. (All
the bits are thrown into the virtual ver-
tical file.) However, if you make a mis-
take, error messages, which are emitted
to standard error, are displayed. If you
want to ignore all output, use the >&
operator to send stdout and stderr to
the bit bucket.
You can also use /dev/null as a zero-
length file to empty existing files or create
new, empty files (Listing 4),
Other Tricks
Im addition to redirection, the shell offers
many other tricks to save time and effort
‘The “back tick” or “back quote” op:
erator ("... ) expands commands in
place. A phrase between back ticks
runs first, while the shell interprets the
command-line, and its output replaces
the original phrase. You can use back
ticks to yield, for example, a file name
or a date:
pe > tate, ante ‘se
5 as stator
1s842 ttysooL 0:00.84 -bash
s0so0 trysoot 1:57.15 2
ruby ./seript/server
r9eu2 ttys001 0:00.84 -ash
0400 ttysool 1:57.15 2
ruby ./seript/server
‘The first command-line captures the
list of running processes in a file
named something like state.
YYYY.MM-DD, where the date portion
of the name is generated by the com-
mand date "+ %6F". The single quotes
around the argument prevent the shell
from interpreting + and 9%. The last
command shows another example of
the back tick. The evaluation of
state.* yields a file name.
‘Speaking of capturing results, if you
want to capture the output of a series of
commands, you can combine them
within races ({... })
LINUX SHELL HANDBOOK ~ 2022 EDITION
§ (pai w) > state. ate KE"
In the preceding command, ps runs, fol
lowed by w (which shows who is using
the machine), and the collected output is
captured in afi
You can also embed a sequence of
commands in parentheses to achieve
the same result, with one important
difference: The series of commands
collected in parentheses runs in a sub-
shell and does not affect the state of
the current shel. For example, you
right expect the command { ed
SHOME; ls-1 }; pwd to produce the
same output a8 (ed SHOME; Is): pwd.
Note, however, that the commands in
braces change the working directory of
the current shell. The latter technique
is inert
‘The decision to use a combination or
1 subshell depends on your intentions,
although the subsbell is a much more
powerful tool. You can use a subshell
to expand a command in place, just as
‘you can with back ticks. Better yet, a
subshell can contain another subshell,
0 expansions can be nested. The two
commands
w} > state.4(aate "KE")
w) > state, date ok
are identical. The notation $( ) runs
the commands within the parentheses
and then replaces itself with the out-
ut. In other words, $( ) expands in
place, just like back ticks; however,
unlike back ticks, $( ) can be very
‘complex and can even include other $( )
expansions:
§ (ca (arep strike /ete/passna | 2
cout £6 -€:"); Lede
‘This command searches the system
password file to find an entry for user
strike, clips the home directory field
(field six, if you count from zero),
changes to that directory, and lists its
contents. The output
rep /ete/pasawa ateixe | cut -£6 2
is expanded in place before any other
‘operation. Because the subshell has
sO many uses, you might prefer to use
it instead of the { } or the back tick
operators.Customizing the Bash Shell GETTING AROUND
Customizing the command:
ine with Bash
BESPOKE
SHELL
Make the Bash shell your own by customizing the shell
environment with variables and aliases. You may end up
with a more efficient Bash shell. BY BRUCE BYFIELD
achis the dealt command shell
inal, Ws petty fine
somal Howeve you ay want toast
itmore to your igo or get ef
Gieny, Whaterer your reason, Bas
tr pen of opporunles for asom
iat, Many eustonizaon ae stored
ina nd of es, alnough these a
2 ew are managed by emia apie
ton. Alona, wer ean always
wit set for pei sks
Essel, Bash sa colton of nv
cone vrles a sometine
fanetons) Afi gnc, ht might
stems feria stenentioa non
protamine However al hat means
that ash nde a goup of stings hat
defines what your command line looks
like and what it can do. Some variables
are added during installation to oversee
general system functionality. Other var
ables are added as you install applica:
tions such as desktop environments.
Table 1 shows some of the common en
vironment variables. Environment vari-
ables can be set temporarily from the com
‘mand line or loaded as commands along-
side snippets of code in Bash configuration
files that run when Bash opens (Table 2,
Before going further, you should check out
each command's man page to learn more
about each one's purpose. Note that vari-
ables are printed in uppercase letters only
‘When used in a command, they are pref
ced with a dollar sign ($).
Environment variables can be stored
in several places. The most common file
for variables is ~ /.bashre. However,
your home directory may also include
profile or .baslprofile, a standard set of
variables that sets the paths and deter-
mines whether .bashre can be run. Your
hhome directory may also contain ,bash_
login and bask_login. These dot files ~
so called because each file name starts
with a period - are not ordinarily visible
when viewing directory contents. In:
stead, the ls command must specify the
«a option to make them visible. However,
even then, you may not see most of
them, because the modern trend is not
to install any of them by default, espe-
cially on standalone machines. When
one is used, itis generally .bashare (Fig.
ure 1). Many distributions heavily com-
‘ment the files to make them mote useful.
Im addition, /ete/profile.bashre and /ete/
‘sty. bashue are global files - templates
sed when setting up new users. They are
used primarily for seting up multiple com.
puters or networks, so home users may
never have seen them. As you might guess
from the fle names, both have similar con-
tents tothe correspondingly named files in
home directory. Should both global and
home directory versions exis, those in
home directories override the files in fete
Read on for more details about specific
variables.
PCA cee Setting the Editor
COLUMNS ‘The width of the terminal display in characters (usually 80) If you do not define EDITOR, applications
DESKTOP_SESSION The default desktop environment iat nese ce soe et to use, ens Hi
DISPLAY Te display used by X usually stto;00 which thet c=] er You nay oer Eas one ore
hay ont current compsten ‘Working from the command tine, you
eDrToR ‘Your dfauttext editor
HISTCONTROL ‘Settings to control the history file ice oa cate nang
cal editor o start p= and in some cases,
HISTFILESIZE The maximum lines inthe history fle
MISTSZE The maximum number of entries inthe history fle Ea
HOSTNAME The computers hostname Ea ee
HOME Yourhome directory ‘env Customizasthe environmentin
LANG Your current language which a command uns. By i
MAIL The location of your mail spool (usually var/spoolimail/USER} anil, t enammecsniiion
MANPATH The lst of directories to search for man pages a ass ete eee
Pst “The default promptin Bash thecommand line or perma
Pao The defaut current working dreciony rently in one of te files n
‘SHELL The path to the current command shell (e.g. bin/bash) ee tioranra imate!
TERM The curent terminal type The unset command removes
1 Your time zone variables.
USER Your current username export Like set except itaete the
variable for the entire login
"Note:The default variables depend on your distribution, environment
LINUX SHELL HANDBOOK - 2022 EDITION
19GETTING AROUND Customizing the Bash Shell
Figure t: The beginning ofa Debian .bashre fle.
you may not be using Bash from a desk
top. Be sure to define your editor and
know how to use it before you need it
(especially how to close the editor)
Setting the Path
By defining PATH, you make any com-
‘mands on the path accessible anywhere
Figure 2: Finding items in the Bash history is easler i you modify
the history to include the date an time.
‘on your system, Should you try to use a
command not on the path, you will re-
ceive a “command not found” message.
To use a command off the path, you have
to change to the command's directory or
else type out the full path, either of which
isa nuisance if you use the command
regularly.
The default
paths are the most
common directo-
ries for storing exe
cutable files. You
can view the cur-
rently defined
paths with ecko
SPATH. Typically,
the paths are /usr/
Table 3: Building Blocks for Command Prompts
id Displays today’s date in weekdaylImonthiday]
G Current time in 24-hour HH:MMSS format
ta Current time in 12-hour HH:MMSS format
“ 2ichour clock in HH:MM format (no seconds)
W Fullhosiname
v [Number of jobs being managed by the shell
© The name ofthe shell
w Current usemame
w Bash version
Ww Extra information about the Bash version
Current working directory (SHOME's represented by -)
The basename ofthe working directory (SHOME|s represented by
v ‘This commanat’s number in the history
ve ‘This command's command number
s Specifios whether the users roat (fj or otherwise (8)
u Backslash
v Start a sequence of non-displayed characters
v Close or end a sequence of building blocks
local, /usr/bin, in, /usrlocal/games,
and /usr/games. To add a directory tothe
path called »./sandbox/bir, you would
first define tas a path and then add it to
‘the general list of paths:
ariesPamt"
‘export PATH
snaox/oin
‘To remove a path from the path state-
ment, replace the existing statement in
bashye using the command:
‘export Pati (path): (path [patho]
Setting the History
Bash’s history is alist of previously en
tered commands. Instead of retyping,
you can use the history, either with the
history command or the arrow keys, 0
select a command, lems inthe history
ae stored in bash history, but control
‘of how the history command operates i
defined in base.
‘Most distributions use the HISTSIZE
variable to change the number of com
mands inthe Bash history. Afterall, fa
command is used more than once, no
convenience is gained by listing it more
than once. Another common history va
able is HISTFILESIZE, whichis a misno
me, since what it defines is the number
oflins. The defaults 1,000 lines, but i
you work regularly at the command lin,
you may want to increase that number.
The less common HISTTIMEFORMAT,
inthe form
export HISTTINEFORNAT:
on
adds a date and timestamp to the history,
making items easier to find (Figure 2).
Ifyou add
PROUPT_COBUND- "history -a!
‘then all commands are entered in the his-
tory immediately after being run, instead
of atthe end of the Bash session, which is
the default. Immediately saving com
mands is especially useful if the same
cory
fee ee
Normal
Bold
Dim
Underlined
20
LINUX SHELL HANDBOOK ~ 2022 EDITIONGeneral | Tabs | Appearance Serling
Color Scheme & Background
poze
oro
WE coo
EEE coon
——
[razze7 |
eee
oe
Preview Oxygen Hono)
Texts: 18.0
2 Smooth fonts
2 Draw intense color
‘te terminal application.
user has several tabs opened ~ otherwise,
‘only the first tab's history is saved.
‘Another useful variable is HISTCON:
TROL, which takes four definitions. If
HISTCONTROL is completed with ignore
space, it deletes history listings that
begin with a space; ignoredups deletes
duplicate commands, while ignorebotlt
deletes both those that begin with a
space and duplicates
Yet another variable, HISTIGNORE
takes a list of commands not to be added
to history, Outside of export and .bashre,
you can also run history -cw to com-
pletely delete the current history.
Customizing the Prompt
‘The command prompt marks the latest
position in the shell from which an entry
‘ean be made, The default prompt on
most systems usually has the format of
USER@HOST or something similar and
{s set with the PSI variable. A sub-
prompt is sometimes set with PS2 as
well, usually >. Typically the prompt
for an ordinary account ends in $, while
the prompt forthe root user ends in #
‘Both PSI and PS2 can include any text
you want. You can also use the building
blocks shown in Table 3, separating each
with a backslash, Why would you want to
do this? There are many reasons. If you
usually have Bash open, then you can
save space by not having a desktop clock.
Ie you frequently refer tothe Bash history,
then a prompt that refers to a command's
history number might be convenient. Ex:
perts might lke a command inthe prompt
Description: New olorScheme
Background
Color
Blur background
Seledl Back ound image:
J TEN ~ vv) cont
Figure 3: You can quickly change the look of Bash using profiles in
torun when Bash
‘opens, but to be
hidden, or to store
administrative in-
formation at the
prompt where itis
always easly seen,
For instance, the
default Debian
‘prompt conceals a
‘prompt for a chroot
jall that does not
‘ordinarily display.
‘The more you
lear about Bash,
the more reasons
for customizing the
prompt willbe:
come obvious,
‘The prompr’s
color can also be
customized. Use \e to mark the start of the
color definition and \efOm to mark the
tend, Numbers define the promps font
‘weight (Table 4) and color (Table 5). So
the following line in bashie
(o:20n)\e S\e(om"
displays the username and dollar sign ina
normal green font. Ifyou use a bold weight,
you get lighter version ofthe color
Cosmetics
Besides using number codes to color the
‘command prompt, you can set the color
in your terminal with tput (Table 6)
However, tput seems to have fallen into
disuse. In this desktop era, Bash's appear
ance is usually set not in Bash, but in the
terminal application through the use of
profiles that set both the appearance and
the behavior ofthe terminal (Figure 3)
Profiles offer far more customization
choices than sput or prompt codes, and
they are far easier to set as well
Aliases
‘An alias is an alternative name for a
command. You might create an alias for
a common misspelling (e.g, typing s! for
1s), a8 an alternative to adding to a path,
as a way of making a command name
easier to remember, orto save typing a
long command. Many distributions in-
stall with the alias fs for is ~color = auto,
which colors different types of files, pre
sumably on the assumption that no one
wants the plain s command. Typing,
LINUX SHELL HANDBOOK - 2022 EDITION
Customizing the Bash Shell GETTING AROUND
alias lists the aliases currently on your
system. Usually, aliases are stored in
‘bash, but they can also be stored in
‘bash_aliases, which is slightly more
convenient to find. Typing alias lists the
aliases currently on your system.
Up Next: Bash Scripting
‘When you have implemented the builtin
customizations that you want inthe Bash
shel, you may want to expore Bash serit-
ing. Bash sriptng i done ina simple lan
guage, and sometimes is no more than a
collection of commands entered one per
line. A sript hasan sh extension and is
run withthe sh command, Learning Bash
scripting is beyond the scope ofthis artic,
but you can gta stat by loking up scripts
online and modifying them for your pur-
poses (sometimes tis inches changing
the scripts permissions). Before long, you
ray havea Bash sel far beyond the de-
fault provided during instalation.
ark
30 Black
2 Green
3 Brown
u Blue
5 Purple
6 yan
7 Ushtarey
Table
Penne tn ue
Poe
a ke
{putsetb [1-7] Set a background color
tputsetl|1-7] Seta foreground color
a
Ioutbold —_ Setbold mode
tputdim Tun anhalt
‘putsmul Begin undorine mode
‘butrmul Ex undetine mode
tputrev Tum onreverse mode
tputsgrd Tur off al atibites
|, |
0 Black
1 Red
2 Green
3 Yellow
4 ive
5 Magenta
6 Cyan
7 White
21Enjoy a crash course on some of the text-processing and -filtering
capabilities found in Linux. BY HAL POMERANZ
nix-like operating systems have
historically been very much
about text processing. Really,
the Unix design religion is: Make simple
tools whose output can be manipulated
by others with the use of pipes and
other forms of output redirection. In
this article, I'l ook at the wealth of
Linux command-line tools for combin-
ing, selecting, extracting, and otherwise
‘manipulating text.
we
‘The we (word count) command isa sim-
ple filter that you can use to count the
‘number of lines, characters (bytes), and,
yes, even the number of words ina file.
‘Whereas counting lines and bytes tends
tobe useful, I rarely find myself using we
to count words.
‘You can count lines ina file with wel:
Ifyou don’t specify a file name, we will
also read the standard input, To exploit
22
this feature, use the following useful
idiom for counting the number of files in
a directory
fae xe
198
‘To count the number of bytes ina file,
$ wo -¢ kern. 10g
106982 kern. 10g
On a single file, we -cisn’t necessarily
that interesting because you could see
the same information in the output of ls
-l. However, if you combine we with the
find command, you get byte counts for
all files in an entire directory tree:
§ find /var/tog type £2
oreo ve -© 1) \i
79666 /var/1og/kern.108.6.62
8781 /var/log/Apks- 108.4.
106982 /var/Log/kern. 10g
LINUX SHELL HANDBOOK ~ 2022 EDITION
‘After I examine a few more shell tricks
in the sections that follow, I'll return to
this example.
head and tail
‘Another pair of simple text-processing
filters are head and tail, which extract,
the first 10 or the last 10 lines from their
input, respectively. Also, you can specify
2 larger or smaller number of lines. For
‘example, to obtain the name of the most
recently modified file in a directory, use:
5 18 | hone
xern.10g
‘Then if you wanted to see the last few
lines ofthat file, use:
tail -2 kern.t0g
Nov 21 09:00:29 elk Kemet: 2
(12698, 090352} [UEW BLOCK INPUT]: 2
Now 22 09:00:22 elk Kernel: 2
[12608.ce06s5} [UW BLOCK INPUT]: 2
[papa2. 39890
n0 OUT=
[ew stock 1npur}: 2
Here's a trick for extracting a particular
line from a file by piping head into tail:bead -19 /eto/pasowd | tail -1
(Fexefots fein
In this case, am extracting the 13th line
of /ete/passwd, but you could easily se-
lect any line just by changing the nu-
‘meric argument that is passed in to the
head command.
Another useful feature ofthe tail com-
mand is the-f option, which displays the
last 10 lines ofthe file as usual, but then
keeps the file open and displays any new
lines that are appended onto the end of
the file. This technique is particularly
useful for keeping an eye on logfiles ~
for example, tail -f ker log.
cut and awk
head and tail are useful for selecting par
ticular sets of lines from your input, but
sometimes you want to extract particular
fields from each input line. The cut com:
‘mand is useful when your input has reg-
ular delimiters, such as the colons in
/ete/passwd:
§ cat a: -£1,8 /eto/oasea
root: /root
‘anenon:/asr/sbin
bin:/oin
‘The -d option specifies the delimiter
used to separate the fields on each line,
and -fallows you to specify which fields
you want to extract. In this case, 'm
pulling out the usernames and the home
directory for each user. cut also lets you
pull out specific sequences of characters
by using -c instead of . Here’s an exam-
ple that filters the output of ls so that
you see just the permissions flags and
the file name:
$s 7 | cnt -c2-10,52-
ere-ar-x cep
eer--r-- adduaer.cont
sajeine
Darn! The output contains the header
line from ls -l. Happily, tail will help
with this
$ te | tait -n 2 | out -c2-10,52-
ore-ar-« sept
eer--r-+ aduaer, cont
aajtine
‘That looks better! Notice the syntax with
{ai here. The -n option is the alternative
(POSIK-Iy correct) way of specifying the
‘number of lines tail should output. So,
(ail -10 and tail-n 10 are equivalent. If
you prefix the number of lines with +,
as in the example above, it means start
with the specified line, So, here I'm tell
ing tail to display all lines from the sec-
fond line onward. The + syntax only
works after-n.
cut is wonderful for lots of tasks, but
the output of many commands is sepa-
rated by white space and often irregular.
‘The awk command is best for dealing
with this kind of input
400 -ef | av 2
M(print $2 "\t" 42 *\e" 42)"
uD op
reat 1 /abin/init
root 2 [etnresaa)
root 3 migration/o]
awk automatically breaks up each input
Tine on white space and assigns each
field to variables named $1, $2, and so
con. awk is a fully functional scripting
language with many different eapabil-
ties, but at its simplest, you can just use
the print command to output particular
Input fields as I'm doing here,
awk also allows you to select specific
lines from your input with the use of
pattern matching or other conditional
‘operators, which saves you from first
hhaving to filter your input with grep or
some other tool. For example, suppose I
wanted the filtered ps output above, but
only for my own processes:
pe “ef | ani (/*ha / 2
{print 41 "\e* 42 *\e" 45)"
mms 2
/use/bin/gnome-keyring-Aaenon
pal 7460 x-seseion-nanager
hal 7566 2
‘ose /bin/dbus-Lonnch
Here, use the pattern match operator
(V..)10 produce output only for lines
that start with al . The com-
mand ps-ef | awk ‘($1 ~~ "hal") .."
would accomplish the same thing.
LINUX SHELL HANDBOOK - 2022 EDITION
Text Manipulation Tools GETTING AROUND
You can use the -F option with awk to
specify a delimiter other than white
space. This lets you use awk in places
‘where you might normally use cut, but
where you want to use awk’s conditional
‘operators to match specific input lines,
‘Suppose you want to output user-
names and home directories as in the
first cut example, but only for users with
directories under /home:
§ ee “FE "(66 ~ /*\nome\//) 2
( print $2.7: $6)" /ete/easena
subayon:/none/sabayon
‘na: nome fat
Aura: /pone/laura
Rather than matching against the entire
line, the command here uses the ~ op-
erator pattern match against a specific
field only,
sort
Sorting your output is often useful:
# ae “Fs “(66 ~ /*\lnome\//) 2
(prime #20" 46) 2
Jetefoassed | sort
hal: tone hal
aura: /bone/laura
sabayon:/hone/sabayon
By default, sort simply sorts alphabet
cally from the beginning of each line of
Input, Sometimes numeric sorting is
what you want, and sometimes you
‘want to sort on a specific field in each
Input ine. Here's a classic example that
shows how to sort your password file by
the user ID field (useful for spotting du-
plicate UIDs and when somebody has
added illicit UID 0 accounts):
4 sort on -t: “ks /ete/pasewa
root 4: 0:0:neet:/zoot: bin/bash
daemon: x:1:1 daemon: /use/abin: /osn/
binsx:2:2cbin:/oin:/oin/an
‘The -1 option indicates a numeric sort, -t
specifies the field delimiter (such as cut
dor awk -F), and ~k specifies the field(s)
to sort on (clearly they were running out
of option letters)
Also, you can reverse the sort order
with -rto get descending sorts
§ 1s fere/zea.a | sort x
So9atop-reedanend
23RTA Cg Ld
Sesmmmologin
Remember the find command that l used
we with to get byte counts forall files
under a given directory? Well, you can
sort that output and then filter with head
to get a count of the 10 langest files
under your chosen directory:
4 tind /var/1og -type £ -exee 2
ve =e {) \5 | sort nr | head
4962018 /ver/1og/metnib
24748291 /var/104/systog
2708201 /var/Log/mail. log
‘24708201 /var/10g/maiinto
0242782 /var/log/ConsoleKit/aistory
902904 /var/10g/sysiog.0
‘a7aaeia /var/iog/matt 208.0
782682 /var/og/mail.info.0
1099048 /var/2og/umare/hostd-7. 10g
01991 /var/log/inavatter/eartnan
unig
When you're extracting les with cut
and ai, you sometimes want ooxtpt
just the unique values. There’ a unig
primitive fortis, but ung only sup
presses dupliate lines that follow one
right after the other. Therefore, you must
‘spcally sor the oupat before handing
off For example, to get ast of al users
with processes running on the curent
system, use the following command
4 pp -2f | awk *{print 41)" 2
| sort | unig.
apache
dovecot
sort | unig is such a common idiom that
the sort command has a-u flag that does
the same thing, Thus, you could rewrite
the above example as,
ps ef | ane ‘(print #2)° | sort -a
‘The unig program has lots of useful op-
tions. For example, unig -c counts the
total number of lines merged, and you
could use this to report the number of
processes running as each user, as in the
following command:
4 pe -ef | au "(print 41)" 2
| sort | unig <<
24
4 apache
8 dovecot
‘And with the use of another sort com-
‘mand, you could sort that output by the
‘number of processes;
5 pe -0f | awe "fprine $1)" 2
I sort | unig -c | sort -nr
8 apache
Another useful trek is unig, which
only shows lines that ae repeated (4u-
plicated) and doesn’t show unique lines.
For example, if you want to detect dupli-
cate UIDs in your password fle, enter:
# cut -a: -£9 /ete/pesewa 2
[sort
“Ka wost-populoas) <(sort eities) | 2
ut =a, -f2,3,8 | sort -nr -t, -k2
nina, 1220044848, Bet sing
India, 1147296900, ow Dott
United states, 305824640, ashington D.C.
Examples like this are where you really
start to get a sense of just how powerful
the text-processing capabilities ofthe op:
crating system are,
split
Joining files together i all well and
00d, bt sometimes you want to split
them up. For example, might split my
password-cracking dictionary into
smaller chunks so that I can farm out the
processing across multiple systems:
# split -a-1 1000 dictionary 2
dictionary.
peri
eases asetionary
1000 dictionary.0o
1000 dictionary.o1
2000 asetionsey 02
Here, 'm spitting the file called diction:
ary into 1000-line chunks (1 1000, is actu
ally the default) and assigning dictionary
as the base name of the resulting files,
‘Then, I want spit to use numetic suffixes
(a) rather than leters, and Tuse we 10
count the number of lines in each file and
confirm that I got what I wanted
‘Note that you can also specify a dash
(, meaning standard input, instead of
a file name. This approach can be use-
ful when you want to split the output of
2 very verbose command into manage
able chunks (e., tepdump | split -1
100000 - packet-info)
tr
‘The tr command allows you to transform
‘one set of characters into another. The
classic example is mapping uppercase
letters to lowercase. For this example, to
transform the capitals file I used previ
ously, I'll use:
$ tr At ace ¢ capitals
>
But this isa rather silly example. A more
useful task for tris this little hack for
looking at data under /proc:
404 /orec/selt
§ eat environ
(cious_ ERIN SOCKET /tmp/2
xkeyring-1F20ts/socketLOcuaus?
shalODMSESSTONede F901
4 tr \\o00 \\n Don't run test
‘enable /prve/ays/va/ 2
Oy, to change it temporarily, enter:
sysctl -w vn.diety_ 2
Pe Cue aie is eee
4.9.0-8-amd64 SMP mod_unload modversions
Figure 2: modinfo lists the options for a module.
LINUX SHELL HANDBOOK - 2022 EDITION
27CONFIGURATION Hardware Configuration
uthent icAMD
io FX(tm)
Borrtr)
cr
0xs00084t
TT
Ea
0
Stetr A
Boer)
Earn
aatet)
apicid
or
fpu
ure
rae ene eee
Pecueeny d
elayed_all
eae ins
tion_bloc
rr_ratelimit_burst
meus tare
Scere e
ce
Gee earerY Peet mre es
Figure 4: The subdirectory n
The sysct utility is designed specifically
to work with /proe and /sys
Working with Traditional
Configuration Files
Although systemd is today the norm for
launching services at boot time, there
are stil services, traditionally called
“daemons,” that are shell scripts. Dist
butions use shell-like configuration files
to configure these services easily, with
out having to invent a new syntax for
each configuration, You can usually re:
ognize these configuration files because
they have:
Cry
reenerat
rerreg ss
sole
faery
cron
Prey
Cans
Prseriny
retry
Hoe erro
Heserechat
ecernrny
cr
Err st ins
meee
Pons aes
vere eri
peepee
Cae aCe)
was
Sse
[er ataciae suc cy
cetcisC mat ars
Case Ta ey
Cacia a Tera crs
ae ome
mae)
cee me)
iieesered
or
Shell variables (writen in capital let
ters and with no spaces), lke BLUE:
TOOTH_ENABLED = in /ete/default/
bluetooth
* Comments explaining what each vari
able means
+ Shell functions (sometimes) to extend
‘or override features in existing scripts
In Debian-based systems, most ofthese
contig scrips are placed in /ete/defaul/*
and can be edited in a text editor as root
(igure 5).
Ifyou make changes to any system shell
script or write your own system scripts,
please keep thefllowing facts in mind
steer)
PCC)
cry
rs:
eso
ieee)
i
intel-mi
erent
Ponrrie)
etup
orn
opt p
msg_
rese
caer ia
Cmca Crten Tats
near
95 in /sys give detalled information. Her, the characteristics ofan ext4 drive are displayed
Crore
creer)
over
Peag str)
co
oro
RCS eS
re rmC meres
PCat Cm TTL)
legacy svm extapic cr8_legacy
stream_req
retreat:
eeu reat Tia Tiel)
d_clusters
_write_kbytes
Paagg
Perce ean earls
* IF these scripts run as root, they have
the potential to destroy your system if
‘you add the wrong command or acc
dentally activate a command that is
supposed to be commented out, To
prevent accidents, always backup a
configuration file before editing it
Scripts are usually called with an “in-
clude” to another script by the dot (.)
shell command, and the calling script
‘will terminate if an exit appears.
In the shell, no spaces are allowed be
fore and after the equal sign (=) when
setting variables. KDE and Gnome con
fig files frequently have spaces every
fae PCr}
ire)
sted
caret
timidity
te
ri
Peery
virtualbox
LINUX SHELL HANDBOOK ~ 2022 EDITIONHardware Configuration CONFIGURATION
‘where to make them easier to read, but
in the shell, a space means separation
of a command and its parameters,
‘which can cause a syntax error. Values
‘oF options containing spaces should
hhave quotes around them.
temd;system. To
be used, a new
override must be
activated with
systemetl dae:
‘mon-reload. Run:
ning the com
mand systemd-
delta shows all
the overrides cur
rently running on
the system. An
Cen rae
Hiren)
Peele laa bed
Pet adeta ys
Default TimerAccuracySec
Using systemd
systemd began asa replacement forint
for starting daemons and soon morphed
into a general eystem manager. Contig
ration files ae stored within /et/s
cra)
PeeeceiC ees est htt ens
PT emesiei ris aces Lees
Peemeastr thst testes ry
PSEe eu ihstay et tee7 ey
eno et em De faultRestartSec-100ms
nine basic files in /ete/systemd, most of (EXTENDED] Muses irises eurss tier lets
‘which have self-explanatory names, in- shows the loca- (se TNecyse tea pha (Uses)
cluding ones for login, the logfile, and tion of the over- | Usue NS UNE SSN
the network. Systemd configuration _—_ride fle, whereas jaye
files typically begin with a series of one marked CESS aed
fields ina section labeled (Marager] [OVERRIDDEN] __Fiqure6:systemd configuration fies start wth a (M
that can be edited freely. The mast im-
portant of these files is systera.conf
(Figure 6). All the files are detailed in
systemnd-user.conf(S) in the man pages.
For editing individual system re
sources, systemd uses the systemct! uti
ity systemetl works with units, or system
resources configuration files, usually as
a three-part structure:
aystenct1 (oub-conmand) [unit]
For example the major sub-commands
for system services are status, enable,
or disable,
Each unit has its own configuration
file, However, rather than being edited
directly like traditional configuration
files, unit configuration files can be pro-
vided an override file ora full replace-
ment file by using the systemet! com-
mand, Overrides ate stored in /ete/sys
root
Irae
EXTENDED] /Lib/
Gauci)
(cory
/Lib/systemd/
rane ty
Gates
(Cotes ee
PENeae Crome nee Tie TS Cet ery
Lines 1-9/9 (END)
CER ec asiac ta)
eee
shows the differ-
ence between the
original and the currently used replace-
‘ment unit file (Figure 7).
Although controversial when fist in
troduced, systemd is a far more orderly
approach than the other methods of con-
figuring or finding information, How-
ever, it does introduce numerous new
concepts that can be overwhelming at
first. As with any other methods, be sure
you know what you are doing with sys-
temnd before you actually edit one ofits
files. See the article on systemd else
‘where in this issue.
Consistency Is Key
“These sources of information and ways
to edit are alot to absorb, Unsurpris
ingly, functions are often duplicated
between different sources. if you
change the configuration, usually you
arse ery
Scere ys)
ete
ver Eves
fstresnis
~inputattach@
corr
Figure 7: systemd has the option of overrides that take precedence over the original fle without overwriting It.
taining editable lds.
eeu
eee ee eet YES
should use the same approach consis
tently, so you can keep track ofall the
changes made more easily. In many
modern systems, the most straightfor-
ward approach is to use systemd. How-
ever, experienced users often prefer to
edit configuration file, a practice that
is as old as Linux itself - if not older.
Most of the time, what matters is not
the method so much as consistency.
Whatever your approach, a wealth of
information is available. In fact, there is
probably more information than alex
cept a small minority of users can com:
prehend or use, but Linux is built on the
assumption that users want to tinker ~
and the beginning of tinkering is infor-
mation and options. With the tools listed
here, users have an embarrassment of
riches to use and to learn from,
erat eR UES Tags
CSP ELE S
stemd,
DAREN at
EN Eee
LINUX SHELL HANDBOOK - 2022 EDITION
29Device partitions and volumes
DISK MAGIC
‘We show how to prepare a hard disk for the filesystem.
BY NATHAN WILLIS, HANS-PETER MERKEL, AND BRUCE BYFIELD
hard ikon modem copseria
Desh iiieretion 4
eer he data str ta sores
fle and det), n Uns, emap mace
isu implemented a flrysem of
iow, resign pon Al
Mal may ses rete separate pat
tons forthe ota, an home ie
tories. In theory, although Linux can be in
stalled on one partition, many Linux sys
tems use multiple partitions
Before you can install an operating sys-
tem, you need to create partitions and for-
‘mat them with filesystems. Most Linux in
stallers provide a CUI for creating and
‘managing partitions during the installa-
tion process, but if your system is already
installed, you can tum to several manage-
‘ment utlties for configuring partitions
The Bash command line provides several
utlities for creating and configuring part:
tions, including fdisk, gdisk, and parted.
These tools are all generally safe, but
accidents such as power interruptions can
hhappen, so be extremely careful. Before
beginning, back up your data. Then boot
from a Live disk so all your hard drive
partitions are unmounted before you edit
them, Most of all, check all your actions
‘owice before beginning them,
MBR to GPT Switch
For many years, information on the part-
tion structure was stored in a small sector
at the beginning ofthe disk known as the
Master Boot Record (MBR).
The old MBR served the hard disk in-
dustry wel, but the industry outgrew it.
MBR-based disks could only have four pri
‘mary partitions, and the size ofa partition
\vas limited to 2TB (once an impossibly
large size but today sometimes severely
Figure t: Listing the partition tables with fdisk.
30
limiting). The Unified Extensible Firm-
ware Interface (UEFI) standard, defines a
new format for specifying partition infor:
mation known as the GUID Partition
‘Table (GPT). As older PCs are replaced,
GPT-based disks are replacing MBR-based
disks. All new personal computers, in
cluding those running Linux, macOS,
and Windows, support GPT. Some oper-
ating systems still offer MBR support for
compatibility with older hardware.
fdisk for MBR Partitions
‘The fisk utility lets you ereate and man-
age partitions on MBR-based disks. Fisk
has two basic modes: interactive and
non-interactive. Non-interactive mode
queries a partition and displays the infor-
mation, By contrast, interactive mode is
menu driven and lets you alter, as well as
explore, partitions and partion tables.
Running fis prints a listing of the
Patton tables of allo the dives on the
system. To use fdisk, you might need to
preface it wth suo sudo to attain root
privileges, depending on your distribution.
‘To view only a single drive's table, ap-
pend the drive name to the command:
aise -1 /aer/sta
Note that fisk requires a drive as its de
vice argument. Faisk’s output (Figure 1)
includes the total drive size and basic ge-
‘ometry, then lists the partitions on the
drive and their stat and end locations,
size, and partition type (both by name and
by ID number). Size is reported in blocks.
By adding the-u flag, you can have fsk
report partition start and end locations in
sectors instead of cylinders. Running
‘Aik -2
prints onthe size
The device but
wrest fo bon
ve and prions,
agro
with fdisk, start it
mapaencrsets
I Onto me tana
A igs and apeaty
iteen unt
LINUX SHELL HANDBOOK ~ 2022 EDITION
Ra Ce ce
ais /aer/ada
‘ais -u /aev/eae
‘The program writes its output tothe screen
and provides a command prompt but does
not provide paging (e.., les), s0 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 (7),
delete existing partitions (d), verify the
partition table (v), and set several flags
(the most notable being the bootable flag,
‘toggled with a). To apply any changes,
write a new partition table to the drive by
centering w. At any time, you can quit with
‘out writing the partition table with q
Creating a partition is a multistep pro-
cess. Type 1 to begin, and fdisk will ask
‘whether you want to ereate a primary
partition (p) or an extended partition (e).
Whichever you choose, fdisk will then
ask you to select the partition number
(be careful to choose an unused one if
you have already created several) the lo
cation on the drive where you want the
partition to start, and its size.
Fisk will prompt you with the num-
ber of the first available cylinder on the
drive. To leave an empty space between
partitions, choose a higher number,
‘which could help if you ever need to re
size your partition,
gdisk for GPT Partitions
‘The new UEFI standard replaces the old
MBR with the new GPT format, which
solves some of the problems associated
with the MBR, supporting a much larger
disk size and theoretically allowing up to
128 partitions on a disk.
Because GPT uses a different format
for storing pattition information, it r-
quires a different utility. The most popu-
lar options for the Linttx command line
are the GPT fdisk utilities gdisk, sgdisk,
and fixparts. The GPT fdisk toolset
‘comes standard on several contemporary
Linux systems; if you don't find i, install
it through your distro's package manage-
‘ment system. Once you have installed the
GPT toolset, you can use it to check and
‘modify the disk. The gdisk command
here returns what follows for a new disk;
isk /aov/ean
BR: not present
BSD: not present
ADL: not present
Ge: not prevent
Several choices for managing the part
tion table appear in the text mode menu.
For instance, choosing the p option prints
the partition table, whereas o frst out-puts a security prompt and then creates a
GPT table. The n option lets you create a
new disk-sized data partition. The w op-
tion writes the data (saves your changes)
from the gdisk session,
Gdisk can convert MBR-partitioned
hard disks to GPT, which removes the
need to back up and restore existing par-
tition content. Choosing r sends you to
the recovery and transformation menu,
which offers options for converting your
[MBR disk to GPT. Gaisk can also convert
from GPT to MBR. In some cases, this
‘option will not work, so be sure to back
uup your data if you try it.
GNU Parted
Fisk is one of the older Linux tools, and
Gdisk is modeled after it. Increasingly,
‘many users prefer GNU Parted.
You can run parted in interactive or
non-interactive mode. The non-interac-
tive syntax is parted
-. Running the command
parted /dov/eda print
prints the partition table found on the
/dev/sda disk (Figure 2). The information
displayed is similar to faisk's,
Providing the ~i flag before the device
and command arguments launches
parted in interactive mode. Unlike faisk,
however, you can create and modify par-
titions in non-interactive mode as well.
One important difference between
parted and fsk and gdisk is that parted
‘commands take effect immediately; that
is, when you create a new partition table,
the existing partition table (if any) on the
target drive is overwritten. This leaves lit-
tle margin for error when working with a
drive that has existing partitions and can
leave you hunting for recovery tools (for-
tunately, Parted can assist in that task, as
well). The command
parted 2
‘kpart 2
cond?
‘where partition_type is primary, extended,
ot logical. For primary or logical part
tions, you must also specify fesystem_
type, the filesystem format that the par-
tution will hold,
However, the mkpart command does
‘not actualy create the lesystem. To do
0, use mkpartfs instead. Parted supports
‘many common filesystems, including
ext, FATS2, NTPS, JFS, UFS, XPS, and
Linux swap. The start and end parameters
specify the location of the new partition
con the disk; you do not have to use drive
‘geometry such as sectors, but you can
provide human-readable sizes expressed
in megabytes.
‘To remove a partition, use parted rm , where isthe part
tion number.
Parted really improves on fdisk in its
ability to move and resize partitions. For
variety’s sake, start Parted in interactive
mode before exploring partition manipu
lation. You still need a drive device ar-
gument, such as
parted <1 /aev/bao
While in interactive mode, the device
given as an argument is assumed; you do
not need to inelude it in the commands
you type. To switch to a different device
within interactive mode, type
select
atthe Parted command prompt.
The resize command takes three argu:
‘ments: the partition number, the new
start location of the resized partition, and
the new end location. To continue the
above example, running
estze 1 0 1000
at the prompt would resize the partition at
/deu/hdbl to begin atthe stat ofthe drive
‘and end at the 1000MB mark,
You can use Parted both to grow and
shrink partitions. However, for ext2/3 fle-
systems, you cannot change the start loca-
tion with a resize command, only the end
‘That restriction does not apply to the
other filesystems that Parted supports.
Parted can move a partition toa new
free location on a drive with the move
command, The syntax is
rove cpartitiontinber>
although is
optional. If omit-
ted, the partition is
moved to the new
location in its orgi-
nal size. fan end
ing point defines a
new size for the
partition, Parted
Automatically =
sizes as well as
‘moves it
‘When shuffing
and resizing parti-
tions, you might
LINUX SHELL HANDBOOK - 2022 EDITION
fdisk, gdisk, and parted CONFIGURATION
need to duplicate a partition in a new loca-
tion, perhaps to move a partition to a new
device in an attempt to free up space. At
the Parted prompt, use
cp 2
“originnlPartitiom ctnrgetPartition>
where /original/device is optionals it
omitted, the current working device will
be assumed. Thus, the command
ep (ov /add $2
copies the /dev/sdbs partition to /dev tut
I you accidentally delete a partition
from the partition table or overwrite the
partition table itself, entering
rescue cond
initiates a search for filesystem signa
tures on the disk. Parted searches a range
of sectors around the start and end posi-
tions for signs ofthe filesystem, so you
ddo not need to be exact. If it finds a po-
tential filesystem in the appropriate loca-
tion, Parted asks whether you want to
create a new partition. For this rescue to
work, the filesystem must be more or less
intact; Parted can only recreate partition
table entries ~ to fix filesystem corrup-
tion, you need other tools.
The LVM Alternative
‘Logical Volume Manager (LVM) is an
alternative to traditional partitioning that
treats the space on one dive — or even
multiple drives - as a single unit and di-
vides it into logical volumes. GNU Parted
also works with LYMS.
‘The use of LVMs may come at a price:
Should a drive become corrupt, your en-
tire system suddenly can be inaccessible,
By contrast, if you use traditional parti-
tions, especialy for /home, you might be
able to recover data by booting froma
Live device after the oot or boot parti-
tion erashes. You should research the dit
ferences between LYM and traditional
partitioning carefully before deciding
Which to.use, Bl
fan" Esau naracin St
31Configuring filesystems with mkfs, df, du, and fsck
BUILDER
Although most Linux distributions today have simple-to-use graphical
interfaces for setting up and managing filesystems, knowing how to
perform those tasks from the command line is a valuable skill. We'll
show you how to configure and manage filesystems with mkfs, df,
du, and fsck. BY NATHAN WILLIS
ix suport a wide na of Ge
Losin ntti many
rgiatel on other operating 3
teme: The mos common cles far
tanta, however alate ave
Lins ent lowed by the high pe
formance XPS and Bt fesyten or
compatsy knowing howto work
sre VERT system pont
Because itis the standard che found
preinstalled on any med nluing
Use thumb dives and sh isk, Ag
tonal, several ofthe same lie
ted to manage normal flesyteme ako
apply to ewap partons, wih the
Lipo Keel oes a ial memory
when Ratti saree
mkfs
‘The mkfs command (Figure 1) creates a
new filesystem on a specified block de-
vice, such as a partition on a hard disk,
‘The basic usage is:
ricfs -t cfdecysten type
Figure 1 The simulated mits commands for XFS and ext3 differ (The
fags specify a simulation, which does not actually creat
filesystem.) The + and -F flags tell fs to force filesystem creation,
even if it detects a filesystem already in place.
32
where < filesystem _type > is a Linux-
supported filesystem type (eg., ext3 or
XFS) and isthe location
of the target disk partition (e.g. /dev/
sda or /dev/sde3). Filesystem-specific
options are added after < ilesystem_
type> (see also the “Filesystem Options”
box).
‘The basie form of the command de-
scribed in the previous example hands
off creation of the filesystem to one of
several specialized utilities, depending
on the filesystem type you specify (eg.
mkf.ext3, mkfs.xfs, or mks. fat). Be-
cause filesystems differ so much from
‘each other, having specialized tools
maintained by experts in the individual
filesystems results in more stable code.
‘Most of these utilities implement the
same options, although they vary accord-
ing to the features implemented in the
different filesystems. According to the
rms man page, the general form of the
command is now depracated in favor of
these type-specific mks. utilities.
Despite the differ
ences, afew key op-
tions are common
to all mkfs.* ui
ties. Adding the -¢
flag checks the
specified device for
bbad blocks, which
is then skipped over
luring the filesys-
tem creation step.
‘Adding the or -V
flags produces ver-
bose or extremely
verbose output,
spectively,
mkts
Examples
To format the st
panition ofthe
frst drive ona sys
tem a8 ext, you
would run the
command
LINUX SHELL HANDBOOK ~ 2022 EDITION
Cae eG
ifs -t extt /dev/ota1
‘This command uses the default block size,
‘node parameters, and all other options,
some of which are determined at run time
‘when mis analyzes the geometry of the
disk partition, Using
iikfs =t oxtt -b $086 /dow/saat
also creates an ext4 filesystem on /dev/
sda, but it forces the use of 4096-byte
blocks. Running
és -t ext -b 4008 2
“3 dovives/dev/sabn /der/siat
creates the same filesystem as the pre-
ceding command, but it creates the jour-
nal on a separate partition (/dev/sdb1).
‘To create an XPS partition on /dev/sda1,
center the following mkfs command:
kfe “tf /dov/sdoi
‘To speeily the use of 4096-byte blocks on
this filesystem, use
nkfs -t xfs -b size-a0se /der/sda1
‘which is a different syntax than that
used for ext4. The following command,
‘which uses the alternative (and now
preferred) mkjs.*
ncfe.btefs -L aylabel
creates a Birfs filesystem with 2 16-KiB
default block size (where 1000KiB
1024KB). To create a partition with a 4KiB
block size, use:
kts. bert -L mylabel “1 Uke
and ~ex-
clude-type= < filesystem type > allow
‘you to limit or exclude output to a particu-
lar filesystem type.
(On discovering a nearly ful filesystem,
you can further explore space usage with
du, Executing du re-
tums alist ofthe disk space occupied by
‘each subdirectory beneath , expressed in kilobytes. Adding the -«
‘option tells de to report the space used by
the files in addition to the directories
Both commands are recursive. Ifyou do
not provide a directory as an argument to
du, it reports on the current directory. The
-c option produces a grand total in addi-
tion to individual usage statistics. Other
helpful options are-L, which could help
‘wack down an errant large file, following
all symbolic links; -x, which limits the
scope of the search to the current filesys-
tem only; and ~max-depth=N, which al-
lows you to limit the number of recursive
subdirectories into which you descend,
‘This option is very helpful when dealing
with a lange file library:
Several utilities exist to help you get
better performance out of your filesys-
tems. The rune2fs program lets you con:
‘rol many parameters of ext2, ext3, and
ext filesystems. You can set the number
‘of mounts between automatic filesystem
integrity checks with rune2fs ~cN, set
the maximum time interval between
checks with cune2fs i Nfd|m|w} (where
, m, and w are days, months, and.
‘weeks, respectively), of add an ext3 or
cextd journal to a filesystem that does not
hhave one with tune2fs-j. Additionally,
you can adjust RAID parameters, journal
settings, and reserved block behavior, as,
‘well as change parameters manually,
such as the time last checked and num-
ber of mounts, which are usually re-
ported automaticaly.
Other utilities are associated with spe-
cific filesystems. Btrfs has a separate uti
ity for resizing filesystems (birfs filesystem
resize). The btrfs-convert tool can migrate
data from existing ext2/3/4 volumes to
the Bits filesystem,
XPS also provides a defragmentation
tool called 2fs_fsr that can defragment a
‘mounted XFS filesystem, and Burts sup-
ports defragmentation of metadata or en-
tire filesystems. The
btrfs filecysten defragnent utility, where
Is a filesystem supported by the com-
‘mand (eg. ex13, ext4, XFS, Btrfs, VFAT),
supports options that tweak filesystem
settings such as the size of blocks used,
umber and size of nodes, fragment.
size, amount of space reserved for use
by root privileged processes, amount of
space reserved to grow the group block
descriptor ifthe filesystem ever needs to
be resized, and settings for stripe, stride,
and other details required for using the
filesystem in a RAID
Al ofthese parametors have default set
tings, and unless you are sure you ne
tochange thom, you can safely create a
filesystem with the default settings. Nev-
ertheless, itis a good idea to familiar
Yourself with the basics of filesystem po
rameters in general, in case you ever run
into problems,
The block sizeis the size ofthe chunks
thatthe filesystem uses to store data —in
‘sense, itis the granularity ofthe pieces
into which a files spit when stored on
the disk
command defragments the entire filesys-
tem verbosely. No such utilities exist for
ext3, but exté has eddefrag.
Troubleshooting
I you suspect trouble ona filesystem, you
00% fa/caovice?
to check and make repairs. Ifyou run fsck
with no target device specified, it wll run
checks sequentially on all ofthe filesys-
tems in /ete/ftab.
The filesystem-specific error-checking
programs ~ e2fsck for ext2, ext3 and ext4,
btrfsck for Biri, and fsck. vfat for VAT ~|
support many of
the same options,
but again, the syn:
tax may vary, s0 it
is critical to read
the man page for
the filesystem
cheeker before at
tempting any re-
pai
When cor-
rupted, VEAT file:
systems suffer
from bad clusters,
bad directory
pointers, and even
bad file names.
‘The fsck.vfat tool
can find and cor-
rect many of these
problems. Like the
Figure
LINUX SHELL HANDBOOK - 2022 EDITION
Larger block sizes ean improve disk
throughput because the disk can read
‘and write more data ata time before
‘seeking to a new location; however, a
large block size can waste space in the
presence of many small files, because a
{ull Block is consumed for each fragment
cof afile, even if only a small portion oft
is used. Ext3/¢ and XFS allow you to
specify the block size (1024, 2048, 4096,
tc.) by adding a -b lag; the syntax that
follows the flag varies, so consult the
‘manual pages for each option.
‘The mkswap command creates a swap
‘area on a disk partition, just as mkfs
creates a filesystem. The basie syntax
isthe same, mkswap , withthe optional -cflag again al-
lows you to check the partition for bad
blocks before creating the swap area.
Just as a new filesystem must be at-
tached to Linux’s root filesystem with
‘mount before you can use it, a new
‘swap partition must be attached with
‘swapon-L .
others, it can be called in non-interactive
‘mode for use in scripts, and it can mark
bad clusters automatically to prevent
their reuse in the future. The -V flag tells
fsck. vfat to run a second check after it
has tried to correct any errors
XFS has separate error-checking and
repair utilities: xfs_check and xfs_repair
(see the man pages for more on com
‘mand-line options).
For ext2/3/4 problems, the debug tool
lets you examine a filesystem and correct
errors interactively. It can step through
and work within a filesystem with com-
‘mands similar to those of atypical Linux
shell, such as ed, open, close, pwd, mkdir,
and even chroot.
BR atopic
pact cary
he results ofa at command showing disk usage on a Live
system. The-a flag includes “dummy” filesystems lke roc.
33