Professional Documents
Culture Documents
WWW.LINUX-MAGAZINE.COM
openSUSE Conference
BASH CLASS
Think like the experts: The powerful Bash shell provides a comprehensive collection
of utilities for configuring and troubleshooting Linux systems.
Before the icons, menus, and wobbly windows of the modern Linux user environment, users
managed and interacted with their systems from the command line. Many advanced users still
prefer to work from the keyboard, and many will tell you that exploring the command-line
environment is the best way to build a deeper understanding
of Linux. The Linux Shell Handbook is a thorough
primer on the Bourne Again Shell (Bash)
environment found on most Linux systems.
You'll learn to navigate, manipulate text,
work with regular expressions, and
customize your Bash settings. We'll show
you shell utilities for configuring
hardware, setting up users and groups,
managing processes, and installing
software - and we'll even help you
get started creating your own Bash
scripts to automate recurring tasks.
Keep the Linux Shell Handbook
beside your computer as a
permanent desktop reference on
the world of the terminal window.
GETTING AROUND
CONFIGURATION
26 Hardware Configuration 32 Configuring Filesystems
Learn about some tools for You can’t store files without a filesystem. Use these Bash
configuring and managing commands for easy filesystem configuration.
hardware on your Linux
system. 34 mount and fstab
Most Linux distros mount storage media automatically,
30 fdisk, gdisk, and parted but someday you might need a classic command-line tool.
Use these handy disk
partitioning utilities to 36 Time Tools
configure your hard drive These utilities let you set and keep time.
before you install a new operating
system.
81 SSH
Manage your server from a distance with this convenient
and secure remote access toolkit.
84 Rsync
Sync your files to stay consistent and avoid data loss.
46 systemd
Systemd has become the standard for starting,
stopping, and managing services in
Linux.
AUTOMATION
54 Managing Processes 86 cron and at
Monitor and manage the Automate and schedule common tasks.
processes running on your
system. 88 Bash Scripting
We show you how to start writing your own Bash
58 Package Management scripts.
Tools
Linux package tools help 93 Images and PDFs
you install and manage software. We show you some Use these picture perfect command-line tools to convert
package tools in Debian and RPM-based systems. and adapt your digital images.
65 dd and mkisofs/genisoimage/xorrisofs
Create backups and bootable CDs with these handy
disk utilities.
96 Bash Command Index
AT YOUR COMMAND
Beyond all the splash screens, screen savers, and vivid rock-star poses. The option -debugger is also used
to log debugging information.
wallpaper is the simple yet powerful Bash shell. BY BRUCE BYFIELD
through the keyboard, type a line, then If you start to get lost when you are navi In later articles, you will learn about
press Enter. Of course, modern tools gating around in the directory structure, other Bash commands for modifying
like Konsole or the Gnome Terminal you can always enter the pwd command text, managing users, overseeing
are not terminals in the old sense but (print working directory) to display the processes, and troubleshooting net
are actually terminal emulators. You name of the current directory. works.
can close or minimize the terminal To create a new directory, enter the
window as you would any other win mkdir command and give the name of History
dow on your Linux system. the new directory: If you are doing repetitive commands in
This handbook assumes you have Bash, you can save time by using the
some basic knowledge of how to move $ mkdir /home/berney/Music/Beatles history for the current account. Stored
around in the Bash shell. If you are look in the bashjzistory file in your home di
ing for a very basic crash course, a few Or, if user bemey were already in his rectory is a list of commands you have
simple commands will help you get fa Music directory, he could just type: run, with the oldest numbered 1. You
miliar with the command prompt. can use the arrow keys to move up and
Most likely, the terminal will open in $ mkdir ./Beatles down or use the plain command history
your home directory. Type Is to list the to see a complete list of what is stored
contents of the directory. You can use the The cp command lets you copy files. The in your history.
cd (change directory) command to move syntax is as follows: If you are somewhat more adventur
to another directory. You’ll also need to ous, you can use a number of shortcuts
mention the path to the target directory: cp <source_filename> P to run a previous command in the his
< dest inat ion_f ilename> tory. Inumber runs the command with
$ cd /home/bemey/Music that number. Similarly, !-number sets the
number of previous commands to revert
Bash shells let you use a dot (.) in the to, and Istring runs the first command
path to represent the current directory. that includes that string.
In other words, a user named berney When you are either very certain of
could move from his home directory to what you are doing or willing to live
the Music subdirectory by typing: dangerously, you can enter ^stringl^
string2/'' to repeat the last command but
$ cd ./Music replace the first string of characters with
the second. Another trick is to add :h to
A double dot means “go up one level in remove the last element of the path in
the directory path,” so if berney wanted the command or :t to remove the first el
to go from /home/bemey/Music back to ement. However, if you are uncertain of
/home/bemey, he could type: Figure 2: Finding the Terminal in Ubuntu. the results, you can add :p to print the
brucegnandaycd /home/bruce
Table 1: Some Basic bruce@nanday:'$ ''bruce''trish/' Table 2: Man Page Sections
Bash Commands cd /home/trish Section Description
brucegnanday:/home/trish$ !-l:h
Is List contents of the current 1 General commands
directory cd /home
brucegnanday:/home$ | 2 System calls
cd Change directory
Figure 3: You can use several keyboard 3 C library functions
pwd Show current working directory
shortcuts to run commands in the history 4 Special files (usually devices
mkdir Make directory found in /dev) and drivers
with slight changes. Here, the string "bruce"
cp Copyfile(s) 5 File formats and conventions
is replaced with "trish'’ in the first case,
rm Remove file(s) then only the head of the path is preserved 6 Games and screensavers
rmdir Remove directory in the second. 7 Miscellanea
8 System administration com
mands and daemons
command that you find but not run it press Ctrl+Z followed by Ctrl+C to re
(Figure 3). turn to the command line.
When you are doing deeper research, ers simply maintain both info and man,
Documentation consider using apropos followed by a focusing on the command structure in
Bash and the individual commands as topic to receive a list of all the applicable the man pages and on basic instruction
sociated with it add up to a lot to learn. man pages. The one drawback to apro in the info pages. Still, it can never hurt
Fortunately, you don’t have to remember pos is that, unless you are very specific, to check both in the hope of finding the
everything. Like other Unix-type sys you could get dozens of pages, only a most complete information.
tems, GNU/Linux includes a number of few of which are relevant to you.
different help systems. By contrast, if all you need is a brief Digging Deeper
The most basic form of help is the snippet of information, use whatis fol As experts will be quick to note, these
man page (Figure 4). Man pages are di lowed by the command. For example, if comments provide only the barest out
vided into eight sections (see Table 2), you enter whatis fdisk, you receive the line of subjects that have filled entire
but most of the time, you only need to line fdisk (8) - Partition table manipula books. Read on for more about working
type the command man followed by the tor for Linux. The (8) refers to the man in the Bash shell. For additional informa
command, file, or concept about which section where detailed information is tion, a good place to start is the man
you want information. available. Similarly, if you need to iden pages. Another important reference is
However, some topics have entries in tify a file type, use type then the file. the online Bash Reference Manual [1].
several sections. To go to the specific For several decades, man pages have Read this material with a Bash shell
section, place the number of the section been the standard help form. However, open next to the text, so that you can try
between the man command and the more than a decade ago, the GNU Proj commands as you learn about them. ■
topic. Thus, man man takes you to the ect made info its official help format.
basic page about the man command in But, instead of replacing man, info has INFO
section 1, but man 7 man takes you to a simply become an alternative (Figure 5).
[1] Bash Reference Manual:
section about the collection of macros Although some man pages today stress
http://www.gnu. org/software/bash/
used to create man pages. Either way, that the full help file is only available
man ual/bashref.html
when you are finished reading, you can through info, in practice, many develop-
L5(l)
ESCRIPIIOM
List information about the FILES (the current directory by default).
--block-size=SIZE
use SIZE-byte blocks
-B, --ignore-backups
do not list implied entries ending with -
Figure 4: The man page for the Is command. Figure 5: The info page for the Is command.
k
FILE POWER i'H
We give you an overview of commands for moving, editing,
II
rm -r can remove key system files when
used thoughtlessly; thus, some users
prefer to add -preserve-root when run
ning the command anywhere near the
root directory. In comparison, rmdir is a
compressing, and generally manipulating files. BY BRUCE BYFIELD much safer option, because it works
only on empty directories (Figure 4).
A completely different approach to file
NU/Linux treats everything as a owner or timestamp, or -no-preserve management is taken by dd, an old Unix
• bzipcat displays the contents of a file tives as the ability to archive an entire di pride themselves on their ability to con
in an archive, with the same options rectory tree and create archives in multi struct elaborate and elegant globs.
as the cat command. ple formats (of which TAR is the only one But what if you want to work with a
• bziprecover helps recover damaged ar that is widely used), as well as numerous metacharacter? Then you put a back
chived files. options to view and edit already-archived slash (\) in front of it. For instance, \\ in
• bunzip2 decompresses files. files. However, unless you are a system dicates that you are looking for a back
The differences between gzip and bzip2 administrator or an old Unix hand, slash, not a directory. The backslash is
can be hard to remember, so many users chances are you will rarely see cpio used. known as an escape character, and it sig
prefer to rely on the tar command. The nals that the command should read what
tar command not only has the advantage Extending File follows literally, instead of as a glob.
of having options to use gzip and gunzip Management with Globbing Globs can be especially useful when
(-z) or bzip2 (-;), but it also offers far One reason shell commands are so pow you want a selected list from a directory
more control over exactly how you com erful is that they can work with multiple full of files or when you are using one of
press files. files. With many commands, the easiest the grep commands to find content in
In fact, tar's options run into the doz way to work with multiple files by enter side a file. However, you must be careful
ens - too many to detail here. For exam ing a space-delimited list directly after about using globs with commands like
ple, you can use -exclude < file > to ex the command. However, the most con rm or mv that change or rearrange the
clude a file and -p to preserve the per cise and efficient way to handle multiple content of your hard drive. Otherwise, a
missions of a file. If you want to preserve files is through file globbing. command can have disastrous conse
a directory structure, use -p. To be safe File globbing refers to the use of quences. To be safe, consider using a
when decompressing, use -k to prevent regular expressions (often abbreviated newly constructed glob with the innocu
any accidental overwriting of files. to regex), pattern matching, metacha ous Is command, so you can see what
The tar command also includes its racters, or wildcards. The terms are files it might affect.
own built-in utilities in many cases. To not quite synonymous, although they
add one archive to another, use the are mostly used as if they were. What Learning that Pays
format ever term you use, it refers to a string File management commands have a long
of characters that can stand for many history in Bash. During the course of
tar --append <tarfilel> <tarfile2> different strings. their development, they have accumu
The most widely used glob in the Bash lated options the way ships accumulate
To update an archive with newer versions shell is the asterisk (*), which stands for barnacles - constantly and apparently
of files with the same name, use the -u any number of unknown characters. haphazardly.
option, or to compare the files in an ar This glob is especially useful when you However, often, the options are sim
chive with other files, use the format: want to find files that share the same ex pler than they first appear. For example,
tension. For instance, the command Is you can be fairly certain that most file
tar --compares <tarfile files> *.png lists all the PNG graphics in the management commands will use -r to in
current directory. clude sub-directories and their contents
The fourth compression command, cpio, By contrast, a question mark (?) and -v to print a detailed description of
has fallen out of favor in recent years, stands for any single character. If you what they are doing to the terminal.
probably because its format is non-stan enter the command Is ca?.png, the list of Similarly, to force a command to work,
dard. For example, to create an archive matches will include the files cat.png regardless of consequences, you gener
with cpio, you have to pipe Is through it and cab.png but not the file card.png, ally use -f. Adding the -i option, how
and specify the file for output: which contains two characters instead of ever, means that every action needs to
one after the ca. be confirmed by you before it happens.
Is | cpio -o > <outputfile.cpio> From these simple beginnings, globs Even with such hints, these commands
can quickly become more elaborate. To can take a long time to master.
That said, cpio has even more options specify specific characters, you can use In fact, for basic actions, they might
than tar, including such powerful alterna square brackets, so that test[12].png lo offer little more than a graphical file
cates files test1.png and manager can. But, if you try to do some
bruce@nanday:~$ file ./visits.odt test2.png, but not test3.png thing more intricate - such as specifying
./visits.odt: OpenDocument Text (Figure 8). Also, you can how symbolic links are going to be
Figure 7: The file command identifies the format of files, specify a search for a regex at treated or excluding a file from an ar
helping you identify them. the start (A) or the end ($) of chive - the file management tools easily
a line. Similarly, you can outclass their desktop equivalents. If you
magazine@MacBuntu:~$ find ./test[12].png search at the start of a word learn some of the less straightforward
./testl.png with \< or the end of a word options for these commands, you’ll soon
./test2.png with \> - and these are sim understand why many experts prefer to
magazine@MacBuntu:-$ |
ply a few common possibili use the command line for file manage
Figure 8: A few regular expressions increase the flexibil ties. Using globs is an art ment over anything that the desktop has
ity of commands. Here, they greatly simplify finding files. form, and experts rightly to offer. ■
T O
hen it comes to finding and /home, and /tmp directories to look for owner. For example, if you want to find
Note the {} \; at the end of the com time. Just execute the updatedb com In its most basic form, grep searches a
mand. The {} symbol is a placeholder mand as root to force the system to up file for text matching a specified pattern
for the name of the file that has been date the database. and outputs every line of the file that
found, whereas \; indicates the end of contains the string.
the command. Instead of -exec, you can whereis and which The syntax for the grep command is:
also use the -ok option, which asks you If you need to find the path to an execut
for confirmation before the command is able program, its sources, and man grep [options] pattern file_name(s)
executed. pages, the whereis tool can help. The fol
Finally, you can use the -fprint option lowing command, for example, returns You can specify the search pattern ex
paths to binary, source, and man pages plicitly or use a regular expression. (See
find /home/user -name "Lin*" P for the Rawstudio application: the article elsewhere in this issue on reg
-fprint search_results.txt ular expressions.)
whereis rawstudio Several options help to refine the
to print the search results to a text file. search (see Table 1 for some exam
Using the available options, you can ples). For example, if you don’t want
Searching for Files with limit your search to specific types. To to output all the lines that match the
locate and updatedb search only binaries, you can use the -b search string but only want to know
Similar to find, the locate tool lets you option, or use -m to search for man the number of matching lines, use the
find files by their names. But instead of pages and -s to search for source files. -c option.
searching the system in real time, locate Whereas the whereis tool lets you lo To specify more than one pattern, use
searches the database of file names, cate program files and man pages, which the -e option once for each pattern:
which is updated daily. The key advan tells you which version of a command
tage of this approach is speed; finding will run if you just type its name in the grep -e patternl -e patterns P
files with locate is much faster than terminal. For example, the which soffice filename.txt
with find. The use of locate is easy: Just command returns the /usr/bin/soffice
run the locate command with the name path. This means that the soffice com Alternatively, you can use the -f option
of the file you want to find: mand runs the application in the /usr/bin to specify a pattern file that can contain
directory. If you want to find all the lo multiple patterns.
locate backup.sh cations of the command, you can use Although most modern text editors
the -a option: and word processors have built-in
To ignore the case, you can use the -i search features, grep is still very useful
option: which -a soffice for searching across a group of several
files or for expressing complex search
locate -i backup With just these few, simple commands, you patterns that would be cumbersome in
can locate your files quickly and easily. a GUI tool. System administrators often
As with find, you can use wildcards in use grep to hunt for errors, warnings,
your searches: grep devices names, and other information
The Bash command shell also has tools in system logs. See the following arti
locate "*.jpg" that will let you search for a text string cles on “Regular Expressions” and
inside of a file. The most popular com “Pipes and Redirection” for more grep
If you want to see only a limited num mand for finding a search string is grep. examples. ■
ber of results, you can do so by using
the -n option followed by the number Table 1: Examples of grep Options
of your choice: Option Description
-c Prints only a number representing the number of lines matching the pattern
locate "*.jpg" -n 5
-e Specifies an expression as a search pattern (you can specify multiple
expressions in one command - use the -e option with each expression)
As mentioned before, locate performs
-E Use extended regular expressions (ERE)
searches by querying the database of
-ffile_name Take patterns from a pattern file
file names, which is automatically up
dated every day, so if you have just -i Ignore case
downloaded a batch of photos from -/ Prints a list of file names containing the search string
your camera, the locate command -o Only prints matched parts of matching line
won’t see them until the database is -v Prints all the lines that do NOT match the search pattern
updated. -w Match a whole word
Fortunately, you don’t have to wait
-A n Prints the matched line and n lines after the matched line
until the system updates the database;
-Bn Prints the matched line and n lines before the matched line
with the updatedb command, you can
manually update the database at any -Cn Prints the matched line with n lines before and n lines after
Regular expressions help you filter through the data to find the information you need. BY MARTIN STREICHER
ost computer systems have an library, or PCRE. You will find the PCRE lowed by an n. The letters must appear
has since expanded into a POSIX stan Spider-Woman the start or end of a line, or the begin
dard for pattern matching. Today, the ning and end of a word. A regex can also
most popular implementation of regex is Here, grep scans each line in the file, describe alternates (i.e., occurrences of
the Perl-Compatible Regular Expressions looking for an m, followed by an a, fol this or that pattern); fixed, variable, or
indefinite repetition (zero, one, two, or each regex on the command line with grep -i -E ,A(bat|cat)' heroes.txt
more of any stretch); ranges (e.g., any of single quotes to protect the regex opera
the letters between a and m, inclusive); tors from interpretation by the shell. For The second approach uses the set opera
and classes (kinds of) characters (e.g., example, both * and $ are regex opera tor ([ J). If you place a list of characters
printable characters or punctuation). tors, but they also have special meaning in a set, any of those characters can
In the rest of this article, I explore to the shell. The shell’s asterisk is differ match. (Think of a set as shorthand for
some examples of regular expressions ent from its facsimile regex operator: It alternation of characters.) For example,
that work with grep. Many other Unix matches any portion of a file name. The
tools, including interactive editors Vi regex * is a qualifier, matching zero or grep -E ,A[bcBC]at' heroes.txt
and Emacs, stream editors sed and awk, more operands. The dollar sign indicates grep -E 'A(bat|Bat|cat|Cat)1 heroes.txt
and all modern programming languages a variable in the shell but marks the end
also support regex operations. of a line or string in a regular expression. both produce the same results. To sim
For more information on regex theory To find names that end with man, you plify again, you can ignore case with -i
and practice, see the Perl man pages (or might use the regex man$ to match the to reduce the regex to /'[bc]at.
see perl.org [1]) and books by Jeffrey sequence m, a, and n, followed immedi To specify an inclusive range of char
Friedl [2] and Nathan Good [3]. ately by the end of the line or string ($). acters in a set, use the hyphen (-) opera
Given the purpose of A and $, you can tor. For example, usernames typically
Match a Position find a blank line with A$ - essentially, begin with a letter. To validate one in a
To find names that begin with Bat, use: this regex specifies a line that ends im web form submitted to your server, you
mediately after it begins. might use ^[A-Za-z]. This regex reads:
grep -E 'ABat' To find words that begin with bat, Bat, “Find the start of a string, followed im
cat, or Cat, you can use one of two tech mediately by any uppercase letter (A-Z)
The option -E specifies a regular expres niques. The first is alternation, which or any lowercase letter (a-z).” By the
sion. The A (caret) character matches the yields a match if any of the patterns way, [A-z] is the same as [A-Za-z].
beginning of a line or a string - an imag match. For example, the command You can mix ranges and individual
inary character that appears before the characters in a set. The regex [A-MXYZ]
first character of each line or string. The grep -E 1A(bat|Bat|cat|Cat)' heroes.txt matches any of uppercase A through M,
letters B, a, and t are literals and only X, Y, and Z. If you want the inverse of a
match those characters. Filtering the does the trick. The vertical bar regex op set - that is, any character except what’s
contents of heroes.txt, the command erator (|) specifies alternation, so this\ in the set - use the special set [A ] and
that matches either the string this or the include the range or characters to ex
grep -E 'Abat' heroes.txt string that. Hence ^(bat\Bat\cat\Cat) clude. To find all superheroes with at in
specifies the beginning of a line, fol the name, excluding Batman, type:
produces Batman and Batgirl. lowed immediately by one of bat, Bat,
Many regex operators are also used by cat, or Cat. Of course, you could simplify grep -i -E '[Ab]at' heroes.txt
the shell (some with different seman the regex with grep -i, which ignores
tics), so it’s a good habit to surround case, reducing the command to: The command produces Catwoman and
Black Cat.
Table 1: Common Regular Expression Operators Certain sets are required so
Operator Purpose frequently that they are repre
. (period) Match any single character. sented with a shorthand nota
A Match the empty string that occurs at the beginning of a line or string. tion. For instance, the set
$ Match the empty string that occurs at the end of a line. [A-zO-9_J is so common, it can
A Match an uppercase letter A. be abbreviated \w. Likewise,
a Match a lowercase a.
\d Match any single digit. Listing 1: heroes.txt
\D Match any single non-digit character. $ cat heroes.txt
Iw Match any single alphanumeric character; a synonym is [:alnum:]. Catwoman
[A-E] Match any of uppercase A, B, C, D, or E. Batman
lAA-E] Match any character except uppercase A, B, C, D, or E. Here, the caret P) inverts the The Tick
range operator to exclude any of the characters that appear in the range. Spider-Man
X? Match no or one capital letter X. Black Cat
X* Match zero or more capital Xs. Batgirl
the operator \IV is a convenience for the no or 1,1 or more, and 0 or more re perl -n -e '/AThe\s+(.*)$/P
set [AA-zO-9_]. Also, you can use the no peats, respectively (e.g., ?is shorthand print heroes.txt
tation [:alnum:] instead of \w and for {0,1}). The regex boys? matches
[A[:alnum:]] for \W. boy or boys. The regex Goo?gle matches the result should be Tick. The perl -e lets
Gogle or Google. The regex Goo+gle you run a Perl program right from the
Repetition, Repetition matches Google, Gooogle, Goooogle, and command line, perl -n runs the program
So far, I've shown literal, positional, and so on. The construct Goo*gle matches once on every line of the file. The regex
two kinds of alternation operators. With Gogle, Google, Gooogle, and on and on. portion of the command, the text be
these operators alone, you can match al • Repetition modifiers can be applied to tween the slashes, says: “Match the liter
most any pattern of a predictable length. individual literals, as shown immedi als at the beginning of the string, then
For example, you could ensure a user ately above, and can also be applied to ‘T’, ‘h’, ‘e’, followed by one or more
name started with a letter and was fol other, more complex combinations. white space character(s), \s + ; then cap
lowed by exactly seven letters or num Use the parentheses just as you do in ture every character to the end of the
bers with the regex [a-z][a-zO-9] [a-zO-9] mathematics to apply a modifier to a string. ” The rest of the Perl program
[a-zO-9][a-zO-9][a-zO-9][a-zO-9] [a-zO-9], subexpression. prints what was captured.
but that approach is a little unwieldy. Consider the file test.txt containing lines Individual Perl captures are placed in
Moreover, it only matches usernames of with typos: special Perl variables named $1, $2, and
exactly eight characters. so on, one variable per capture de
A regular expression can also include The rain in Spain falls mainly scribed in the regex. Each nested set of
repetition operators. A repetition opera on the the plain. parentheses, counting from the left, is
tor specifies amounts, such as none, 1, placed in the next special, numerical
or more; 1 or more; 0 or one; 5 to 10; It was the best of of times; variable. Consider the following,
and exactly 3. A repetition modifier must it was the worst of times.
be combined with other patterns; the $ perl -n -e '/A(\w+)-(\w+)$/T
modifier has no meaning by itself. As an Entering the following command, print "$1 $2\n"'
example, the regex A[A-z] [A-zO-9] {2,7}$
implements the username filter desired grep -i -E '(\b(of|the)\ ){2,}' test.txt which yields: Spider Man, Ant Man, Spi
earlier: A username is a string beginning der Woman:
with a letter, followed by at least two but produces on the the plain. It was the best Capturing text of interest just scratches
not more than seven letters or numbers of of times;. The regex operator \b the surface. Once you can pinpoint ma
followed by the end of the string. matches a word boundary, or (\W\iv| terial, you can surgically replace it with
The location anchors are essential \iv\W). The regex reads: “A sequence of other material.
here. Without the two positional opera whole words ‘the’ or ‘of’, followed by a
tors, a username of arbitrary length space.” You might be asking why the Express Yourself
would erroneously be accepted. Why? space is necessary: \b is the empty string Regular expressions are extremely power
Consider the regex A[A-z][A-zO-9] {2,7}. at the beginning or end of a word. You ful. Virtually every Linux command that
It asks the question: “Does the string have to include the character(s) between processes text supports them in one form
begin with a letter, followed by two to the words; otherwise, the regex fails to or another. Most shell command syntax
seven letters?” But it makes no mention find a match. also expands regular expressions to
of a terminating condition. Thus, the match file names, although the operators
string samuelclemens fits the criteria, but Capture the Needle might function differently from shell to
is obviously too long to be valid. If your Finding text is a common problem, but shell. For example, Is [a-c] finds the files
match must be a specific length, don’t more often than not, you want to extract a, b, and c; Is [a-c] * finds all file names
forget to include delimiters for the begin a particular snippet of text once it’s that begin with a, b, or c. Here, the * does
ning and end of the desired pattern. found. In other words, you want to keep not modify [a-c] as in grep; rather, * is in
Following are some other samples: the needle and discard the haystack. terpreted as. *. The ? operator works in
• {2,} finds two or more repeats. The A regular expression extracts informa the shell, too, but matches any single
regex AG[o] {2,}gle matches Google, tion via capture. To isolate the text you character. Check the docs for your favor
Gooogle, Goooogle, and so on. want, surround the pattern with paren ite utility to see what is supported. ■
• Repetition modifiers ?, +, and * find theses. Indeed, you already used paren
theses to collect terms because parenthe INFO
Locales ses capture automatically (unless they
[1] Perl documentation:
Iw (and its synonym [:alnum:]) are locale are disabled).
http://perldoc.perl. org/
specific, whereas [A-z0-9_]is literally the To see a capture, I’ll switch to Perl
{grep does not support capture because [2] Fried I, Jeffrey. Mastering Regular
letters A to z, the digits 0 to 9, and the
Expressions. Apress, 2004
underscore. If you're developing inter its purpose is to print lines containing a
national applications, use the locale pattern). grep’s regex operators are a [3] Goog, Nath a n. Regular Expression
specific forms to make your code porta small subset of what Perl has to offer. If Recipes, 2nd ed. O'Reilly Media,
ble among many locales. 2006
you type this command,
PIPE TIME
Special tools in the shell help you combine commands to create
impromptu applications. BY MARTIN STREICHER
he Linux command line provides commands with many pipes. For example, the file does not exist, it is created; if
respectively. The option -i ignores case. -I that sort of output - which is useful, be $ { ps; w } > state.'date '+%F''
(capital I) skips binary files. cause it often interferes with working at
Assuming that the directory /path/to/src the command line - redirect your output In the preceding command, ps runs, fol
contains files a, b, and c, using find in to the “bit bucket, ” /dev/null. Bits check lowed by w (which shows who is using
combination with xargs is the equivalent of: in, but they don’t check out. the machine), and the collected output is
Listing 3 shows a simple example. If captured in a file.
$ find /path/to/src you redirect the standard output of cat You can also embed a sequence of
a to /dev/null, nothing is displayed. (All commands in parentheses to achieve
b the bits are thrown into the virtual ver the same result, with one important
tical file.) However, if you make a mis difference: The series of commands
$ grep -H -I -i -n string a take, error messages, which are emitted collected in parentheses runs in a sub
$ grep -H -I -i -n string b to standard error, are displayed. If you shell and does not affect the state of
$ grep -H -I -i -n string c want to ignore all output, use the >& the current shell. For example, you
operator to send stdout and stderr to might expect the command { cd
In fact, searching a collection of files is the bit bucket. $H0ME; Is -1 }; pwd to produce the
so common that grep has its own option You can also use /dev/null as a zero same output as (cd $H0ME; Is); pwd.
to recurse a file system hierarchy. Use -d length file to empty existing files or create Note, however, that the commands in
recurse or its synonyms -R or -r. For ex new, empty files (Listing 4). braces change the working directory of
ample, the command the current shell. The latter technique
Other Tricks is inert.
grep -H -I -i -n -R string /path/to/src In addition to redirection, the shell offers The decision to use a combination or
many other tricks to save time and effort. a subshell depends on your intentions,
works as well as the combination of find The “back tick” or “back quote” op although the subshell is a much more
and xargs. However, if you need to be selec erator ('... ') expands commands in powerful tool. You can use a subshell
tive and pick specific kinds of files, use find. place. A phrase between back ticks to expand a command in place, just as
runs first, while the shell interprets the you can with back ticks. Better yet, a
Bit Bucket command-line, and its output replaces subshell can contain another subshell,
As you’ve seen, most commands emit the original phrase. You can use back so expansions can be nested. The two
output of one kind or another. Most com ticks to yield, for example, a file name commands
mand-line commands use stdout and or a date:
stderr to show progress and error mes $ { ps; w } > state.$(date '+%F')
sages, in that order. If you want to ignore $ ps > state.'date 1+%F’' $ { ps; w } > state.'date '+%F''
$ Is state*
Listing 3: The Bit Bucket state.2009-11-21 are identical. The notation $( ) runs
01 $ Is $ cat state.2009-11-21 the commands within the parentheses
02 secret.txt 13842 ttysOOl 0:00.54 -bash and then replaces itself with the out
03 $ cat secret.txt
04 I am the Walrus. 30600 ttysOOl 1:57.15 P put. In other words, $( ) expands in
05 $ cat secret.txt > /dev/null ruby ./script/server place, just like back ticks; however,
06 $ cat socrates.txt > /dev/null unlike back ticks, $( ) can be very
07 cat: socrates.txt: No such file or
directory $ cat 'is state.*' complex and can even include other $( )
08 $ cat socrates.txt >& /dev/null 13842 ttysOOl 0:00.54 -bash expansions:
09 $ echo Done. 30600 ttysOOl 1:57.15 P
10 Done.
ruby ./script/server $ (cd $(grep strike /etc/passwd | P
cut -f6 -d':'); ls)xw
Listing 4: Empty Files The first command-line captures the
01 $ cat secret.txt list of running processes in a file This command searches the system
02 Anakin Skywalker is Darth Vader. named something like state. password file to find an entry for user
03 $ cp /dev/null secret.txt
YYYY-MM-DD, where the date portion strike, clips the home directory field
04 $ cat secret.txt
05 of the name is generated by the com (field six, if you count from zero),
06 $ echo "The moon is made of mand date ' + %F'. The single quotes changes to that directory, and lists its
cheese!" > secret.txt around the argument prevent the shell contents. The output
07 $ cat secret.txt
08 The moon is made of cheese!
from interpreting + and %. The last
09 $ cat /dev/null > secret.txt command shows another example of grep /etc/passwd strike | cut -f6 -d':'
10 $ cat secret.txt the back tick. The evaluation of Is
11
state. * yields a file name. is expanded in place before any other
12 $ cp /dev/null newsecret.txt
13 $ cat newsecret.txt Speaking of capturing results, if you operation. Because the subshell has
14 want to capture the output of a series of so many uses, you might prefer to use
15 $ echo Done. commands, you can combine them it instead of the { } or the back tick
16 Done.
within braces ({ ... }): operators. ■
SHELL
home directory may also contain .bash_
login and bash_login. These dot files -
so called because each file name starts
with a period - are not ordinarily visible
when viewing directory contents. In
Make the Bash shell your own by customizing the shell
stead, the Is command must specify the
environment with variables and aliases. You may end up -a option to make them visible. However,
with a more efficient Bash shell. BY BRUCE BYFIELD even then, you may not see most of
them, because the modern trend is not
ash is the default command shell defines what your command line looks to install any of them by default, espe
# ~/.bashrc: executed by bash(l) for non-login shells. local/bin, /usr/bin, /bin, /usr/local/games,
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples and /usr/games. To add a directory to the
# If not running interactively, don't do anything
path called ~/sandbox/bin, you would
case S- in first define it as a path and then add it to
*i*) ;;
*) return;; the general list of paths:
esac
# don't put duplicate lines or lines starting with space in the history. PATH=$PATH:~/sandbox/bin
# See bash(l) for more options
HISTCONTROL=ignoreboth export PATH
General Tabs Appearance Scrolling Keyboard Mouse Advanced to run when Bash alias lists the aliases currently on your
opens, but to be system. Usually, aliases are stored in
Color Scheme & Background
hidden, or to store .bashrc, but they can also be stored in
New...
Breeze administrative in .bash_aliases, which is slightly more
Edit Color ...e — Konsole ? © formation at the convenient to find. Typing alias lists the
Dark Pastel
Description: New Color Scheme prompt where it is aliases currently on your system.
Green on Bl;
always easily seen.
Name Color tense col aintcolo
Linux Colors For instance, the Up Next: Bash Scripting
Foreground
default Debian When you have implemented the built-in
Red on Blad prompt conceals a customizations that you want in the Bash
Color
prompt for a chroot shell, you may want to explore Bash script
Solarized Color
jail that does not ing. Bash scripting is done in a simple lan
Vary the background color for each tab
ordinarily display. guage, and sometimes is no more than a
Blur background
The more you collection of commands entered one per
Preview: Oxygen Mono Background transparency: O','..
learn about Bash, line. A script has an .sh extension and is
Text size: 18.0 0 Select! Background image:
the more reasons run with the sh command. Learning Bash
■ Smooth fonts for customizing the scripting is beyond the scope of this article,
■ Draw intense colors in bol prompt will be but you can get a start by looking up scripts
Figure 3: You can quickly change the look of Bash using profiles in come obvious. online and modifying them for your pur
the terminal application. The prompt’s poses (sometimes this includes changing
color can also be the script’s permissions). Before long, you
user has several tabs opened - otherwise, customized. Use \e to mark the start of the may have a Bash shell far beyond the de
only the first tab’s history is saved. color definition and \e[0m to mark the fault provided during installation. ■
Another useful variable is HISTCON- end. Numbers define the prompt’s font
TROL, which takes four definitions. If weight (Table 4) and color (Table 5). So Table 5: Prompt Colors
HISTCONTROL is completed with ignore- the following line in .bashrc 30 Black
space, it deletes history listings that
32 Green
begin with a space; ignoredups deletes PSI ="/0;32m]\u $\e[0m"
duplicate commands, while ignoreboth 33 Brown
deletes both those that begin with a displays the username and dollar sign in a 34 Blue
space and duplicates. normal green font. If you use a bold weight, 35 Purple
Yet another variable, HISTIGNORE you get a lighter version of the color.
36 Cyan
takes a list of commands not to be added
Cosmetics 37 Light gray
to history. Outside of export and .bashrc,
you can also run history -cw to com Besides using number codes to color the
pletely delete the current history. command prompt, you can set the color Table 6: Coloring the
in your terminal with tput (Table 6). terminal with tput
Customizing the Prompt However, tput seems to have fallen into Area Color
The command prompt marks the latest disuse. In this desktop era, Bash’s appear tput setb [1-7] Set a background color
position in the shell from which an entry ance is usually set not in Bash, but in the
tput serf[1-7] Set a foreground color
can be made. The default prompt on terminal application through the use of
Text Weight
most systems usually has the format of profiles that set both the appearance and
USER@HOST or something similar and the behavior of the terminal (Figure 3). tput bold Set bold mode
is set with the PSI variable. A sub Profiles offer far more customization tput dim Turn on half-bright mode
prompt is sometimes set with PS2 as choices than tput or prompt codes, and tputsmul Begin underline mode
well, usually >. Typically, the prompt they are far easier to set as well. tput rmul Exit underline mode
for an ordinary account ends in $, while tput rev Turn on reverse mode
the prompt for the root user ends in #. Aliases tputsgrO Turn off all attributes
Both PSI and PS2 can include any text An alias is an alternative name for a
Colors
you want. You can also use the building command. You might create an alias for
0 Black
blocks shown in Table 3, separating each a common misspelling (e.g., typing si for
with a backslash. Why would you want to Is), as an alternative to adding to a path, 1 Red
do this? There are many reasons. If you as a way of making a command name 2 Green
usually have Bash open, then you can easier to remember, or to save typing a 3 Yellow
save space by not having a desktop clock. long command. Many distributions in 4 Blue
If you frequently refer to the Bash history, stall with the alias Is for Is -color = auto, 5 Magenta
then a prompt that refers to a command’s which colors different types of files, pre 6 Cyan
history number might be convenient. Ex sumably on the assumption that no one
7 White
perts might like a command in the prompt wants the plain Is command. Typing
—
Text pr_____
Enjoy a crash course on some of the text-processing and -filtering After I examine a few more shell tricks
in the sections that follow, I’ll return to
capabilities found in Linux. BY HAL POMERANZ this example.
$ head -13 /etc/passwd | tail -1 rw-r--r-- adjtime You can use the -F option with awk to
www-data:x:33:33:www-data:P specify a delimiter other than white
/var/www:/b in/sh space. This lets you use awk in places
That looks better! Notice the syntax with where you might normally use cut, but
In this case, I am extracting the 13th line tail here. The -n option is the alternative where you want to use awk’s conditional
of /etc/passwd, but you could easily se (POSIX-ly correct) way of specifying the operators to match specific input lines.
lect any line just by changing the nu number of lines tail should output. So, Suppose you want to output user
meric argument that is passed in to the tail -10 and tail -n 10 are equivalent. If names and home directories as in the
head command. you prefix the number of lines with +, first cut example, but only for users with
Another useful feature of the tail com as in the example above, it means start directories under /home:
mand is the -/option, which displays the with the specified line. So, here I’m tell
last 10 lines of the file as usual, but then ing tail to display all lines from the sec $ awk -F: ' ($6 ~ /A\/home\//) P
keeps the file open and displays any new ond line onward. The + syntax only { print $1 $6 }' /etc/passwd
lines that are appended onto the end of works after -n. sabayon:/home/sabayon
the file. This technique is particularly cut is wonderful for lots of tasks, but hal:/home/hal
useful for keeping an eye on logfiles - the output of many commands is sepa laura:/home/laura
for example, tail -fkem.log. rated by white space and often irregular.
The awk command is best for dealing Rather than matching against the entire
cut and awk with this kind of input: line, the command here uses the ~ op
head and tail are useful for selecting par erator pattern match against a specific
ticular sets of lines from your input, but $ ps -ef | awk P field only.
sometimes you want to extract particular '{print $1 "\t" $2 "\t" $8}'
fields from each input line. The cut com UID PID CMD sort
mand is useful when your input has reg root 1 /sbin/init Sorting your output is often useful:
ular delimiters, such as the colons in root 2 [kthreadd]
/etc/passwd: root 3 [migration/O] $ awk -F: '($6 ~ /A\/home\//) 7
{ print $1 $6 }' 7
$ cut -d: -fl,6 /etc/passwd /etc/passwd | sort
root:/root awk automatically breaks up each input hal:/home/hal
daemon:/usr/sb in line on white space and assigns each laura:/home/laura
bin:/bin field to variables named $1, $2, and so sabayon:/home/sabayon
on. awk is a fully functional scripting
language with many different capabili By default, sort simply sorts alphabeti
The -d option specifies the delimiter ties, but at its simplest, you can just use cally from the beginning of each line of
used to separate the fields on each line, the print command to output particular input. Sometimes numeric sorting is
and -/ allows you to specify which fields input fields as I’m doing here. what you want, and sometimes you
you want to extract. In this case, I’m awk also allows you to select specific want to sort on a specific field in each
pulling out the usernames and the home lines from your input with the use of input line. Here’s a classic example that
directory for each user, cut also lets you pattern matching or other conditional shows how to sort your password file by
pull out specific sequences of characters operators, which saves you from first the user ID field (useful for spotting du
by using -c instead of -/. Here’s an exam having to filter your input with grep or plicate UIDs and when somebody has
ple that filters the output of Is -I so that some other tool. For example, suppose I added illicit UID 0 accounts):
you see just the permissions flags and wanted the filtered ps output above, but
the file name: only for my own processes: $ sort -n -t: -k3 /etc/passwd
root:x:0:0:root:/root:/bin/bash
$ Is -1 I cut -c2-10,52- $ ps -ef | awk '/Ahal / P daemon:x:1:1:daemon:/usr/sbin:/bin/sh
otal 1540 {print $1 "\t" $2 "\t" $8}' bin:x:2:2:bin:/bin:/bin/sh
rwxr-xr-x acpi hal 7445 P
rw-r--r-- adduser.conf /usr/bin/gnome-keyring-daemon
rw-r--r-- adjtime hal 7460 x-session-manager The -n option indicates a numeric sort, -t
hal 7566 P specifies the field delimiter (such as cut
/usr/bin/dbus-launch -d or awk -F), and -k specifies the field (s)
Darn! The output contains the header to sort on (clearly they were running out
line from Is -I. Happily, tail will help of option letters).
with this: Here, I use the pattern match operator Also, you can reverse the sort order
(/.../) to produce output only for lines with -r to get descending sorts:
$ Is -1 I tail -n +2 I cut -c2-10,52- that start with hal < space >. The com
rwxr-xr-x acpi mand ps -ef | awk '($1 = = "hal") ...' $ Is /etc/rc3.d | sort -r
rw-r--r-- adduser.conf would accomplish the same thing. S99stop-readahead
field 2 from the first file and field 1 from 1000 dictionary.01 shell normally interprets the backslash
the second file. The complicated thing 1000 dictionary.02 as a special character. Doubling them up
about join is that it only works if both indicates that the backslash should be
files are sorted in the same order on the taken literally.)
fields you’re going to be joining the files Here, I’m splitting the file called diction Instead of converting one set of char
on. Normally, I end up doing some pre ary into 1000-line chunks (-Z1000, is actu acters to another, you can use the -d op
sorting on the input files before giving ally the default) and assigning dictionary tion simply to delete a particular set of
them to join: as the base name of the resulting files. characters from your input. For example,
Then, I want split to use numeric suffixes if you don’t happen to have a copy of the
$ join -t, -12-21 <(sort -t, 7 (-d) rather than letters, and I use wc -I to dos2unix command handy, you can al
-k2 most-populous) <(sort cities) count the number of lines in each file and ways use tr to remove those annoying
Bangladesh,7,153546896,Dhaka confirm that I got what I wanted. carriage returns:
Brazil,5,196342592,Brasilia Note that you can also specify a dash
China,1,1330044544, Beijing (-), meaning standard input, instead of $ tr -d \\r <dos.txt >unix.txt
a file name. This approach can be use
ful when you want to split the output of Or, for a sillier example, here’s a way for
The options to the join command spec a very verbose command into manage all you fans of The Matrix to get a spew
ify the delimiter I’m using «) and the able chunks (e.g., tcpdump | split -d -I of random characters in your terminal:
fields that control the join for the first 100000 - packet-info).
(-1 2) and second (-2 1) files. Once $ tr -d —c [:print:] </dev/urandom
again, I’m using the < (...) Bash syn tr
tax, this time to sort the two input files The tr command allows you to transform Here I’m using [:print:] to specify the set
appropriately before processing them one set of characters into another. The of printable characters, but I’m also em
with join. classic example is mapping uppercase ploying the -c (compliment) option,
The output isn’t very pretty, join out letters to lowercase. For this example, to which means all characters not in this
puts the joined field first (the country transform the capitals file I used previ set. Thus, I end up deleting everything
name), followed by the remaining fields ously, I’ll use: except the printable characters.
from the first file (the ranking and the
population), followed by the remaining $ tr A-Z a-z < capitals Conclusion
fields from the second file (the capital a This has been a high-speed introduction
city). The cut and sort commands can b to some of the text-processing and -filter
pretty things up a little bit: ing capabilities in Linux, but of course it
really only just scratches the surface.
$ join -t, -12-21 <(sort -t, 7 Lots of sites on the Internet have more
-k2 most-populous) <(sort cities) | 7 But this is a rather silly example. A more examples and ideas for you to study, in
cut -d, -fl,3,4 | sort -nr -t, -k2 useful task for tr is this little hack for cluding shelldorado.com, command-
China,1330044544,Beij ing looking at data under/proc: linefu.com, and the weekly blog I co-au
India,1147995904,New Delhi thor with several friends at blog.com-
United States,303824640,Washington D.C. $ cd /proc/self mandlinekungfu. com.
$ cat environ The online manual pages can help a
GNOME_KEYRING_SOCKET=/tmp/7 lot too - and don’t forget man -k for
Examples like this are where you really keyring-lFz8t4/socketLOGNAME7 keyword searches if you’ve forgotten a
start to get a sense of just how powerful =halGDMSESSION=default... command name or just aren’t sure
the text-processing capabilities of the op $ tr \\000 \\n <environ where to start! But, really, the best
erating system are. GN0ME_KEYRING_S0CKET=/tmp/P teachers are practice, practice, and prac
keyring-lFz8t4/socket tice. I’ve been using Unix and Linux
split L0GNAME=hal systems for more than 20 years, and I’m
Joining files together is all well and GDMSESSION=default still learning things about the shell
good, but sometimes you want to split command line. ■
them up. For example, I might split my
password-cracking dictionary into Typically, /proc data are delimited with Hal Pomeranz is the Founder and
smaller chunks so that I can farm out the nulls (ASCII zero), so when you dump CC Technical Lead of Deer Run Associ-
processing across multiple systems: /proc to the terminal, everything just o ates, an IT and Information Security
J consulting firm. He is also a Faculty
runs together, as shown in the output of Fellow of the SANS Institute and the
$ split -d -1 1000 dictionary 7 the cat command above. By converting course developer and primary instruc-
dictionary. the nulls (\000) to newlines (\n), every iii tor for their Linux/Unix Security certi-
$ wc -1 * thing becomes much more readable. X fication track (GCUX). And, yes, he
98569 dictionary (The extra backwhacks (\) in the tr com could replace you with a very small
shell script.
1000 dictionary.00 mand here are necessary because the
J 9 9 |
HARDWARE HELP W
Learn about some command-line tools for discovering and configuring hardware. \
n the early days of Linux, drivers in IDE interfaces, which can include sound use increasingly unnecessary. You may
nanday
description: Desktop Computer
product: MS-7693 (To be fitted by O.E.M.)
vendor: MSI
version: 4.0
serial: To be fitted by O.E.M.
width: 64 bits
capabilities: smbios-2.8 dmi-2.8 smp vsyscatt32
configuration: boot=normat chassis=desktop famity=To be fitted by O.E.M. sku=To be
fitted by O.E.M. uuid=00000000-0000-0000-0000-4CCC6A250851
*-core
description: Motherboard
product: 970 GAMING (MS-7693)
vendor: MSI
physical id: 0
version: 4.0
serial: To be fitted by O.E.M.
slot: To be fitted by O.E.M.
★-firmware
description: BIOS
vendor: American Megatrends Inc.
physical id: 0
version: V22.4
I
Figure 1: Ishw summarizes the hardware on the system.
filename: /lib/modules/4.9.0-8-amd64/kernel/drivers/usb/host/ehci-pci.ko
license: GPL
author: Alan Stern
author: David Brownell
description: EHCI PCI platform driver
alias: pci:v0000104Ad0000CC00sv*sd*bc*sc*i*
alias: pci:v*d*sv*sd*bc0Csc03i20*
depends: usbcore,ehci-hcd
retpoline: Y
intree: Y
vermagic : 4.9.0-8-amd64 SMP mod_unload modversions
[BiDM
Figure 2: modinfo lists the options for a module.
processor : 0
vendor.id : AuthenticAMD
cpu family : 21
model : 2
model name : AMD FX(tm)-8350 Eight-Core Processor
stepping : 0
microcode : 0x600084f
cpu MHz : 1400.000
cache size : 2048 KB
physical id : 0
siblings : 8
core id : 0
cpu cores : 4
apic id : 16
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat ps
e36 ciflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr.opt
_ pdpelgb rdtscp Im constant
_tsc rep_good nopl nonstop.tsc extd_apicid aperfmperf pni pcimulqdq monitor ssse3 fma
cx!6 sse4_l sse4_2 popcnt aes xsave avx fl6c lahf_lm cmp_legacy svm extapic cr8_legacy
oot@nanday:/sys/fs/ext4/sdal# Is
lei ayed_allocation-blocks last_error_time mb_st ream_req
r rors_count I ifetime_write_kbytes msg_ratelimit_burst
rr_ratelimit_burst max_writeback.mb_bump msg_ rat elimit-interval_ms
r r_ratelirnit.interval.ms mb_group_prealloc reserved-dusters
xtent_max_zeroout_kb mb_max_to_scan session-write.kbytes
irst_error.time mb_min_to_scan trigger.fs_error
node.goal mb_order2_req warning.ratelimit_burst
node,readahead blks_____ mb_stats_______________ warning,ratelimit_interval_ms
Figure 4: The subdirectory names in /sys give detailed information. Here, the characteristics of an ext4 drive are displayed.
The sysctl utility is designed specifically • Shell variables (written in capital let • If these scripts run as root, they have
to work with /proc and /sys. ters and with no spaces), like BLUE the potential to destroy your system if
TOOTH-ENABLED = 1 in /etc/default/ you add the wrong command or acci
Working with Traditional bluetooth dentally activate a command that is
Configuration Files • Comments explaining what each vari supposed to be commented out. To
Although systemd is today the norm for able means prevent accidents, always backup a
launching services at boot time, there • Shell functions (sometimes) to extend configuration file before editing it.
are still services, traditionally called or override features in existing scripts • Scripts are usually called with an “in
“daemons,” that are shell scripts. Distri In Debian-based systems, most of these clude” to another script by the dot (.)
butions use shell-like configuration files config scripts are placed in /etc/default/* shell command, and the calling script
to configure these services easily, with and can be edited in a text editor as root will terminate if an exit appears.
out having to invent a new syntax for (Figure 5). • In the shell, no spaces are allowed be
each configuration. You can usually rec If you make changes to any system shell fore and after the equal sign (=) when
ognize these configuration files because script or write your own system scripts, setting variables. KDE and Gnome con
they have: please keep the following facts in mind: fig files frequently have spaces every
root@nanday:/etc/default# Is
acpid bsdmainutils gdomap locale rsyslog
amd64-mic rocode cace rt 5 google-talkplugin minidlna saned
anac ron console-set up grub minissdpd sma rtmontools
apache-htcacheclean c r da halt mysql spamassassin
apt-firewall cron hddtemp networking speech-dispatcher
avahi-daemon dbus ht dig nfs-common t imidity
bacula-dir devpt s hwcloc k nss tmpf s
bacula-fd ebtables intel-microcode openvpn uf w
bacula-sd exim4 irqbalance rcS useradd
bluetooth firebird2.5 keyboard r sync virtualbox
Figure 5: /etc/default contains configuration files that run as scripts.
root@nanday:/etc/systemd# systemd-delta
[EXTENDED] /Iib/systemd/system/rc-Iocal.service -* /lib/systemd/system/rc-local.servi
[EXTENDED] /Iib/systemd/system/systemd-timesyncd.service -* /Iib/systemd/system/syste
[OVERRIDDEN] /usr/Iib/systemd/system/wacom-inputattach@.service -» /lib/systemd/system/
DISK MAGIC
We show how to prepare a hard disk for the filesystem.
The program writes its output to the screen
and provides a command prompt but does
not provide paging (e.g., less), so you
might need to scroll up to read lengthy out
put. Entering m at the prompt lists the
available fdisk commands. From the main
menu, you can create new partitions (n),
BY NATHAN WILLIS, HANS-PETER MERKEL, AND BRUCE BYFIELD delete existing partitions (d), verify the
partition table (v), and set several flags
hard disk on a modern computer is limiting). The Unified Extensible Firm (the most notable being the bootable flag,
puts a security prompt and then creates a many common filesystems, including need to duplicate a partition in a new loca
GPT table. The n option lets you create a ext4, FAT32, NTFS, JFS, UFS, XFS, and tion, perhaps to move a partition to a new
new disk-sized data partition. The w op Linux swap. The start and end parameters device in an attempt to free up space. At
tion writes the data (saves your changes) specify the location of the new partition the Parted prompt, use
from the gdisk session. on the disk; you do not have to use drive
Gdisk can convert MBR-partitioned geometry such as sectors, but you can cp </original/device> 7
hard disks to GPT, which removes the provide human-readable sizes expressed < ori ginalPart it ion> <t argetPart ition>
need to back up and restore existing par in megabytes.
tition content. Choosing r sends you to To remove a partition, use parted </some/ where /original/device is optional; if
the recovery and transformation menu, device> rm <N>, where <N> is the parti omitted, the current working device will
which offers options for converting your tion number. be assumed. Thus, the command
MBR disk to GPT. Gdisk can also convert Parted really improves on fdisk in its
from GPT to MBR. In some cases, this ability to move and resize partitions. For cp /dev/sdb 5 1
option will not work, so be sure to back variety’s sake, start Parted in interactive
up your data if you try it. mode before exploring partition manipu copies the/dev/sdb5 partition to/dev/hdbl.
lation. You still need a drive device ar If you accidentally delete a partition
GNU Parted gument, such as from the partition table or overwrite the
Fdisk is one of the older Linux tools, and partition table itself, entering
Gdisk is modeled after it. Increasingly, parted -i /dev/hdb
many users prefer GNU Parted. rescue <start> <end>
You can run parted in interactive or While in interactive mode, the device
non-interactive mode. The non-interac- given as an argument is assumed; you do initiates a search for filesystem signa
tive syntax is parted </some/device> not need to include it in the commands tures on the disk. Parted searches a range
<command>. Running the command you type. To switch to a different device of sectors around the start and end posi
within interactive mode, type tions for signs of the filesystem, so you
parted /dev/sda print do not need to be exact. If it finds a po
select </some/other/device> tential filesystem in the appropriate loca
prints the partition table found on the tion, Parted asks whether you want to
/dev/sda disk (Figure 2). The information at the Parted command prompt. create a new partition. For this rescue to
displayed is similar to fdisk’s. The resize command takes three argu work, the filesystem must be more or less
Providing the -i flag before the device ments: the partition number, the new intact; Parted can only recreate partition
and command arguments launches start location of the resized partition, and table entries - to fix filesystem corrup
parted in interactive mode. Unlike fdisk, the new end location. To continue the tion, you need other tools.
however, you can create and modify par above example, running
titions in non-interactive mode as well. The LVM Alternative
One important difference between resize 1 0 1000 A Logical Volume Manager (LVM) is an
parted and fdisk and gdisk is that parted alternative to traditional partitioning that
commands take effect immediately; that at the prompt would resize the partition at treats the space on one drive - or even
is, when you create a new partition table, /dev/hdbl to begin at the start of the drive multiple drives - as a single unit and di
the existing partition table (if any) on the and end at the 1000MB mark. vides it into logical volumes. GNU Parted
target drive is overwritten. This leaves lit You can use Parted both to grow and also works with LVMs.
tle margin for error when working with a shrink partitions. However, for ext2/3 file The use of LVMs may come at a price:
drive that has existing partitions and can systems, you cannot change the start loca Should a drive become corrupt, your en
leave you hunting for recovery tools (for tion with a resize command, only the end. tire system suddenly can be inaccessible.
tunately, Parted can assist in that task, as That restriction does not apply to the By contrast, if you use traditional parti
well). The command other filesystems that Parted supports. tions, especially for /home, you might be
Parted can move a partition to a new able to recover data by booting from a
parted </some/device> mklabel <type> free location on a drive with the move Live device after the root or boot parti
command. The syntax is tion crashes. You should research the dif
creates a new partition table on the speci ferences between LVMs and traditional
fied device. You must specify the partition move <partitionNumber> <start> <end> partitioning carefully before deciding
table type; for Linux, a widely used type which to use. ■
is msdos, although Parted supports several although <end> is
others. To create a new partition, use: optional. If omit
File Edit View Terminal Help
ted, the partition is magazine@HacBuntu:~S sudo parted /dev/sda print
parted </some/device> P moved to the new [sudo] password for magazine:
Model: ATA Hitachi HTS54505 (scsi)
mkpart <partition_type> P location in its origi Disk /dev/sda: 590GB
Sector size (logical/physical): 512B/512B
<filesystem_type> <start> <end> nal size. If an end Partition Table: gpt
ing point defines a
Number Start End Size File system Name Flags
where partitionjtype is primary, extended, new size for the 1 20.5kB 210MB 210MB fat32 EFI System Partition boot
2 210MB 393GB 393GB hfs+ Untitled
or logical. For primary or logical parti partition, Parted 3 393GB 394GB 1094MB ext3
tions, you must also specify filesystem_ automatically re 6 394GB 394GB 1000kB bios grub
7 394GB 448GB 54.2GB ext4
type, the filesystem format that the par sizes as well as 8 448GB 451GB 2358MB linux-swap(new)
tition will hold. moves it. 4 451GB 500GB 49.3GB ext3
5 500GB 580GB 181MB linux-swap(new)
However, the mkpart command does When shuffling
magazine@HacBuntu:~$ |
not actually create the filesystem. To do and resizing parti
so, use mkpartfs instead. Parted supports tions, you might Figure 2: Listing the partition tables with parted.
Configuring filesystems with mkfs, df, du, and fsck mkfs -t ext4 /dev/sdal
BUILDER
inode parameters, and all other options,
some of which are determined at run time
when mkfs analyzes the geometry of the
disk partition. Using
Although most Linux distributions today have simple-to-use graphical mkfs -t ext4 -b 4096 /dev/sdal
interfaces for setting up and managing filesystems, knowing howto also creates an ext4 filesystem on /dev/
perform those tasks from the command line is a valuable skill. We'll sdal, but it forces the use of 4096-byte
blocks. Running
show you how to configure and manage filesystems with mkfs, df,
du, and fsck. BY NATHAN WILLIS mkfs -t ext4 -b 4096 7
- J device=/dev/sdbl /dev/sdal
inux supports a wide array of file where < filesystem_type > is a Linux- creates the same filesystem as the pre
Media access with mount and fstab A number of optional parameters aside,
you have to specify the device file and the
MOUNT UP
mountpoint. If you call mount without
supplying any parameters, the command
tells you, among many other things, which
media are currently mounted (Listing 1).
Additionally, mount tells you about
We examine tools for mounting and unmounting storage media.
the filesystems for the devices, and it lets
BY HEIKE JURZIK AND JOE CASAD you know what mount options are in
access to various devices and filesys place. The /dev/sdal partition has been
inux attaches media directly to the
L
tems, you need to create a link between formatted with ext4 and mounted as the
directory tree in a process known as
a device and a directory in the filesys root partition (at /); the CD drive con
mounting. Device files for devices
tem tree. The mount command (or the tains ISO 9660 media (the default filesys
of all kinds - network, removable media,
equivalent systemd mount process) as tem for data CDs) and has been
hard disk partitions - can typically be
sociates a device with a directory. mounted under /media/cdromO.
found below the /dev (device) directory.
The listing also tells you if the hard
Many modern Linux systems handle the Mounting disk partitions are readable and writable
mounting process automatically. Your hard
Mounting occurs at boot time or manu (rw for “read-write”). The information
drives, CDs, and USB sticks just appear in
ally at a later stage. Hard disk partitions
the desktop GUI, and you can navigate errors=remount-ro
are normally mounted at boot time;
to the data without the need for explicit
USBs, CDs, DVDs, and other removable ensures the media will be remounted
mounting commands; however, the classic
media used to be mounted manually read-only; that is, the data will be read
Unix/Linux mount system is still useful for
and were often in the domain of the able but with no write access.
troubleshooting or when working with
system administrator (root), unless the
systems that don’t offer udev support.
privilege was specifically given to users Mounting Removable Media
This article describes how to mount
(see the section titled “Tabular: /etc/ Data CDs/DVDs, floppy disks, and USB
and manage storage resources using
fstab"). Nowadays, most of these de media are normally mounted automati
mount, amount, and the fstab file. Sys-
vices are autodetected and are mounted cally when you plug them in. If your
temd environments offer an alternative
automatically or at a user prompt. system does not automount or you’re
option for mounting using systemctl (see
However, if you have trouble or need working on the console, run mount
the box entitled “Mount and Systemd”).
a little more control, the utility used to manually. Linux assigns directories
Name Game mount from the command line is mount. below /mnt or /media for removable
IDE device names (names of hard disks,
CD-ROMs, or DVD drives) start with sd Mount and Systemd
(the “s” refers to the SATA interface used The systemd init environment used on the file - with hyphens replacing
for most modern mass storage); the let most modern Linux systems lets you cre slashes. For example, if the mount point
ter that follows depends on the connec ate a systemd unit file and then reference is /media/backup, the name of the unit
tor and the order. The first drive is sda, the file to mount the resource. See the file must be media-backup.mount.
the second sdb and so on. "Systemd" article for more on creating a The format for an automount unit file is
Linux handles USB mass storage de systemd unit file. similar, systemd.mount and systemd.
vices, SD cards and so on as SCSI de Systemd supports both the mount [1] and automount support several other unit
vices. Their device filenames also starts automount units [2]. A mount unit mounts file options. See the documentation on
when executed (either at startup or manu line [1 ]. Once you create the unit file, you
with sd. CD and DVD drives tend to be
ally from the command line). An automount can mount and manage the resource
listed as sr, and floppy disk drives are fd. unit automounts on demand when a user using systemctlcommands:
Besides the letters, many devices attempts to access the resource. As with
# systemctl daemon-reload
have numbers that reflect the logical other systemd units, the extension on the
# systemctl start unit_file_name
structure of the storage media (e.g., the filename indicates the file's purpose. For ex
first primary partition on an SATA hard ample, the filename for a mount unit would You can also use the systemd-mount com
have the form: unit_file_name.mount. mand to mount the resource, or use sys-
disk attached to the first controller is
A mount unit file should contain a [Mount] temd-umountto unmount.
sdal, the second partition is sda2, etc.).
section with the following basic options: Systemd continues to support the/etc/
Logical partition numbers start at 5.
• W/?ar=-path, partition name, or UUID fstab file as described in this article. The
The second logical partition on sdc thus fstab file serves as an alternative means
maps to the device file /dev/sdc6. for a device, partition, file, or other re
source you wish to mount for configuring mount units in systemd.
The system enumerates SCSI CD/DVD Mounts listed in fstab will be converted
• Where=-absolute path of the mount
drives in the same way (srO, srl, etc.), to native systemd mount units at
point
along with floppy drives (fdO, fdl, etc.). startup. Recent Linux systems include
• Type=- (optional) the filesystem type some additional fstab mount options
Many distros use aliases such as /dev/
You must name the mount unit file for that will pass unit file settings directly
cdrom or /dev/dvd that point to the
the path to the mount point specified in to Systemd [3].
names for CD/DVD drives. To support
media. In the command line, you need Combinations are also supported: To re automatically dismounts mounted media
to type the device file name and the move write access for media mounted with at shutdown, you can also unmount de
mountpoint. read-write access, supply two parameters vices manually, including removable CD-
When you mount a USB mass storage when running the command; for example, ROMs/DVDs, floppies, and USB devices:
device, check the /var/log/messages or
mount -o remount,ro /media/usb amount /media/usb
/var/log/kern.log logfiles to see if the de
umount /media/cdromO
vice has been detected correctly and to tells mount to remount the media and at
discover the device file name. To mount the same time disable write access (ro). USB media and floppies must be un
the device detected, sdc, in an existing To test an ISO by mounting a 1:1 copy mounted before you remove them. CD
directory, /media/usb, type: of the image before burning, enter: and DVD drives block automatically
and refuse to open the drive bay while
mount /dev/sdcl /media/usb mount -o loop file_name.iso /mnt/tmp a disk is mounted.
Linux typically autodetects the filesys which uses a loop device to access the An additional safety mechanism is
tem type for media. If you get an error image. that umount will not unmount a filesys
message, you can explicitly specify the tem while a process is accessing the
filesystem by supplying a value for the Tabular: /etc/fstab files. A program might be using the data
-t parameter - for example, Linux mounts some filesystems directly at on the CD in the drive, or the data might
boot time. The /etc/fstab file (see Figure 1) be part of the working directory used by
mount -t vfat /dev/sdcl /media/usb has entries for the filesystems to mount. the shell or a file manager (i.e., /media/
The fstab file used to contain config cdromO) or one of its subdirectories. To
for an older Windows filesystem on FAT-
uration information for the full set of determine which process is blocking the
formatted media. Besides vfat (for the
hard disk partitions in addition to the device, run Isof, which displays open
DOS/Windows filesystem), the sup
various removable media. But, remov files and directories, as root against the
ported values are ext2 (extended filesys
able media are now managed by the device name of the drive, as in Listing 2.
tem version 2), ext3 (extended filesys
udev subsystem, which allows regular If Isof does not tell you what the com
tem v3), ext4 (extended filesystem v4),
users to mount and unmount them mand is, it will tell you the PID (process
reiserfs (Reiser filesystem), iso9660 (ISO
from the command line or desktop. number). You can then use the ps tool
9660), ntfs (NT filesystem), and so on.
The first column is the device file, and output a list of all processes in wide
Most systems define the device names
UUID, or label, and the second is the display mode, pipe the output to grep,
and mountpoints for CDs/DVDs and and search the output for the process ID:
floppies, so a command such as mountpoint. The other entries specify
the filesystem for the media (the kernel ps auxwww | grep 23884 7
mount /media/cdrom normally autodetects this - auto), and paul 23884 0.3 1.2 804532 7
might be all it takes to mount a CD. various mount options. 76544 ? SI 22:36 0:00 7
Often you see entries such as user /usr/bin/gwenview /run/media/
Critical Mount Options (the device can be mounted without paul/Ubuntu 15.04 amd64/P
The -o ro option for mount makes a device root privileges), nouser (the opposite), ubuntu/pics/blue-lowerleft.png 7
“read-only.” Its counterpart, as well as the auto (mounted at boot time), noauto, -caption Gwenview —icon gwenview
default setting, is -o rw (for “read-write”). exec (executable), or noexec. If you
In this case, it looks like Gwenview is
want to modify the /etc/
the culprit. If you close the image viewer
fstab file, you must be
window showing the pictures on the CD
come root.
content, you should be able to unmount
Out! the CD with:
To unmount filesystems, umount /media/cdromO
use the command
amount. Although Linux If this command doesn’t help, you might
have to be more assertive and use the
kill command. ■
Zdev/disk/byid/ata-ST9750-l23AS_6WS0Q7JM-part 1 swap defaults
Zdcv/dlsk/by-ld/ata-si9ZbH423AS_6wsev7JM-part2 Z acl,user_xattr
Zdev/diskZby-idZata-ST9750423AS_6WS0Q7JM-part3 Zhoae
proc
sysfs INFO
debugfs ZsysZkcrnelZdcbug
ZprocZbusZusb [1] systemd.mount:
devpts Zdev/pt s node=0620,gid=5
ihora:Zho«eZlnmsZcommon ZhomeZpaulZDocumontsZZcomnon nfs rsize=Bifl2,w»ize=ai02,nosuid o o
https://www. freedesktop. org/software/
zhorcZhoaeZlnms ZhomcZpaulZbocumentsZZlnms nfs rsize=8i92,wsize=8192,nosuid o o systemd/man/s ystemd.mount.html
Figure 1: The fstab file provides information on hard disk partitions. [2] systemd.automount: https://www.
freedesktop. org/software/systemd/
man/systemd. automount.html#
Listing 2: Isof/dev/sdd1 [3] systemd.mount Manpage with fstab
# Isof /dev/srO Mount Options: https://manpages.
COMMAND PID USER FD TYPE DEVICE SIZE/0FF NODE NAME debian.org/testing/systemd/systemd.
gwenview 23884 paul cwd DIR 11,0 2048 4096 /run/media/paul/Ubuntu 15.04 amd64/pics mount.5.en.html
TIME WARP
I'm late, I'm late, for a very important date. For many
time and time zone. We'll show you howto keep your PC
n incorrectly set PC clock can be process of setting the clock by synchro -y flag produces a year calendar (Fig
you will see the date, time, and also the July August September
Su Mo TuWe Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo TuWe Th Fr Sa
time zone: 1 2 3 4 5 6 12 3 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21
$ date 21 22 2324 25 26 27 18 19 20 21 22 23 24 22 23 2425 26 27 28
Tue Feb 19 15:23:41 CST 2019 28 29 3031 25 26 27 28 29 30 31 29 30
command. Check your /usr/share/zo- Figure 2: With Cal, you can display a calendar for the whole year at the console.
neinfo/ directory to find out which time
zone values your computer supports $ TZ=America/New_York date (man date) for a complete list of the
with TZ. Tue Feb 19 16:27:24 EST 2019 options.
To find out the time in New York, for These formatting options are particu
example, you simply run the following If you happen to live in Australia and larly practical if you use date to generate
command: need to phone friends in New York on a file names made up of date, time, or
regular basis, you might want to set up both values automatically.
Table 1: Date Command- an alias for the last command to make it The command
Line Parameters easier to check the time before you call.
Meaning
To set up an alias, just add the follow tar -cvjf backup_$P
Parameter
ing line to your Bash configuration file, (date +%d_%m_%Y).tar.bz2 *
%M Minutes (00 to 59)
~/.bashrc
%H Hours, 24-hour clock creates a Bzip2 compressed tarball
%l Hours, 12-hour clock alias NY=1TZ=America/New_York date1 with a name comprising the text string
%a Weekday, short form backup_, the date (that is the day,
and re-parse the settings after saving them month, and year separated by under
%A Weekday, long form
by giving the source ~/.bashrc command. lines), and the file extension .tar.bz2 (for
%d Day as two-digit number Then, you can simply type NY at the com example, backup_05_ll_2009. tar. bz2).
%b Name of month, short form mand line to output New York time.
%B Name of month, long form
Setting the System Time
Formatted Output The root user can use date to set the time
%m Month as two-digit number
The date program has a large number and date for a machine. To do so, use the
%y Year as two-digit number of parameters that influence the output -s option followed by a string that con
%Y Year as four-digit number format. You can format the date output tains the new time (see the next section,
%D Four-digit date (mm/dd/yy) with a plus sign, followed by a percent “Everything is Relative”). Before you
sign, and a letter. For example: enter the following command, make sure
%T Time in 24-hour clock
that all NTP components have been unin
%r Time in 12-hour clock $ date +%Y_%m stalled (see the “Automated” section):
%t Tabulator 2019_02
%n Line break # date -s "19 Feb 2019 16:20"
Table 1 lists some of the more common # date
°/o% % sign
options; you can refer to the man page Tue Feb 19 16:20:03 CST 2019
Everything Is Relative
As an alternative to the absolute date
and time, the date tool also under
stands relative values and even has a
couple of predefined strings to help
you:
• yesterday
• tomorrow
• today
• now
• sec{s)/second (s)
• min{s) /minute{s)
• hour{s)
• day(s) Figure 3: To access documentation conveniently, use the info command at the command line.
• week{s) This information is the output of 'info coreutils date'.
• fortnight
• month{s) The hwclock program lets you read Internet, or you could use a manual
• year{s) and set the hardware clock; the com command in the shell.
Additionally, date understands concepts mands all require root privileges. When In the pre-Systemd era, most major
such as ago, so you can say day ago in used in combination with the -r option, Linux distributions had packages
stead of yesterday. you can display the local hardware time: available for enabling NTP support.
If you use one of these strings to set Many of those packages still exist -
the time, you must specify the -s para # hwclock -r see the documentation for your own
meter like so: 2019-02-19 15:44:09.49830-0500 Linux distribution to learn about NTP
package options.
# date -s '+3 mins' Additionally, hwclock has options for Systemd provides a built-in sys
setting the system time to reflect the temd-timesyncd service that performs
To display a relative time, you need the hardware clock time {hwclock -s) or vice basic time synchronization duties. To
-d parameter instead: versa {hwclock -w). check whether the service is running on
A combination of -set and -date sets your system, enter:
# date -d '+S days -2 hours' a specific time. You need to enter a string
Sun Feb 24 13:14:18 CST 2019 to describe the new date and time after systemctl status P
the -date parameter. The format is ex systemd-timesyncd.service
The date information page tells you actly the same as the date program’s -s
more about strings and how to use option. The command The systemd-timesyncd service is like
them. To read the documentation at the other Systemd services. You can start,
command line, use info coreutils date # hwclock —set --date="+2 hours" stop, or restart it using a variation of the
(see Figure 3). systemctl command:
sets the hardware clock to a time two
Setting the Hardware Clock hours in the future. systemctl restart P
In addition to the software clock, your systemd-timesyncd.service
computer has another timekeeper, and Automated!
this one will continue to count down Network Time Protocol (NTP) is a stan See the article on Systemd elsewhere in
the days when your computer is dard for automating the synchronization this issue, or consult the systemctl man
switched off and even when it is not of clocks in computer systems [1]. The page, for more on managing Systemd
plugged in. time signal propagates over the network services. ■
To ensure uninterrupted timekeeping, from an NTP server to a client, and you
computer mainboards have a battery- can configure the point in time when INFO
buffered clock, referred to as the CMOS your Linux machine’s NTP client con [ 1 ] NTP: http://en. wikipedia.org/wiki/
clock, RTC (Real-Time Clock), BIOS tacts a server on the network. This could Network- Ume_Protocol
clock, or even hardware clock. be at boot time or when you get onto the
INTED!
sixth field, can still list the user’s shell,
but /sbin/nologin is more likely to be en
tered than in the pre-systemd days.
The /etc/shadow file has preserved its
original functionality (Figure 2). The
T. . „ ... . . . , .
The shell comes with some simple commands for managing first field in each line is the username,
and the second is the encrypted pass
users and granting access to system resources.
word - or a placeholder if the user can
BY MATT SIMMONS, JOE BROCKMEIER, HEIKE JURZIK, not log in. The third through fifth fields
BRUCE BYFIELD, AND JOE CASAD are used for controlling passwords -
showing the age of the password, the
minimum age before the password can
sers and groups are concepts Files for Users and Groups be changed, and the maximum time be
passwd USER, authenticating with the use finger, adding a user after the com
root:x:0: current password before changing it. mand for specific information.
daemon:x:1: If you want to disable a user account As you edit an account,
bin:x:2: rather than delete it, the easiest solution
sys:x:3: is the command usermod OPTIONS USER
On this basis, you can see, for exam chown petronella:audio FILE_NAME it (including the hidden configuration
ple, 644 would mean u = rw,go = r (re files) to user pooh:
sulting in rw-r-r--), or 777 would be The file now belongs to user petronella
a = rwx (resulting in rwxrwxrwx). and group audio. chown -R pooh /home/pooh
To set the s or t bit, you need to add a chown is mainly used by the root
fourth number at the start of the block of user, however, an ordinary user can use From the Beginning
three. The number 4 represents the s bit it for certain limited tasks, such as The umask program specifies the default
for the owner (setuid), 2 sets the 5 bit for changing the group membership for a permissions assigned to newly created
the group (setgid), and 1 sets the t bit. file the user owns to a group to which files and directories. Typing the umask
Listing 2 gives an example. the user belongs. command without setting any parame
ters reveals the current setting:
Changing Group Across the Board
Memberships All three tools - chmod, chgrp, and $ umask
To change group membership for files chown - support the -R option for recur 0022
and directories, you can use the chgrp sive actions. If you want members of the
tool. As a “normal” user, you are al video group to access a directory and the The four-digit octal number that is re
lowed to assign your own files to a spe files it contains, just type: turned specifies what to subtract from
cific group; however, this assumes that the default values (0666 for files, 0777
you are a member of the group. The root chgrp -R video DIRECTORY for directories). In other words, new files
user, as always, has no restrictions. are assigned 0644 (rw-r- -r- -), and new
The following command tells you your The -R option can also save you some folders are assigned 0755 (rwxr-xr-x)
own group memberships: typing in combination with the chmod when they are created.
command. To remove read, write, and To change the umask, enter the file
$ groups execute permissions from this folder for and specify the new value at the com
petronella adm dialout fax cdrom 7 all users who are not the owner or mem mand line:
tape audio dip video plugdev fuse 7 bers of the video group, just type:
Ipadmin netdev admin sambashare umask 0077
chmod -R o-rwx DIRECTORY
In this case, the user called petronella This entry means that new files and direc
may change access to her own files for Be careful when you run recursive tories are only available to their owner. To
members of the groups petronella, adm, commands that remove the execute make new files writable for group mem
dialout, fax, cdrom, and so on. The flag. If you mistakenly type a-x instead bers, you can choose umask 0002 instead.
chgrp command first expects information of o-x, you will lock yourself out: The umask you assign in this way is
about the new group and then the name chmod will remove execute permissions valid for the current shell, but you can
of the file or directory. To assign a file to from the parent directory and your abil add an entry to your Bash configuration
the audio group, just type: ity to change the directory and modify file ^/.bashrc to make the change perma
files (Listing 3). The use of the find nent. Don’t forget to run source ~/.bashrc
chgrp audio FILE_NAME command can help you avoid this kind to reload the Bash configuration file.
of dilemma (Listing 4). The find com To modify the umask for the system,
Changing Owners and mand first discovers the files (-type f) you will need to add a global entry to the
Groups in the test directory (and possible sub /etc/profile file, and you will need to
On a Linux system, the system adminis folders) and then runs chmod against work as root to edit it. ■
trator is allowed to assign new owners them, ignoring the
and new groups to files and directories. directory itself. Listing 3: Oops ... Locked Out!
To give a file to user petronella, simply To use the -R pa $ Is -1 test
use the chown command: rameter with the total 0
chown program, -rwxr-xr-x 1 petronella petronella 0 Nov 4 12:12 bar
chown petronella FILE_NAME you would enter -rwxr-xr-x 1 petronella petronella 0 Nov 4 12:12 foo
the following com
$ chmod -R a-x test
Also, you can define a new group in the mand to hand over
chmod: cannot access 'test/bar': Permission denied
same command. To do so, add the name the home directory
chmod: cannot access 'test/foo': Permission denied
of the group after a colon: and all the files in
Listing 2: Setting the s Bit by Number Listing 4: Using the find Command
$ Is -1 script.sh $ find test -type f -exec chmod a-x \{\} +
-rw-r—r— 1 heike heike 3191789 Oct 6 05:01 script.sh $ Is -1 test
$ chmod 4755 script.sh total o
$ Is -1 script.sh -rw-r—r— 1 petronella petronella 0 Nov 4 12:12 bar
-rwsr-xr-x 1 heike heike 3191789 Oct 6 05:01 script.sh -rw-r—r— 1 petronella petronella 0 Nov 4 12:12 foo
SPECIAL PRIVILEGES
the root account (Figure 1).
When you use the basic su command,
you change accounts but do not com
pletely change your environment. To
Su and sudo give you a limited login to other accounts. Both commands be specific, only the $HOME, $SHELL,
play a role in Linux security by minimizing the time you'll need access $USER, $LOGNAME, $PATH, and $IFS
environment variables are reset. De
to the root account. BY BRUCE BYFIELD
pending on how su was compiled,
$TERM, $COLORTERM, $DISPLAY, and
inux and other Unix-like systems conventional logins. Similarly, developers $XAUTHORITY may also be reset.
However, whereas su requires the root Figure 4: Query /etc/sudoers to learn what commands you can run.
When you are finished, visudo checks Avoiding Self-Sabotage the bare minimum, but that doesn’t mean
for errors, giving you the chance to cor Like much of Linux, su and sudo can be you can relax other precautions.
rect them or go ahead and save to the as simple or as complex as you choose. Specifically, avoid using su to become
original file. Be careful before you save - Most popular uses of sudo, in particular, root and then keeping a terminal open
syntactical errors can prevent sudo from are extremely basic, and by copying and forgotten on some overlooked vir
working properly, or even at all. them, you can quickly get up to speed. tual workspace. Similarly, reduce the
The top of the sudoers file sets aliases However, when you use su and sudo, be time that a successful sudo login lasts to
for advanced configuration. Aliases can careful that you do not undermine their the minimum. Consult system logs to
be used for such purposes as creating purpose. The entire point of both com ensure that the powerful su and sudo
comma-separated lists of users or com mands is to increase security by minimiz commands are only used for authorized
mands to simplify configuration. For ex ing the time you run as root. Both com activities. (Also see the box titled “The
ample, if you want to restrict who can mands can reduce your time as root to Administrator Sees Everything.”) ■
power off the system or network, add
the following line to create the command
alias SHUTDOWN:
Cmnd_Alias SHUTDOWN P
= /sbin/halt, /sbin/shutdown, P
/sbin/reboot, /sbin/poweroff
SYSTEMD
to initialize and start units at boot time
are known as unit files. Admins will find
the unit files in folders such as:
• /etc/systemd/system/*
• /run/systemd/system/*
PRIMER • /usr/lib/systemd/system/*
Unit files serve a role that is similar to
the init scripts of older Linux systems;
however, a unit file is not executable. In
stead, a unit file is more like a configura
Systemd manages the services on most Linux systems. We'll show you tion file in the style of Windows .ini
files. A quick look at the unit file for
some useful commands for managing processes, analyzing log data, starting a MySQL server shows how sys
and automating recurring tasks. BY JENS-CHRISTOPH BRENDEL, temd works (Listing 1).
The [Unit] section contains a human-
TIM SCHURMANN, AND JOE CASAD readable description of the service; the
After variable specifies other services
that need to start first. In this case,
ystemd has gradually replaced the while the system is running. Systemd also MySQL depends on the network and the
This setting completely isolates the ser capabilities away from the service. If you allowed to spawn, the service cannot
vice from any networks. The service prepend the capability with a tilde (~ fork any other processes.
then only sees a loopback device, and this capability is explicitly taken away.
even that does not have a connection to You can also use the unit file to limit LimitNPROC=l
the host’s actual loopback device. Of the resources a service can access. The LimitFSIZE=O
course, this option is not very useful for setrlimit() man page lists all restrict
network-based services. able resources. For example, if you set You can limit other resources in a
A word of caution: Sometimes you the maximum size of a file (FSIZE) that similar way.
need a network, even if the need is not the service is allowed to generate to 0,
apparent at first glance. For instance, a as shown in the example below, the Monitoring Processes
service might perform most of its work service cannot write the file anywhere. After you system boots, you might want
locally but use LDAP to handle authenti If you specify 1 as the maximum num to know whether all the required ser
cation. In that case, you need to be sure ber of processes (NPROC) the service is vices are actually running. The systemctl
only users with a user ID below 1000 are
authenticated; names need to resolve to
UIDs locally through /etc/passwd for
these accounts.
A second security feature in [Service] is:
PrivateTmp=yes
Linux provides a means for assigning the 02 * mysqld.service - MySQL 5.6 database server
privileges traditionally associated with 03 Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled)
superuser. These privileges are known as OU Active: active (running) since Do 2015-11-26 09:52:45 CET; 7h ago
capabilities, and you can see the list of
05 Process: 1528 ExecStartPost=/usr/libexec/mysql-check-upgrade (code=exited,
all available capabilities by viewing the
status=0/SUCCESS)
capabilities man page:
06 Process: 1000 ExecStartPost=/usr/libexec/mysql-wait-ready $MAINPID
(code=exited, status=O/SUCCESS)
man capabilities
07 Process: 919 ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n (code=exited,
command provides an overview of ser ExecReload = options in the unit file. draws a graph with the service startup
vice status. Systemctl lists all booted ser However, -kill-who = all (and this is the information.
vices with status information (Listing 2). default) would affect the control and main
If you only want to see the failed start processes. Accessing Log Data
ups, try: If you do not simply want to stop a Systemd includes a journal feature that
service, but you also want to prevent it serves as a log of system events. The
systemctl —state=failed from restarting on the next boot, disable creators of the systemd logging compo
it with the following command: nent wanted to fix the shortcomings of
For a single service, you can view more earlier tools, but they also wanted a
detailed information with: systemctl disable Unit_name simple and reliable solution that didn’t
need maintenance. Other objectives
systemctl status mysqld.service If the process is still running, it is not were portability, security, and perfor
stopped by disabling; if it was already mance. The developers wanted a design
The output (Listing 3) shows the exit stopped, it can still be started manu that delivered tight integration into the
states of the pre- and post-scripts from ally even after disabling. Only auto overall system and harmonized with ex
the unit file, as well as additional infor matic restarting at the next boot time is isting logging systems.
mation on the service status. prevented. The solution differed considerably from
The status messages can be quite There is an even more precise use the previous Syslog daemon. Applications
long on a case-by-case basis. Admins case, even if it is rarely necessary: After
can thus use either the n line number typing: Listing 4: Analysis (excerpt)
parameter to limit the number of rows
01 jcb@localhost:
to output or the o file parameter to redi systemctl mask Unit_name
/var/log$ systemd-analyze blame
rect everything to a file.
02 3.234s docker.service
the service will not start automatically
Starting and Stopping (as is the case with disable), and it also 03 2.152s dnf-makecache.service
Sometimes you need to stop or restart won’t start manually. This command Od 1.281s Plymouth-start.service
individual services after a boot or re links the unit file to /dev/null; if you 05 1.269s mysqld.service
boot. Systemctl and the stop, start, re want to undo this action, you need to 06 1.009s plymouth-quit-wait.service
start, and reload commands can help; delete the link. 07 958ms systemd-udev-settle.service
for example: 08 603ms slapd.service
Analysis of Time 09 02ms firewalld.service
systemctl stop mysqld Reguirements 10 451ms systemd-journal-flush.service
systemctl start mysqld If you have ever considered where your
11 402ms cups.service
computer is wasting time at bootup, and
12 279ms accounts-daemon.service
A user who wants to start or stop a sys maybe used a tool like Bootchart to opti
13 244ms libvirtd.service
tem service must authenticate. If the mize the boot process, you will find life
14 198ms ModemManager.service
process does not respond to the stop much easier with systemd. Systemd al
command, the only way out is: ready has the necessary analysis tools 15 187ms systemd-logind.service
systemctl kill -s HUP 7 tem administrators can at least consider 27 123ms netcf-transaction.service
—kill-who=main crond.service whether they really need these time 28 121ms rtkit-daemon.service
wasters. 29 120ms livesys.service
The -kill -who option ensures that only The whole picture becomes even 30 115ms packagekit.service
the main process receives the signal. clearer if you visualize the data. The fol 31 104ms abrt-ccpp.service
Alternatively, you could also type lowing command: 32 102ms systemd-udevd.service
-kill-who = control to cover all control pro
33 100ms var-lib-nfs-rpc_pipefs.mount
cesses; for example, all processes called systemd-analyze plot > plot.svg
34 [...]
by the = ExecStartPre =, ExecStop =, or eog plot.svg
An attacker who does successfully 11 Jan 10 20:03:52 localhost.localdomain systemd[987]: Reached target Basic System.
break into a system often tries to cover 12 Jan 10 20:03:52 localhost.localdomain systemd[987]: Starting Default.
the tracks by manipulating the system 13 Jan 10 20:03:52 localhost.localdomain systemd[987]: Reached target Default.
logs. The plain-text format of the old Sys- 14 Jan 10 20:03:52 localhost.localdomain systemd[987]: Startup finished in 13ms.
log daemon made this obfuscation very 15 Jan 10 20:03:52 localhost.localdomain gdm-launch-environment][948]: pam_unix(gdm
simple. But journald maintains a crypto -launch-environment:session)...
graphic hash of all messages and a hash 16 Jan 10 20:03:53 localhost.localdomain org.ally.Bus[996]: Activating service
of the preceding entry, which creates a name='org.ally.atspi.Registry'
chain in which the last entry can easily 17 Jan 10 20:03:53 localhost.localdomain org.ally.Bus[996]: Successfully activated
service 'org.ally.atspi.Registry'
authenticate all preceding entries. Log
time-controlled basis. In
this case, simply make a
Listing 9: Service Unit
note of the filename of the [Unit]
service file. Description=Create a backup of the system
[Service]
Tick-Tock
ExecStart=/usr/bin/backup.sh /mnt
To avoid burning the cake
to a crisp, most hobby bak
ers set a kitchen timer. In a similar way, dates, and times separated by
you need to set a separate timer for a commas. In the example from
task you wish to assign to systemd. the first line of Listing 11, sys
First, create a new text file in the/etc/ temd starts the backup No
system/system subdirectory. The text file vember 30, 2020 at lam and
should have the same filename as the 12pm (noon).
service unit you created earlier, but it You can also abbreviate the
ends with .timer. In the example, the file number ranges with two dots
would be named backup.timer. In sys (..), which means that you do
temd speak, the file with the .timer ex not have to list all the months,
tension is known as the timer unit. In for example. The entry from
the timer unit, you describe when the the second line of Listing 11, tells sys can also combine these. Systemd
timer should “go off,” at which point, temd to take action on the first day of would delay the backup by a maxi
systemd will start the backup. each month. If the statement applies to mum of 90 seconds if you state
The structure of a timer unit is very all months, you can also use the wild RandomizedDelaySec = "Im 30s".
similar to that of a service unit. As the card * (last line).
example from Listing 10 shows, it typi The *-*-* entry from Listing 10 tells Repetition
cally consists of three sections: [Unit] is systemd to run the backup every day at Systemd lets you schedule a task to
followed by general information about 18:15 in every month and every year. occur at some recurring interval without
the timer. In Listing 10, this information specifying an exact time - for example,
would include a Description = that Extremely Hesitant every 15 minutes or once a week. Use
serves mainly as a reminder for the user. If the computer is not running at the se the OnCalendar = weekly option to start
Make a note on why the timer exists and lected time, systemd cannot create a a weekly backup. In addition to weekly,
what actions it triggers. backup. In Listing 10, the you’ll find options for minutely, hourly,
In the next section, [Timer], you tell Persistent = true setting ensures that sys daily, monthly, yearly, quarterly, and
systemd when to start the task. Make a temd catches up with the task as quickly semiannually.
note of this time after OnCalendar = in as possible in such situations. However, If you want to run a task 15 minutes
the notation weekday year-month-day if several actions start simultaneously, after system startup, use the following
hour:minutes:seconds. The setting they can slow down the system or even settings instead of OnCalendar =...:
OnCalendar=Fr 2018-11-30 12:00:00 interfere with each other.
tells systemd to create the backup on To prevent a traffic jam, systemd ran 0nBootSec=1Sm
Friday, November 30, 2018 at noon domly delays execution by a few sec OnUnitActiveSec=lw
precisely. You can omit unnecessary onds if necessary. The maximum num
information, such as the day of the ber of seconds it can wait before exe OnBootSec = specifies how many sec
week or the seconds. cuting is stated after Randomized- onds after system startup systemd
Normally, you will not want systemd DelaySec =. Systemd interprets the should execute the task. In the example,
to run the task once only, but to repeat number as minutes for a trailing m and the timer goes off 15 minutes after the
it. To set up a repeating event, you can as hours for an h. In Table 1, you will system startup. The second setting,
simply list the corresponding days, find all other supported time units; you OnUnitActiveSec=, tells systemd the
time intervals at which it should repeat
Table 1: Units Used by systemd the task. In the example, systemd would
Unit Long forms Meaning Example
run the backup 15 minutes after system
startup and then every week.
s seconds, second, sec second 5s
With both settings, you can use the
m minutes, minute, min minute 10m units from the Table 1 and combine the
h hours, hour, hr hours 2h information. For example, the
d days, day day 7d OnBootSec = ”5m 30s" setting would exe
w weeks, week week 2w cute the task five and a half minutes
after system startup.
M months, month month 6M
If a timer is based on a (calendar)
y years, year year 4y
date, as per Listing 10, it is known as a
“Calendar Timer.” If, on the other hand, you need greater accuracy, add the line
a timer starts after a specified period ofAccuracySec = 30s to the [Timer] sec at system startup, you need an [Install]
time relative to an event, such as a sys tion. The time specification determines section in the timer unit. The Want-
tem start, Systemd refers to it as a the desired accuracy; in the example, edBy = setting tells which other units the
“monotonic timer.” Such timers work in the action would be no later than 30 timer should start with. In Listing 10, the
dependently of the time zone. seconds after the assigned date. For WantedBy = timers, target setting ensures
The timer is not only triggered shortlysuch time entries, you can again use that systemd starts the timer together
after system startup, but also responds the units from Table 1. with all other timers at the regular sys
to other events listed in Table 2. As in Timers also let you wake up the com tem startup time.
the previous example, several settings puter from suspend mode on a time-con If you want systemd to start the timer
can be combined with each other; each trolled basis. To do this, add the line at startup time, you have to enable it ex
setting must have its own line. WakeSystem = true to the [Timer] sec plicitly (Listing 12, first line). Alterna
tion. Systemd only wakes the system tively, you can start the timer manually
Relationship Helper when it is in sleep mode and if the hard (second line). All currently configured
The systemd-analyze tool helps you fig ware and the BIOS/UEFI of the computer timers are listed by the systemctl list-tim
ure out the correct times. If you pass it support the process. Systemd is currently ers command (Figure 2).
the calendar parameter, systemd-analyze unable to put the computer to sleep on a In Figure 2 under Next, you can read
converts the relative time specifications time-controlled basis. when the system timer will execute the
into other formats (Figure 1). The fol Systemd assigns the timer unit to the task the next time. The time remaining
lowing command tells you, for example, appropriate service unit based on the until then is in the Left column. Simi
which day of the week weekly corre filenames. In the example, the timer larly, you can see under Last when sys-
sponds to: backup, timer automatically starts the temd-timer last executed the task. How
command from the service unit long ago that was is shown in the
$ systemd-analyze calendar weekly backup.service. Alternatively, in the Passed column. Under Unit, you will
[Timer] section, you can explicitly find the name of the corresponding
By default, systemd guarantees one- specify the name of the service unit timer and thus its configuration file.
minute timer accuracy. You can there that you want systemd to execute You can end the display by pressing Q.
fore expect the backup not to start using the Unit= setting. This is espe By default, systemctl only presents tim
punctually at 6:00pm, but at 6:01pm. If cially useful if you want to start an ex ers that are currently enabled. You can
isting service unit display the inactive timers on screen by
tim@ubuntu:~$ systemd-analyze calendar weekly with a new timer. appending the -all parameter.
Original form: weekly
Normalized form: Mon *-*-* 00:00:00
Next elapse: Mon 2018-05-28 00:00:00 CEST Winding Up Snooze Button
(in UTC): Sun 2018-05-27 22:00:00 UTC the Clock If required, each timer can be stopped
From now: 5 days left
If you want sys manually (Listing 13, first line) and dis
Figure 1: A timer starting weekly would execute at midnight every temd to activate abled (second line). The man page [1],
Monday. The next event will be in exactly five days. the timer directly which goes by the name of systemd. timer,
6 timers listed.
Pass --all to see loaded but inactive timers, too.
[lines 1-10/10 (END)|
Figure 2: Systemctl displays all timers currently running. The display reguires a wide terminal window; alternatively, you can use systemctl
list-timers -no-pager to output the information to the standard output.
provides explanations for all presented The time units again correspond to starts the task stored in the backup, ser
settings. For further information on those in Table 1. In the example, sys vice service unit every week.
the format of dates and times plus nu temd interprets the 30m as half an hour. The timers generated by systemd-mn
merous additional examples, see man Alternatively, use -on-calendar = to only exist temporarily. If you use the
systemd.time. enter a specific date. The details are -on-active parameter, the timer disap
again provided in the same way as in the pears immediately after the action has
Short-Term Alarm timer unit. With appropriate time speci been executed; in any case, it disappears
If you want systemd to make a single fications such as weekly, the action can after rebooting the system. Systemd-run
backup in exactly 30 minutes, use sys execute repeatedly. only creates a timer for a service unit if
temd-run. The command looks like the In any case, systemd-mn creates a new no suitable timer unit exists.
first line of Listing 14. The /usr/bin/ timer in the background without you
backup, sh /mnt command appended needing to create a service file (Figure 3). Conclusions
there is executed by systemd at the spec If a suitable service unit already exists, Systemd lets you define how to start a
ified time. Use the parameter -on-active you can alternatively let systemd-mn service and what the service can do at
to tell it the waiting time. launch it. To do this, simply pass in the runtime. The clear and simple syntax is
name of the service in contrast to the shell-script-based
Listing 14: Examples unit using the -unit methods used in earlier init versions,
parameter. The exam and systemd also offers some interest
$ systemd-run —on-active=30m /usr/bin/backup.sh /mnt
ple from the second ing new options for security, analysis,
$ systemd-run —on-calendar=weekly —unit backup.service
line of Listing 14 data visualization, and automation. ■
Missed an issue?
You're in luck.
usBBoot Privacy
Most back issues are still
available. Order now before
they're gone!
shop.linuxnewmedia.com
GET IT
'(earning
ALTERNATIVE
? PDF EDITIONS V
fosspicks
MANAGEMENT Managing Processes
NICE JOB
Be free, be nice, killall? We'll show you how find out more about
your system's processes and how to monitor and control them, all
from the command line. BY HEIKE JURZIK
he previous chapter on systemd • STAT: Process status. The states can be Entering ps / presents you with a tree
command name (COMMAND). You also also assign a specific priority, where -20 is
Security Tip
can tell top what you want to see; just the highest and 19 is the lowest priority.
The ps tool displays the full set of com press F and the relevant letters to specify To set the level for the process monitor
mand-line parameters in the COM the status line content. top, for example, you would type:
MAND column. Some programs, such
as the wget download manager, option Several commands allow you to con
ally accept passwords for authentication trol top interactively; for example, you nice -n 19 top
in the shell. The password also appears can press H to display the online help.
as a command in the process list; theo Entering U followed by a username gives If you skip the -n option and the nice
retically, any user on the system could you the processes for that user. Shift + R level, nice sets the value to 10. As men
sniff sensitive data.
reverts the output, showing the most fru tioned before, regular users are only al
gal processes instead of the CPU hogs, lowed to use positive increments:
you a snapshot of the current status, and entering Q quits the tool and takes
you will not find out too much about you back to the shell. $ nice -n -19 top
the current system load. However, Shift + Z lets you add color. The W key nice: cannot set niceness: P
Linux has the top tool to help you with toggles through several predefined color Permission denied
this task. Top is a process monitor that schemes, but you can also press the ap
updates the display to give you the cur propriate letters and numbers to define To discover a program’s nice level, use
rent status. You can launch the monitor your own color scheme (Figure 3). the top (under column NI in the status
by typing top at the command line. bar) or ps command. In the ps output in
This program gives you extensive in Mister Nice Guy Listing 3, the top call has been “niced,”
formation about your system and the Processes have a specific priority, as indicated by the capital N in the STAT
processes running on it. The top line which becomes useful if you have a column.
shows the time, the computer uptime, program running in the background To change the priorities of programs
the number of processes, and the status and do not want to risk losing control that are already running, use the renice
details, along with the CPU, memory, over the system load. To start a pro command. Regular users manipulate
and swap load. To find out more about gram with a specific priority, use the only their own tasks; only the root user
used and unused memory and swap nice command. Non-privileged users can renice every program. To change a
space, you can also use free or uptime may only assign lower priorities to priority, find out the program’s PID,
(see the “More Information about their own tasks - assigning higher pri then use renice plus the -n parameter
Memory” box). orities is the administrator’s domain. and the value:
The top status line contains informa Processes have a nice value of 0 by de
tion on the individual processes. The fault; if you run the command without $ renice -n 10 2342
columns of the status line present vari parameters, the program will confirm: 2342 (process ID) old priority 19, 7
ous categories, such as the process ID new priority 10
(PID), username (USER), priority (PR), $ nice
nice level (NI), memory usage as a per 0
centage (%MEM), parent process ID ■ HodcnManager, SIP
I - (gdbus) ,661
(PPID), user ID (UID), CPU time con With the nice com
|-dhcllent,2075 -d -q -ST /usr/ltb/NetworkManager/no-dhcp-helper
sumed as a percentage (%CPU), and mand, you can
|-{gdbus},663
■-{gRatn),6S9
■VBosCllent,12M,huhn --clipboard
-VBoxCltent.1267 --clipboard
-{SHCLIPJ.1284
TIME COMMAND |-{gdbus},660
0:00 /sbin/init splash
0:00 [kthreadd]
0:00 [ksoftirqd/0] -anacron.SOO -dsq
0:00 [kworker/0:0H] -sh,2284 -c ru -report /etc/cron,weekly
0:00 [kworker/u2:0]
0:00 [rcu.sched]
0:00 [rcu.bh] •cat,23OO
0:00 [rcuOS/O] •avahi-daenon,621.avahi
0:00 [rcuob/0]
0:00 [nigration/O] -cgnanoger,616 -r nane-systewd
0:00 [watchdog/O] ■eolord,1096,colord
0:00 [khelper] |-(gdbus},1090
a:ee [kdevt«pfs] '-(gnatn},1099
0:00 [netns]
o:oo [perf]
0:00 [khungtaskd] '-{gdbus},675
0:00 [writeback]
0:00 [ksnd]
0:00 [khugepaged]
0:08 (crypto) -gnone-keyrtng-d,118S,huhn -daenontze -login
0:00 [kintegrityd] |-{gdbus),1356
O:O0 [bioset] |-{gnatn),1186
0:00 (kblockd)
0:00 [ata.sff] - kerneloops,1125,kernoops
0:00 [led] ■to -auth /var/run/lightdn/root/:0 -noilsten
O:00 [devfreq_wq]
0:00 [kworker/u2:l]
0:00 [kworker/0:l]
o:oo [kswapde]
0:00 [fsnotify.nark] i-(gdbus},140S
0:00 [acryptfs-kthroa] •{gnatn}.1410
0:00 [kthrotld]______ -at-spi2-reqlstc,1413 ■-use-qnone-session
Figure 1: The ps command shows you what is happening on your Figure 2: The pstree command shows you process relationships in
Linux machine. the shell. Combine the options to format the output.
Foreground and
Background Processes
In some cases, a program you launch in
the shell might run for an extended pe
riod of time. Graphical programs that
you launch in a terminal window block
the shell, preventing any command
input. In cases like these, you can run Besides the process ID, you can also Az
out and grab a coffee or open a second see the job ID in square brackets. The [4]+ Stopped gimp
console and carry on working. As an al job ID is allocated as a consecutive num
ternative, you can move the process into ber by the shell. If you launch another If you now type bg (background), the
the background, either when you start it program in the same session, you will process will continue to run in the back
or at a later time. see that Bash assigns job ID 2. The jobs ground. The job ID is useful if you have
To move a process into the back command (Listing 5) tells you which stopped several processes in a shell. The
ground when you launch it, just add the jobs are running in the current shell. bg %3 command tells the process with
ampersand character (<&) to the com After a program has completed its job ID 3 that it should start working
mand line (Listing 5). For the Gimp win task, the shell displays the job ID along again. In a similar way, the fg (fore
dows launch, the shell informs you of with a status message (Done) and the ground) program moves jobs into the
the process ID (4302), and Bash can then program name: foreground. Again, this program might
accept more commands. need more details in the form of a job ID
[1] Done gimp following a percent character.
Command-line software managers provide an easy way to install programs, games, fonts, and themes. Get
to know your system’s manager, and you'll never have to worry about searching for software on the Internet.
BY BRUCE BYFIELD AND PAUL BROWN
hen you install software in Debian and Debian operation. In practice, apt rarely needs
metapackage exists for your purposes, if you go through with the installation, inprogress, as well as the download speed
search online in your distro’s reposito cluding the dependencies that will be in and the amount of time required to fin
ries; if all else fails, guess its name, and stalled, the packages that will be up ish the operation. The times are only es
see whether you are successful. graded and removed, and the amount of timates and will change as the Internet
Depending on whether you are using disk space that will be required. Unless connection speed changes. Once the
apt-get or apt, the basic command for the action can proceed automatically downloads are complete, both install the
adding or upgrading a software package without affecting anything else, you then software, sometimes pausing to ask
is either can confirm or cancel the process (Fig questions about how you want it in
ure 1). Usually, you should read the sum stalled. With apt, you also get a progress
apt-get install options <packagename> mary carefully before continuing, just to bar. After everything is done, the com
be sure what you typed doesn’t include mands then exit with a summary of any
or any unpleasant surprises. If you are using problems encountered, if necessary. As a
a non-standard online repository, it might final touch, the software you just in
apt install <packagename> not be verified automatically as a valid stalled is added to desktop menus.
source. When that happens, you should In apt-get, the basic command for in
Deleting a package uses the same struc only continue if you are absolutely sure stalling software can be modified with a
ture, except the sub-command is remove. that you can trust the repository. number of options. For example, you
Both apt and apt-get usually start with As apt or apt-get works, it shows might want to use -s to simulate the in
a complete summary of what will happen which package is downloading and its stallation without actually doing any-
thing, just to make
nanday:-# apt-get install wesnoth sure you uncover any
Reading package lists... Done problems before the
Building dependency tree
real installation. If the
Reading state information... Done
installation reports
The following packages were automatically installed and are no longer required:
libboost-regexl.37.0 libboost-iostreams1.37.0 any problems, you
Use 'apt-get autoremove' to remove them. can run the command
The following extra packages will be installed: again, this time with
ttf-wqy-zenhei wesnoth-all wesnoth-aoi wesnoth-core wesnoth-data wesnoth-dbg the -/'option, in the
wesnoth-did wesnoth-editor wesnoth-ei wesnoth-httt wesnoth-1 wesnoth-low hopes that apt-get can
wesnoth-music wesnoth-nr wesnoth-sof wesnoth-sotbe wesnoth-thot wesnoth-tools intelligently provide a
wesnoth-trow wesnoth-tsg wesnoth-ttb wesnoth-utbs
solution, or with -m
The following packages will be upgraded:
to ignore any missing
ttf-wqy-zenhei wesnoth wesnoth-all wesnoth-aoi wesnoth-core wesnoth-data
wesnoth-dbg wesnoth-did wesnoth-editor wesnoth-ei wesnoth-httt wesnoth-1 dependencies in the
wesnoth-low wesnoth-music wesnoth-nr wesnoth-sof wesnoth-sotbe wesnoth-thot hopes that you will
wesnoth-tools wesnoth-trow wesnoth-tsg wesnoth-ttb wesnoth-utbs get satisfactory re
23 upgraded, 0 newly installed, 0 to remove and 1207 not upgraded. sults. However, both
Need to get 255MB of archives. -/and -m must be
After this operation, 11.0MB of additional disk space will be used. used with extreme
Do you want to continue [Y/n]? []
care and only as a
Figure 1: Before doing anything, both apt and apt-get explain what they will do and give you a chance to back out of last resort, because
the operation. The only visible difference between the two commands is that apt includes a progress bar rather a they can lead to a
percentage-complete field. broken system.
The most common useful option for dpkg -i digikam_'±_li_‘±-l. I_amd64.deb To help with these basic operations,
installation is -t <repository>, which al dpkg and apt-get include a number of
lows you to specify the online repository For other options, the command struc utilities, apt has only a few of these utili
from which you want to install the pack ture is the same, except for the change in ties, presented as sub-commands. When
ages and all its dependencies. This op the sub-command. Even the available you run into difficulties and are seeking
tion is especially useful in Debian, options are the same, although some information, the command dpkg-query
whose main repositories (stable, testing, might not make sense with every sub or apt show can give you detailed infor
and unstable) describe the state of the command. The remove sub-command mation about the packages involved. For
software. For example, if you want the uninstalls software, whereas the purge example, if you type
very latest version of Gnome, even if it sub-command removes all traces of a
has not been well-tested, you can down package, including things like configura dpkg-query -p kdepim4_4_4-l.Iamd64.deb
load it from the Debian unstable reposi tion files, from your computer (neither,
tory by entering: however, removes dependencies, which or
is why you might need to run some of
apt-get -t unstable install gnome the maintenance sub-commands listed apt show kdepim
later). If you want to upgrade every
No similar option is available for apt. package on your computer, you can use you receive a description of the package
Similarly, in other Debian-based distri the dist-upgrade (or the apt equivalent that lists contact information for the de
butions, you might have added a devel upgrade) command rather than entering velopers who maintain it; the package’s
opment branch of the software to your every package individually. dependencies, size, and description; and
repositories or a privately developed ver Most people use the Debian package the homepage for the development team
sion of software that you only want to system to install precompiled binary (Figure 2). Similarly, you can use the -s
use occasionally. With this option, you files. However, if you want to ensure that option to determine the status of a file or
can downgrade a package when the all your software runs as efficiently as -L to see a list of all the files included in
most recent version is buggy or not possible on your system, you can use the the application’s package. All this infor
working. source sub-command to download mation can be invaluable if you run into
If you are an expert, you could also source packages and the -b option to trouble, regardless of whether you want
download a single package to your compile them on your computer. If the to solve the problem yourself or find
hard drive for installation. In that case, source requires dependencies, you can someone to help you.
you would go directly to dpkg. For ex use the build-dep sub-command. Note, The apt-get command includes several
ample, if you downloaded a develop however, that compiling source packages other utilities in the form of sub-com
ment version of the digiKam image can take considerable time, particularly mands that are issued without referring
manager, you could install it by chang with a large application - perhaps even a to any packages. Just as you might use
ing to the directory containing the matter of hours with an application like fsck to investigate and repair the struc
package and entering: LibreOffice. ture of a filesystem, you can use the fol
lowing command
nanday:~# dpkg-query -p kdepim
Package: kdepim
apt-get check
Priority: optional
Section: kde
Installed-Size: 68 to ensure that the package
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org> system is working properly.
Architecture: all
The more you install and
Version: 4:4.3.0-1
Depends: akregator (>= 4:4.3.0-1), kaddressbook (>= 4:4.3.0-1), kalarm (>= 4:4.3.0-1
uninstall, the more regu
), kdepim-kresources (>= 4:4.3.0-1), kdepim-wizards (>= 4:4.3.0-1), kmail (>= 4:4.3. larly you should consider
0-1), knode (>= 4:4.3.0-1), knotes (>= 4:4.3.0-1), konsolekalendar (>= 4:4.3.0-1), k running apt-get with the
ontact (>= 4:4.3.0-1), korganizer (>= 4:4.3.0-1), ktimetracker (>= 4:4.3.0-1), kdepi clean and autoclean sub
m-strigi-plugins (>= 4:4.3.0-1), kjots (>= 4:4.3.0-1), kpilot (>= 4:4.3.0-1), kleopa
commands. The clean com
tra (>= 4:4.3.0-1)
Suggests: kdepim-doc mand removes all the pack
Size: 16052 ages you have downloaded
Description: Personal Information Management apps from the official KDE release and installed while retain
KDE (the K Desktop Environment) is a powerful Open Source graphical ing the installed software,
desktop environment for Unix workstations. It combines ease of use,
and autoclean removes all
contemporary functionality, and outstanding graphical design with the
technological superiority of the Unix operating system. packages that have become
obsolete and can no longer
This metapackage includes a collection of Personal Information Management be downloaded. By run
(PIN) applications provided with the official release of KDE.
ning both occasionally, you
Homepage: http://pim.kde.org/
can free up extra space on
Figure 2: The dpkg-query utility tells you everything you could ever want to know about each software pack your hard drive without af
age. Alternatively, you can use apt show. fecting the system.
Another useful
maintenance sub [ root@local.host -]# dnf install sil-gentium-basic-book - fonts
Dependencies resolved.
command for
apt-get is autore
move, which re Package Arch Version Repository
moves orphaned Size
packages (i.e.,
ones that serve no Installing :
sil-gentium-basic-book - fonts noarch l.l-10.fc20 fedora 240 k
purpose, because
sil-gentium-basic-fonts-common noarch l.l-10.fc20 fedora 22 k
they were added
as dependencies Transaction Summary
for an application
that you have Install 2 Packages
since removed).
Because these or Total download size: 262 k
Installed size: 1.1 M
phans do nothing Is this ok [y/N]: |
but fill space on
your hard drive, Figure 3: DNF gives complete information about what actions it is about to perform.
you might as well
remove them. The Debian package sys positories in sources, list and specifying package manager has for years been
tem keeps track of orphans and will re the -t option for setting the sources from Yum (originally, Yellowdog Updater,
mind you that they exist when you run which to install. In this way, you have Modified). However, in the past few
apt-get for some other purpose. less chance of making a mistake. years, it has started to be replaced by
Yet another bit of maintenance you Depending on your distribution, soft DNF [2] - DNF doesn’t stand for any
might want to perform is to add or re ware installation can involve a number thing in particular; It is just a random
move online repositories from /etc/apt/ of other associated utilities. By far, the collection of letters - a new package
sources.list. With apt, the command is most useful package utility is apt-cache, manager that improves on some of
simply apt edit-sources. With apt-get, you which offers a treasury of information Yum’s shortcomings.
can open the sources.list file in any text about packages and your system. For Just as apt-get in Debian provides
editor. The sources.list file points to all the example, users with access to the functionality of
online repositories that apt-get and dpkg dpkg, so do DNF and Yum act as wrap
use. Each repository is listed on its own apt-cache showpkg <packagename> pers for rpm, the basic command for
line according to a simple system. The RPM package management. The main
entry for each repository begins with deb shows which version you have installed, difference is that, whereas dpkg resolves
if it is a repository of binaries and deb-src the latest version available in the reposi dependency problems on its own, rpm
if it is a repository of source packages. tories you are using, and the reverse de does not. That functionality resides en
This information is followed by the repos pendencies of the packages (i.e., which tirely in DNF and Yum.
itory URL, name, and subsections. packages depend on it). DNF shares a common structure
Sources are disabled with a hash sign (#) Similarly, the commands with Yum. Like apt-get, Yum has a
at the start. Typically, hash symbols also consistent basic format: the basic
are used to add comments that humans apt-cache dump command (dnf or yum), any options,
can use to identify the source. apt-cache stats the sub-command (what you are
When you add or remove a repository doing), and the packages involved.
from sources.list, you must then run list all the packages you have installed The main difference is in the list of
and offer information such as the num sub-commands involved.
apt-get update ber of installed packages and the total The sub-command that you will prob
number of dependencies. An especially ably use most often is install. For in
or useful option is stance, if you plan to install the Book
typeface for the free Gentium font, the
apt update apt-cache search <packagename> basic command in Fedora would be:
to change the repositories that are in which tracks down the exact name of a dnf install 7
use. Otherwise, the package system con package or packages that you might sil-gentium-basic-book-fonts
tinues to use previously identified repos want to install.
itories. Editing and then updating takes a When you enter the command, DNF de
few minutes to complete each time but Fedora and Related termines the dependencies (Figure 3).
has the advantage of ensuring that you Distributions In the example above, DNF would note
know precisely which sources you are In RPM-based distributions such as Fe that it requires the package sil-gentium-
using. Some users prefer enabling all re dora, Red Hat, and CentOS, the main basic-fonts-common, which is needed
with any weight of Gentium you install. mand to see what is available before move, followed by the name of the
It then lists the amount of hard drive installing anything. Or, you might pre group. For instance
space needed both to download and in fer to specify particular packages to
stall the packages. upgrade instead. dnf group KDE
Once you press y (for “yes”) to con All of these basic sub-commands are
tinue the installation process, DNF be available for use on multiple packages. The would add all the files in the KDE group
gins to download the necessary pack simplest way to handle multiple packages to your system.
ages, showing the progress of each is to enter them in a space-separated list at All packages or groups installed can be
download and of the overall process the end of the command. Alternatively, removed using the erase sub-command.
(Figure 4). After the downloads are com you can use regular expressions. If you do, Besides these basic commands, DNF
plete, DNF installs each package and check carefully the summary provided by includes several that provide informa
summarizes what it has done. If it is suc DNF before proceeding, because you might tion or help you maintain your system.
cessful, a succinct Complete! displays get unexpected results. The most basic sub-command, list, is
just before DNF exits. Some repositories organize packages completed by descriptions of the infor
To install a newer version of a pack into groups. In Fedora, for example, mation you want. For instance
age, you can also use install, but a bet the package groups include Games and
ter choice is the upgrade sub-command, KDE. These groups serve much the dnf list installed
because it can handle the removal of same function as metapackages on dnf list available
any obsolete dependencies - an ability Debian systems, allowing you to install
that is especially useful when you are multiple packages without having to displays a complete list of installed and
switching from one version of a distri remember them or edit them sepa available packages.
bution to another. rately. Groups have a series of special When you want more specific informa
If you are cautious, you might pre sub-commands that include groupin- tion about a package, the sub-command
fer to use the check-update sub-com stall, groupinfo, grouplist, and groupre- to use is info followed by the package
name (Figure 5).
Is this ok [y/N]: y The info command
Downloading Packages: provides basic infor
(1/2): sil-gentium-basic-fonts-common-1.1-10 6.4 kB/s | 22 kB 00:03
(2/2): sil-gentium-basic-book-fonts-1.1-10.f 60 kB/s | 240 kB 00:04 mation about the
package: its architec
Total 47 kB/s | 262 kB 00:05 ture; its version num
Running transaction check ber and release;
Transaction check succeeded. whether it is installed
Running transaction test
or, if not, what repos
Transaction test succeeded.
Running transaction itory it is in; its li
Installing : sil-gentium-basic-fonts-common-1.1-10.fc20.noarch 1/2 cense; and its
Installing : sil-gentium-basic-book-fonts-1.1-10.fc20.noarch 2/2 homepage. Also, you
Verifying : sil-gentium-basic-book-fonts-1.1-10.fc20.noarch 1/2 will receive a single
Verifying : sil-gentium-basic-fonts-common-1.1-10.fc20.noarch 2/2
sentence summary
Installed: and a slightly longer
sil-gentium-basic-book-fonts.noarch 1.1-10.fc20 description. The sub
sil-gentium-basic-fonts-common.noarch 1.1-10.fc20 command groupinfo
provides similar in
Complete!
formation for pack
Figure 4: DNF installing a package. age groups.
A rarer but occa
[ root@localhost -]# dnf info firefox II sionally useful sub
Installed Packages 1 command is pro
Name firefox vides, with which
Arch i686
you can find the
Epoch 0
Version 38.0.5 package that includes
Release l.fc20 a particular file or
Size 116 M feature (Figure 6).
Repo ^System For example, the
Summa ry Mozilla Firefox Web browser command
URL http://www.mozilia.org/projects/firefox/
License MPLvl.l or GPLv2+ or LGPLv2+
dnf provides firefox
Desc ription Mozilla Firefox is an open-source web browser, designed for
standards compliance, performance and portability.
returns exactly
Figure 5: The info sub-command gives you all available information about a package. which package ver-
sion is available or installed, as well as ularly powerful maintenance tool is You will only inconvenience yourself if
the versions found in the repositories. clean, which, like list, is completed by a you run it casually.
Another means of tracing references to description of the information source Most of the time, you can use DNF
a specific package is the search sub-com you want to remove. However, with the without any options. A few options pro
mand. This function will locate all pack exception of the command vide useful information to help you ad
ages and dependencies related to the minister software installation. A great
search term, followed by a brief descrip dnf clean packages many more enable or disable informa
tion. search can be useful for finding tion for various purposes. Some options,
packages when you lack an exact name which removes packages that were such as -v (--verbose), which increases
or are reasonably sure that a function downloaded but not installed, using the amount of information DNF pro
must be available somewhere. clean is an act of desperation. Running vides, are useful mainly for program
All of these information sub-com clean followed by any other option - mers who are debugging.
mands frequently give dozens, even such as metadata, dbcache, or all - re Other options are for users who want
hundred, of lines of output. For this rea moves information that DNF requires to use DNF with a minimum of fuss, such
son, consider piping them through the to operate. as -quiet, which causes DNF to run with
less command by adding | less to the end The next time you start DNF after run out reporting what it is doing. Its frequent
of the command so that you can scroll ning clean with these completions, DNF companion is -assumeyes, which as
through at your leisure. will rebuild what was deleted, but re sumes that the answers to all questions
DNF sub-commands also include a building could take a few minutes de are Yes - including the question of
number of utilities that can help you pending on your machine. For this rea whether you want to proceed after DNF
maintain and troubleshoot your system. son, you should only run the clean sub finishes its initial calculations. In much
command when you are having trouble the same way, -nogpgcheck disables
dnf makecache with DNF. Unlike apt-get's clean and au package verification, and -allowerasing
toclean, DNF’s clean is not for routine permits DNF to erase installed packages
downloads the information for all pack maintenance, but for major problems. without asking to resolve any depen
ages in all enabled repositories, which
you can use if the information is cor [ root@localhost -]# dnf provides firefox
rupted or outdated or if you have re firefox-38.0.5-1.fc20.i686 : Mozilla Firefox Web browser
cently changed repositories. Similarly, Repo : @System
for the rare time that problems emerge,
reinstall lets you try again, whereas firefox-25.0-3.fc20.i686 : Mozilla Firefox Web browser
Repo : fedora
downgrade lets you revert to a specific
version to avoid the current program
firefox-38.0.5-1.fc20.i686 : Mozilla Firefox Web browser
that is causing problems on your system. Repo : updates
When problems occur, the sub-com
mand history can help you review recent Figure 6: If you wonder about the origins of files or applications, dnf provides can give you the
package activity on the system. A partic information.
IT Highlights at a Glance
LINUX Linux Update
UPDATE
ADMIN Update
ADMIN HPC
Too busy to wade through press releases and chatty tech news sites?
Let us deliver the most relevant news, technical articles, and tool tips - straight to
your Inbox.
dency problems. Such options save time; using universal packages, although changes, which lists all the snap-re
however, use them cautiously to avoid users should note that combining tradi lated actions performed on the system,
unpleasant surprises. tional package managers with universal as well as list, which displays all the
Other options are less likely to cause ones complicates system care and secu snap packages on the system. For
trouble. The matched pair -enable-repo= rity. However, both traditional and uni more information, see the Snap project
and disable-repo= specify which reposi versal packages have mostly the same website [6].
tories to use. Also, you can use -ex functionality, as well as the same sub The success of universal packages, or
clude = to prevent packages that could commands. how they compete with each other, are
cause a conflict from installing from The first universal package system was still unanswered questions. The most
any source. Applmage [3]. It remains by far the sim common use on the desktop appears to
Another option that might keep you plest. With Applmage, you download a make new versions of applications avail
out of trouble is -skip-broken. If you use compressed image that includes all the able quickly.
it after DNF reports a missing depen necessary dependencies, change its per
dency, it might just allow you to resolve missions to make it executable, and then Conclusion
the difficulty. In some cases, packages run it. No installation is required beyond Other package managers also exist, no
installed with this option will not work, downloading. To remove an Applmage tably Arch’s pacman, openSUSE’s Zyp-
but you can make sure they do not form package, delete it as you would any per, and Gentoo’s Portage. However,
a bottleneck that keeps DNF from work other file. although the details differ, once you
ing. Once they are installed, you can Developed by Red Hat, Flatpak is de have used a couple of package manag
then delete them normally. signed primarily to install software on ers, you will find that all have the
the Gnome desktop. Its online reposito same basic set of commands. These
Universal Packages ries are called remotes. You can see a list commands include commands for
Most package managers reflect a time of remotes using the command flatpak managing repositories, searching for
when disk memory was scarce. Having remotes. Other commands are equally packages, and installing and removing
applications share the same library made simple, with immediately recognizable packages. Often, the sub-commands
economic use of space. However, for sub-commands like search, update, and are identical.
over a decade, disk space has become repair, followed by the package name. To Whatever package manager your
much larger and is less of an issue. At install a package, you can either specify distribution uses, it is sure to make
the same time, a demand has developed a remote plus the package, or else the using software easier. Thanks to pack
for delivering updates in a single pack URL of a flatpak.ref file; for example: age managers, you do not need to
age to containers and embedded sys search the Internet for software. Nor
tems. These changed conditions have led flatpak install flathub org.gimp.GIMP do you have to worry that the soft
to the creation of so-called universal ware will be buggy or a security risk,
package managers like Applmage, or although you should investigate how
Flatpak, and Snap. your distribution handles security up
Much has been claimed for universal flatpak install 7 dates to avoid problems.
package managers that has not been re https://flathub.org/repo/appstream/P These days, most distributions have
alized and probably never will. For in org.gimp.GIMP.flatpakref desktop applications for package man
stance, they are often said to be more agement. However, these desktop man
secure than traditional package man To run a package, specify its ID. For ex agers are almost always front ends for
agement systems, because they can de ample: command-line tools. Open up a terminal
liver updated versions more quickly. and get to know the tools that do the
However, the weak link is the packagers flatpak run org.gimp.GIMP heavy lifting, and you will have taken a
and system administrators, who may giant step toward learning how to ad
not deliver or install updates immedi A complete list of commands is available minister your system. ■
ately. More importantly, many projects from the Flatpak website [4].
are not oriented to producing packages, Snap packages are developed by Ca INFO
having traditionally left making pack nonical, the company behind Ubuntu.
[1] APT: https://wiki.debian.org/Apt
ages to the distributions. In practice, Although designed for embedded sys
too, distributions have their own way of tems, snap packages also rival Flatpak [2] DNF: https://fedoraproject.org/wiki/
managing packages, even when using on the desktop. Just as with phone DNF?rd=Dnf
the same manager, so one package for apps, snaps are available from an on [3] Applmage: https://appimage.org/
all distributions is more of a challenge line store [5], although you can also [4] Flatpak: http://docs.flatpak.org/en/
than might be assumed. use the command structure snap find latest/using-flatpak.html#
However, universal packages do offer < package > from the command line. basic-commands
advantages, such as the ability to install Installation uses the format snap in [5] Snap online store: https://snapcraft.
different versions of any package on a stall < package >; the refresh sub-com io/store
single system. As a result, many major mand is used to update a package.
[6] Snap: https://snapcraft.io/
distributions include the commands for Snap also includes the sub-command
MIRROR IMAGE
Whether you are creating backups, rescuing data, or burning bootable
CD, DVD, flash or Blu-ray media, shell commands help you handle the
job in style. BY HEIKE JURZIK; REVISED BY BRUCE BYFIELD
he command line has applications tions, CDs, or DVDs. Also, dd supports re and writes them to the output file. If you
CONNECTIONS
The Linux command line provides a powerful collection of utilities for running kernels newer than 2.0. The if
config command is still available as part
configuring and troubleshooting network connections. This article of the net-tools package, though, and in
rounds up some new and old networking commands. all likelihood, it is automatically installed
on your system.
BY JAMES MOHR, JOE "ZONKER" BROCKMEIER, NATE DRAKE, On newer Linux systems, you also get
FERDINAND THOMMES, AND JOE CASAD the ip command. More than just a
newer version of ifconfig, ip is the
workhorse of the new generation of net
inux and other Unix-based sys later login when a different device is work tools. Not only does it integrate
mon
The networking tool collection is no ex
Version 197 of the systemd startup dae
unveiled a new method for naming
devices. Instead of assigning consecutive
the functionality of several older tools,
but ip also provides a unified syntax
across all the various functions. In con
trast, the utilities provided by the net-
array of useful tools - some overlapping device numbers to network devices, sys tools package are a patchwork collec
and some unique - for configuring, man temd assigns a predictable network de tion of tools that were developed indi
aging, and troubleshooting network vice name based on identifying informa vidually over many years.
connections. tion about the device itself, such as: The ip command is part of the iproute
In this article, we highlight some fa • Information provided in the BIOS package. The similarity between the
vorite tools in the networking collection. • The physical location of the hardware tools in this package enables you to mas
Of course, a full description of the com • The interface’s MAC (hardware) ter the configuration of your network
plete TCP/IP networking environment address more quickly because you do not need
could fill up a very long book. Here, we The system uses this information to as to learn different syntax options for dif
assume you have some basic knowledge sign a unique (and reproducible) num ferent functions. Furthermore, you don’t
of TCP/IP networking concepts such as ber for the device. This number is then need to remember which utility does
routing, addressing, and name combined with a two-character prefix, what because, for the most part, ip inte
resolution. such as en for wired Ethernet or wl for grates the capabilities of ifconfig, route,
wireless LAN. For instance, an Ethernet and arp into a single tool.
Interfaces adapter might have a logical name like The generic usage is
The old method for naming Ethernet enp0s31f6 and a wireless network inter
e adapters and other network devices is face might have the logical name wlp4s0. ip [OPTIONS] <OBJECT> [COMMAND]
£ with a prefix (indicating the device type) The examples in this article use the in
8 followed by a device number. For in- terface name enp0s31f6 - if you try these where OBJECT is something like ip for
5 stance, the first Ethernet adapter discov- commands, change enp0s31f6 to the log your IP configuration, link for a network
| ered by the system took the name ethO, ical name of your own network adapter. interface, addr for your IP address, route
| the next one is ethl, and the third is The ifconfig command was, and still is for routes, and so forth. (The ip command
eth2. This method worked well in most on many systems, the default tool for also supports several other objects - see
| cases; however, it sometimes causes configuring network interfaces. However, the ip man page for more details.)
| complications. For instance, the same ifconfig is often considered obsolete, in In the context of the ip command, a
- device could have a different name at a that newer tools are provided for systems “link” is a network device, real or virtual.
tracepath is part of the iputils package Naturally, you’ll want to replace the IP your host and the destination and pro
that also includes ping. Although tracer address with the appropriate address. If viding an interactive display similar to
oute is the older utility, it has many the path of the packets is inefficient or Figure 4.
more options than tracepath. In es unexpected, route or ip route will show
sence, the only thing you can pass to you what routes are configured. Note Troubleshooting DNS
tracepath is a destination port number. that you only see the route configured The Domain Name System (DNS) trans
On the other hand, traceroute allows from the local machine; it is very possi lates the familiar alphanumeric domain
you to specify time-to-live values, maxi ble the problem might lie elsewhere. names used in email addresses and web
mum hops, a specific interface to use, Possibly a given router is explicitly URLs (such as linux-magazine.com or
and many more options. configured not to provide any details. whitehouse.gov) to and from the numeric
The basic syntax is simple enough: So, for example, tracepath might report IP addresses necessary for TCP/IP net
Use traceroute host and you’ll see a list “no reply. ” This situation does not working. As long as your system knows
ing of the hosts between your computer mean you cannot connect to the target the location of a DNS server, this name
(or the system you are running tracer (which you can verify with ping); it resolution process happens invisibly; how
oute on) and the final destination. Be simply means the intermediate router is ever, sometimes some troubleshooting is
cause you’re using traceroute to check not responding to the request from tra necessary. Also, sometimes for informa
for overall latency and problems, if a cepath (or traceroute). tional purposes, it is important to know
host returns * * * but the packets are The tracepath documentation specifies the IP address associated with a domain
reaching their destination, this is OK. that it is not a “privileged program” and name or the domain name associated with
The maximum TTL (number of hops) can be executed by anyone. Although an IP address. A pair of classic Linux utili
is usually set to 30. You might have more this is true, we have never had any trou ties that allow you to query the DNS sys
than 30 hops between yourself and the ble running traceroute as a normal user, tem are nslookup and host, both of which
final host. To change this, use the -m except that it is usually not in a normal are part of the bind-utils package, ns
option, like so: user search path. lookup provides more functionality and
Other troubleshooting utilities include more extensive output than host; however,
traceroute -m 35 linux-magazine.com the netstat command (which outputs in nslookup is considered outdated and less
formation on connections, routing ta able than some more modem equivalents.
This line would increase the number of bles, and interface statistics) or the A powerful and popular DNS tool in
hops to 35. Adjust as necessary. newer ss utilities. Although ss is part of use today is dig, which is short for “do
You might need to use traceroute to the iproute package, its syntax is differ main information groper. ” Basically, dig
debug specific interfaces on a machine. ent from ip. See the ss man page for performs a DNS lookup and then shows
To do this, you can use -i (interface), -5 more information. the results. The most basic use is
(source address), or both options. A ma
chine could have two or more IP ad Combining ping and dig <hostname>
dresses without actually having more traceroute with mtr
than one interface, or each interface A newer utility is mtr, which also has a which should return quite a bit of out
might have its own address. Therefore, if GTK + front end called xmtr. Depending put, including an answer section with
you want to specify an IP address on a on the distribution you’re running, mtr the hostname and (by default) the IP ad
system’s second Ethernet interface, use: might or might not be installed, mtr is a dress associated with the hostname.
cross between ping and traceroute. It But dig can tell you much more. For
traceroute -i enpOsSlfG -s 7 combines ping and traceroute functions example, if you want to see what DNS
192.168.1.100 by sending a number of packets between servers the domain uses, run dig NS
hostname - this command will return a
list of DNS servers responsible for trans
lating the domain name to an IP address.
In the output, you also see what DNS
server(s) dig has used to perform its
lookups. Here, I’m using Google’s DNS:
file. For help configuring your network 12 10:38:58 iwd systemdd] : Starting Wireless service...
Seo 12 10:38:58 iwd iwd[6294]: Wireless daemon version 1.8
connections, check out the wpa_suppli- 12 10:38:58 iwd systemd[l] : Started Wireless service.
12 10:38:58 iwd iwd[6294]: station: Network configuration is disabled.
cant man page or refer to the wpa_suppli- -■ 12 10:38:58 iwd iwd[6294]: Wiphy: 0, Name: phy0
cant. conf example file if you have one. 12 10:38:58 iwd iwd[6294]: Permanent Address: 10:0b:a9:23:6f:8c
r-J 12 10:38:58 iwd iwd[6294]: Bands: 2.4 GHz 5 GHz
Sep 12 10:38:58 iwd iwd[6294]: Ciphers: CCMP TKIP
Sep 12 10:38:58 iwd iwd[6294]: Supported iftypes: ad-hoc station ap
iwd Sen 12 10:38:58 iwd iwd[6294]: Error bringing interface 4 up: Operation not possible due to RF-kill
WPA Supplicant has seen many im 1 $1
provements through the years, and, in Figure 6: Once WPA Supplicant is shut down, and if iwd always launches at boot time, the
general, it is much easier to connect status query reports an active service. However, the last line indicates that the device
Linux to a wireless network than it interface cannot be enabled.
sudo rfkill unblock wifi Now launch an interactive shell as a Iwd can also be used without an interac
normal user with the iwctl command. tive shell; you just have to prefix each
Check if this worked with rfkill or a new Typing help lists all the available op command with iwctl.
status request for iwd. service. tions. To exit the shell, press Ctrl + D. Use device list to discover the name
the system is using for the interface (Fig
Fl ft@>iwd2:/etc/iwd Q = □ x ure 7). If the interface goes by the name
ft@)lwd2: -/Download... ft(®iwd2: /etc/iwd ft@)iwd2: /etc/iwd ▼
of wlanO. The command
ft@iwd2: $ iwctl
[iwd]# adapter list device wlanO show
Adapters
ONLINEHELPERS
The Linux environment provides command-line tools for many common Internet tasks, such as checking
email, surfing the web, and even searching on Google.
BY BRUCE BYFIELD, CHARLY KUHNAST, HARALD ZISLER, AND JOE CASAD
or many users, the modern In Bash commands are also easy to inte where URL is the URL of the page you
web are also possible from the com Curl (“Client URL”) is an application curl https://www.linux-magazine.com/
mand line. This article investigates for transferring files to or from a server.
some command-line tools for accessing It supports numerous protocols and will This form of the command basically
Internet content. either choose the protocol that seems simulates an HTTP GET request. The
most appropriate to the situation, or the URL doesn’t have to be just a domain
File and Page Downloads one specified in the command structure. name and can also specify the path to
Sometimes it is necessary to download a Curl can download or upload files from a file:
complete web page for later viewing. a server, as well as download HTML
This might be because you will be of pages, fill and submit HTML forms, and curl https://www.linux-magazine.com/P
fline and would like access to the infor read and write cookies. images/picture.jpg
mation while you aren’t connected. Or Curl (Figure 1) is not always installed
maybe some of the information on the by default, so if you don’t have it, you’ll Use the -I option to output headers only:
page is important for your records? Most need to install it with your system’s
web browsers offer some kind of Save As package manager. curl -I https://linux-magazine.com
option to save the current page locally as The most basic form of the command is:
an HTML file, but in many cases, it is This simple form of the command just
more efficient to use the command line. curl URL writes the output to stdout, which
normally means it prints it to the screen. speed, set the number of download at With wget, you can also log in to the site
The -o option saves the output to a file: tempts, and download in the back with a username and password in a
ground (Figure 2). single command:
curl -o homepage.html P The basic command looks a lot like curl:
https://www.linux-magazine.com/ wget —http-user=USERNAME 7
wget URL -http-password=PASSWORD 7
Or if you want to omit the local file https://linux-magazine.com
name and just give the file the same for example, as follows:
name it had on the original, use -O: If you just want the whole thing, the fol
wget https://linux-magazine.com lowing command will let you download an
curl -0 7 entire website:
https://www.linux-magazine.com/3? To download to a file, you use
images/picture.jpg wget -m -k -p -P DIRECTORY URL
wget -o FILENAME URL
This command will download the file In the preceding command, the -m op
to a file called picture.jpg on the local which looks like: tion tells wget to work recursively, and
system. Enter the -h. switch to output to only follow relative links. The -k op
help information, including a summary wget -o homepage.html 7 tion converts any links in the original
of the most important command-line https://www.linux-magazine.com/ document back into links in the down
options. loaded version, the -p tells wget to in
Just as Curl can emulate an HTTP GET To use the same file name as the clude image files and other files needed
request, it can also emulate a PUT re original, use: to complete the page, and the -P lets you
quest, which means you can use it to specify a directory to recreate the direc
write data to a website: wget -0 7 tory structure of the original site at the
https://www.linux-magazine.com/5? target location.
curl —request PUT https://www.URL images/picture.jpg
BitTorrent
Of course, you’ll need the necessary cre If you have a large file, you might want BitTorrent [1] is a protocol for peer-to-
dentials to write the data to a web server. to limit the download speed, so it peer sharing of files. Rather than
Another command for downloading doesn’t suck up all your bandwidth downloading from a single source, Bit
web pages and writing to websites is and processor time: Torrent downloads files from multiple
wget. You often can use curl and wget sites or clients, thereby lessening the
interchangeably, and many readers wget —limit-rate=MBs URL load on any one site and often increas
confuse the two. Strictly, however, curl ing the speed of the download. As well,
is intended for file transfer, and wget where MBs is the rate in MB per second. BitTorrent downloads can be inter
specializes in the download of pages If you don’t want to wait around while rupted and resumed.
and entire sites, making it ideal for the download completes, use the -b op Several command-line interface Bit
backups and the creation of mirrors. tion to download in the background: Torrent clients are available. However,
The two commands share many of the the most popular is aria2c [2], which
same features, but with small differ wget -b https:/linux-magazine.com supports not only BitTorrent but other
ences. For example, wget is aware only
of HTML, XHTML, and CSS pages, and Listing 1: Installing googler
it doesn’t support as many protocols as $ cd Downloads/
curl. Similarly, although both com $ wget -c https://github.com/jarun/googler/archive/refs/tags/v‘1.3.2.tar.gz
mands use the -o and -O options for $ tar -xvf v(4.3.2.tar.gz
naming file downloads, using the same
$ cd googler-a.3.2/
option for entire sites puts all the
$ sudo make install
source files into a single file. In addi
$ cd auto-completion/bash/
tion, wget offers more control over
$ sudo cp googler-completion.bash /etc/bash_completion.d/
downloads, allowing users to limit the
Figure 2: One of the advantages of wget is its control over download settings, such as the download speed.
googler TERM
If you do not want to leave any data configuration files by adding com If you are using an IMAP server, add:
traces when searching the web, take a mands and a few fields.
look at ddgr [4]. The ddgr utility comes To begin configuring, create the basic set smtp_url = "EMAIL-ADDRESS:PORT/"
from the same author as googler, supports directories and the configuration file: set smtp_pass = "PASSWORD"
(almost) the same parameters, but uses set imap_pass = "PASSWORD"
DuckDuckGo and is therefore far more mkdir -p ~/.mutt/cache/headers set folder = "PATH:PORT"
careful in terms of data handling. mkdir ~/.mutt/cache/bodies set spoolfile = "+INB0X"
touch ~/.mutt/certificates set record = +Sent
Email with Mutt mailboxes = +INB0X
Linux has no shortage of email clients The configuration file, muttrc, can have bind index imap-fetch-mail
that run from the command line. One several locations that are detected auto
of the most common is Mutt [5]. First matically: ~/.muttrc, ~/.mutt/muttrc, For folder, use the directory where mes
release in 1995, Mutt is one of the old and $XDG_CONFIG_HOME/mutt/mut- sages are stored; spoolfile is where Mutt
est email clients available for Linux. trc, each with or without -MUTT_VER- looks for incoming mail. The port is only
Fully controlled from the keyboard, it SION appended. Use touch, to create the needed if the folder is not local. The plus
also has the option for a GUI-like side- muttrc file with the path of your choice. sign indicates that any subdirectories
bar, as well as extensive configuration For example, you can use: will be used as necessary.
options and a choice of external editors Finally, set the mbox type and the struc
for email composition. Mutt is often touch ~/.mutt/muttrc ture for receiving messages as follows:
the choice of those who want wide
spread customization, or, because of If you want to place muttrc in a nonstan set mbox_type=Maildir [or Mbox]
its small footprint, its relative security. dard place, set the location by adding to set folder=~/mail
Mutt is configured in /etc/Muttrc, muttrc the line: set spoolfile=+/
which, among other things, contains set header_cache=~/.cache/mutt
the senders name and email. source /path/to/other/config/file
In deference to its age, Mutt is in where spoolfile should be the same as
cluded in the repositories of most dis Next, open the newly made muttrc in a the spool file set for IMAP; header_cache
tributions. Preparing it for use con text editor. Add the settings in Listing 2 stores email headers to increase the
sists primarily of editing its to set up Mutt’s environment. speed in which headers are displayed.
Do you still have the rose-breasted cockatoo you advertised recently? Qf so,
what is your asking price?
Thanks
Figure 5: Mutt can use any command-line editor, including Vim, Emacs, nano, or JOE (shown here).
n: nail
1870 Dec 06 Cron Daemon 1 KU Cron <root@nanday> /usr/lib/prey/prey.sh >/var/log/prey.l|
1871 0 Dec 07 Anae ron : i) Anacron job 'trim.weekly' on nanday
1872 0 Dec 14 Anacron : i) Anacron job 'trim.weekly' on nanday
1873 0 Dec 19 Anae ron : 23) Anacron job 'cron.monthly' on nanday
1874 0 Dec 21 Anacron : i) Anacron job 'trim.weekly' on nanday
1875 0 Dec 28 Anacron : i) Anacron job 'trim.weekly' on nanday
1876 0 Jan 04 Anacron : i) Anacron job 'trim.weekly' on nanday
1877 0 Jan 11 Anacron : i) Anacron job 'trim.weekly' on nanday
1878 0 Jan 15 Cron Daemon : 4) Cron <root@nanday> /usr/lib/prey/prey.sh >/var/log/prey.l
1879 0 Jan 18 Anacron : i) Anacron job 'trim.weekly' on nanday
1880 0 Jan 19 Anacron : 23) Anacron job 'cron.monthly' on nanday
1881 N + Jan 20 Mail Delivery S : 45) Mail delivery failed: returning message to sender
1882 N Jan 25 Anacron : i) Anacron job 'trim.weekly' on nanday
1883 N + Jan 25 Mail Delivery S : 46) Mail delivery failed: returning message to sender
1884 N + Jan 25 Mail Delivery S : si) Mail delivery failed: returning message to sender
Figure 6: Mutt can run from the command line, or, more conveniently, through a keyboard-navigated text interface.
-- Attachments
|- I 1 /tmp/mutt-nanday-1000-5293-7860455411086 [text/plain, 7bit, us-ascii, 0.2K]|
Figure 7: Before you send an email, Mutt gives you one last chance to edit the headers and displays a summary of the email.
dd@vm-ubu1710d-x64: -
Before you go The sort file determines whether
File Edit View Search Terminal Help
» Linux Magazine (pl of 11) any further, send a aliases are listed by alias or address,
Link:
Link: tnage_src message to check while reverse_alias set to yes displays
[IMG]
whether you have the long name if one is given. Adding
search: search______________ basic functional the source allows Mutt to autocom
* News
* * Features ity. If you made plete when you enter an alias for the
* * Blogs
* * White Papers any typos during To: field. If the alias you enter is non
* * Archives
* * Special Editions setup, it will be existent, a list of all aliases displays.
* * DigiSub easier to trouble If you want a more sophisticated ad
* * Shop
* Desktop
* Development
shoot before you dress book, you can use an external ap
* Hardware
* Security
add more to your plication, such as Abook, GooBook, or
configuration. Khard.
* Programming
* Operating Systems Store account To create a signature that is added au
* Software
passwords inter tomatically to the end of every message,
Figure 8: Links2 in text mode on the Linux Magazine website. nally with: add the following line to muttre:
separate email editor or add the tags described as the attachment of a file this article, the web browsers are the
manually. stored in /tmp/mutt (Figure 7). Press y least functional when compared to their
You can send an email message di when you are ready to send the graphical counterparts.
rectly from the command line with the message. A brief introduction to a couple of
following command: the command-line browsers will give
Web Browsers you an indication of what they are like,
mutt OPTIONS "RECIPIENT-OR-ALIAS" Several web browsers are available for but keep in mind that the idea of a
the Linux command
See Table 1 for a summary of important line, notably Lynx [7], Table 3: Links2 Control
command-line options. w3m [8], Links2 [9], Task Key
When you press the Enter key, Mutt and ELinks [10]. All Switch on menu [F9] or [Esc]
asks for confirmation of the options and four of these browsers
File menu [F10]
then opens in the default editor so that use the same basic
Next link [arrow down]
you can type the message (Figure 5). command structure:
Previous link [arrow up]
The -R option lets you open a mailbox
and select a message to reply to. If you command URL Next page Page Down
are unsure of the available mailboxes, Previous page Page Up
typing -y will provide a list of available All, too emphasize text Next frame [Tab]
ones. If necessary, -f MAILBOX sets the and are designed for Scroll downwards [Del]
current mailbox. those who want to read Scroll upwards [Ins]
An easier way to use Mutt is to type the text-heavy pages such Scroll right Right ]
basic command mutt, which opens a text as Wikipedia rather Scroll left Right [
based interface (Figure 6). The interface is than use images or
Top of page [Home]
entirely mouse driven, with a list of avail sound. As well, many
Bottom of page [End]
able actions along the top, and a summary command-line web
of the current mailbox along the bottom. browsers do not support Input Enter key
When Mutt runs from the command line, JavaScript or the latest Search (forward) /
pressing m to start a message runs you HTML standard. You Search (backward) 7
through a series of prompts for the headers can navigate all of these Next hit n
and then opens Mutt’s default editor. browsers using the Previous hit N
When you are finished writing your arrow keys. Do not ex Reload page [Ctrl]+[Shift]+[R]
message in the editor, save the file and pect command-line web Goto new URL g
quit the editor (the exact commands for browsers to have the
Goto URL G
doing so depend on the editor). A screen complete functionality
Download D
appears in which you can make last min of a desktop browser. Of
View Source code/formatted \
ute changes, using the options listed at all the command-line In
the top of the page, with the message ternet tools described in Quit program Q
INFO
[1] BitTorrent: https://en.wikipedia.org/
wiki/BitTorrent
[2] aria2c: http://aria2.github.io/manual/
en/htm l/aria2c.htmi
[3] googler: https://github.com/jarun/
googler
[4] ddgr: https://github.com/jarun/ddgr
[5] Mutt: http://www.mutt.org/
[6] muttrc man page: https://linux.die.
net/man/5/muttrc
[7] Lynx: https://invisible-mirror.net/
archives/lynx/
[8] w3m: https://w3m.sourceforge.net/
[9] Links2: http://atrey.karlin.mff.cuni.cz/
~clock/twibright/links
Figure 10: w3m in text mode on the internal Figure 11: w3m with graphic display on the
[10] E Li nks: http://elinks. or. cz/
test page. Linux Magazine website.
FnbiSSfe i
Secure connections with SSH
?
TUNNEL BUILDER
Manage your server from a distance with this convenient and secure remote access toolkit.
BY JORG HARMUTH, DMITRI POPOV, HEIKE JURZIK, AND JOE CASAD
he SSH client/server architecture Open sshd_config for editing using your spoofing a genuine login to your ma
debian:-# ssh sector program will need to enter the password for the SSH
The authenticity of host 'sector (192.168.10.10©)' can't be established.
then tell you key to copy the data - so much for au
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes where it has tomated copying.
Warning: Permanently added 'sector, 192.168.10.1O0' (RSA) to the list of known host
Password: stored the data Typing SSH commands like
Last login: Tue Sep 27 14:45:53 2005 from 192.168.10.254
and will display
the fingerprint ssh -p 1777 pi@192.168.101
Figure 1: On initial login, SSH imports the host key. for the new key.
In the example can become a nuisance if you have to do
debian:-# ssh sector
here, the soft this several times a day. Fortunately, you
WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! ware generates can solve this problem by defining SSH
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! an RSA keypair aliases for often-used SSH connections in
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed. (-t rsa) with a the ~/.ssh/configii\e:
The fingerprint for the RSA key sent by the remote host is
length of 2048
Please contact your system administrator. bits (-b 2048). Host alias
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending key in /root/.ssh/known_hosts: 1 For security rea HostName ipaddress
RSA host key for sector has changed and you have requested strict checking.
Host key verification failed. sons, the key User username
length should Port portnumber
Figure 2: If the host key changes, the SSH client will refuse to connect. not be less than
2048 bits. To be Replace alias with the desired alias
machine. To configure this behavior, absolutely safe, you can use a key length name, ipaddress with the IP address or
use the StrictHostKeyChecking variable of 4096 bits. The key length has no influ domain name of the server, username
in ssh_config. ence on the data transfer speed because with the actual username, and port
If you do not want to use your current the program does not use this key to en number with the appropriate port
account name to log in to the remote ma crypt the data. number:
chine, the -I login_name option can help. Next, copy the public key to the
For example, the command $HOME/.ssh/ authorized_keys file on Host raspberrypi
the remote machine from, for example, HostName 192.168.1.101
ssh -1 tuppes sector a floppy disk: User pi
Port 1777
logs you in to the remote machine as mount /media/floppy
user tuppes. SSH also accepts the syn cat /media/floppy/id.rsa.pub P You need to specify the Port parameter
tax ssh tuppes@sector. To run a single > > $H0ME/.ssh/authorized_keys only if the SSH server is running on any
command on the remote machine, you amount /media/floppy port other than 22.
simply append it to the command line
(Listing 1). Certainly you should avoid transfer File Transfer
If you get tired of typing your pass ring the key by an insecure method, The SSH package includes two more
word, public key authentication providessuch as email or FTP. Figure 3 shows useful programs: Secure Copy (scp) and
an alternative. This technique uses en the fairly unspectacular login with the Secure FTP (sftp). You can use scp and
cryption methods such as those used by new key. sftp to copy and transfer files over a se
GnuPG. Before you can use the public Passwords protect keys for interactive cure connection, scp was developed as
key approach, you first need to run sessions; otherwise, anybody with a secure version of the classic file copy
ssh-keygen to generate a pair of keys: physical access to your computer could command cp. sftp is a secure version of
use your keys to log in to the remote the File Transfer Protocol (FTP) utility,
ssh-keygen -b 2048 -t rsa machine. Key-based, password-free log which was used for many years to post,
ins are often used to automate copying download, and move files on the Inter
The software will tell you that it has of files to remote machines. net and other TCP/IP networks. The
created a keypair with a public key and For example, if you back up your data sftp command lets you use FTP over a
a private key on the basis of the RSA every evening and want to copy it auto secure SSH connection.
approach. When prompted to enter a matically to a remote machine, keys To copy test.txt from your home direc
password, press Enlter twice. The without passwords are a useful ap tory on the remote machine to your cur
proach. If the key rent working directory using scp, enter:
Listing 1: Running Commands on the was password pro
Remote Machine tected, you would scp RemoteComputer:test.txt .
jha@scotti:~$ ssh sector "Is -1"
Password: debian:-# ssh sector
Last login: Wed Sep 28 13:36:22 2005 from 192.168.10.254
insgesamt 52 SECTOR;|
Drwxr-xr-x 3 tuppes users 4096 2005-08-26 12:38 .
Drwxr-xr-x 16 root root 4096 2005-09-07 13:47 .. Figure 3: Public key authentication makes the login more user friendly
-rw-rw-r— 1 tuppes users 266 2005-04-12 12:00 .alias
by removing the password prompt.
Depending on your authentication an FTP session. To use sftp to retrieve mget and mput to retrieve or send multiple
method, you might need to enter your the sample file from the remote machine files at once using wildcards. To shovel all
password; however, the colon is manda in automatic retrieval mode, type: the files in a specific remote directory onto
tory in all cases. It separates the name of your local machine, you would type:
the remote machine from the path name. sftp user@RemoteComputer:test.txt .
Also, you need to specify the local path. sftp> mget *
The easiest case is your current working where user is the name of the user ac
directory, which is represented by the count. If you add remote_test.txt to the Of course, you can be more precise if
dot at the end of the line. To copy multi end, the program will give that name the you like; for example,
ple files, just type a blank-delimited list local copy of the file.
of the file names: Typing sftp RemoteComputer opens an sftp> mget *.tar.gz
interactive, encrypted FTP session on the
scp BemoteComputerA:testl.txt P remote machine, and the server will then will download all files with the .tar.gz
RemoteComputerB:t est 2.txt . accept FTP commands. Alternatively, extension.
you can add the username to the Enter bye, exit, or quit to quit sftp.
If you use the standard login approach, command: sftp also supports several of the stan
the client will prompt you to enter your dard file management commands used
password for each file you copy. If you sftp user@RemoteComputer in the Bash shell. You can create a di
use the public key method discussed rectory with mkdir (or Imkdir for the
previously, you don’t need to type a To discover the current directory on the local system) and remove files and di
password. The command remote computer, enter pwd (print work rectories with rm and rmdir. See the
ing directory) as in Bash; to learn the article elsewhere in this issue on “File
scp RemoteComputerA:test.txt 7 current directory on the local computer, Management.” Also, see the article on
RemoteComputerB: enter Ipivd. The familiar Is command “Users, Groups, and Permissions” for
outputs a current directory listing on the more on changing file permissions
copies the file from remote computer A remote system; Ils shows a list of files in (chmod), changing file ownership
to remote computer B. To copy a file as the current directory of the local system. (chowri), and changing group member
tuppes from /home/tuppes/files to your Use cd [directory] to change directories ship (chgrpi), which are also possible
local directory, type: on the remote computer, cd.. climbs up using sftp.
one level in the directory tree, and cd / The / character lets you execute a
scp tuppes@RemoteComputer: takes you to the root directory on the shell command on the local system. If
files/test.txt . FTP server. On the local computer, you Bash is your local shell, you can actu
can change directories with led. ally execute almost any of the com
The program assumes you are copying Once you have navigated to the de mands in this issue from within an sftp
from the user’s home directory if the path sired remote directory, use the get com session if you precede the command
after the colon doesn’t start with a slash/. mand to copy a file from the remote sys with /. For instance, suppose you want
If you want to specify a location that isn’t tem to the local system. The command: to upload the file OdeToBash.txt, but
in the user’s home directory, use an abso you aren’t sure which subdirectory of
lute path beginning with a slash. For in sftp> get mammoth.txt your home directory it is in. You could
stance, if you want to copy a file from the find the exact location of the file while
/etc/cups directory of the remote machine: downloads the mam.moth.txt file from the inside an sftp session by typing:
current remote directory to the current
scp tuppes@)RemoteComputer: 7 local directory. You can specify the target sftp> (find ~ -name OdeToBash.txt
/etc/cups/file_name.txt . file name as well as the source file:
Alternatively, enter / on a line by itself to
Unlike SSH, you do not specify the -I user- sftp> get mammothl.txt mammoth2.txt escape to a local shell session. From
name option. Copying in the other direc there, you can work normally at the
tion - local to remote - is just as easy: The preceding command copies the file Bash command line and then type exit to
mammothl.txt from the remote directory return to the sftp session.
scp ./test.txt 7 and names the file mammoth2.txt on the For a complete list of sftp commands,
tuppes@RemoteComputer:files local system. type help or ? at the sftp prompt.
The put command moves files from
scp copies the test.txt file from your cur the local system to the remote server: Conclusions
rent working directory to /home/tuppes/ The SSH package includes a collection of
files on the remote machine. Again, sftp> put mastodon.txt important programs that make working
watch out for the closing colon. sftp> put mastodonl.txt mastodon2.txt on networks far more secure. The feature
The sftp tool supports an automatic re scope covers anything from basic en
trieval mode, which is similar to scp, and Some (but not all) sftp implementations let crypted connections, through tunneling
an interactive mode, which behaves like you use the alternative FTP commands and port forwarding, to Xll forwarding. ■
sync is the perfect synchroniza $ rsync dirl/* dir2/ timestamps - that is, information on the
Cron and At keep your tasks on task Users who are not listed in at.allow there
fore receive the message You do not have
permission to use at.
ON THE DOT
The cron and at utilities help automate processes on a Linux system.
A cron for All Seasons
If you are looking for a way to handle reg
ularly recurring tasks, repeatedly running
At is not recommended. Instead, you
BY HEIKE JURZIK should investigate the other option that
Linux gives you. Cron also runs in the
he Linux environment includes output by default (e.g., rm, mv, or cp), you
background and runs jobs at regular inter
$ crontab -1 7
A combination of times can also be useful. 25 17 * * * root
10 8 * * mon-fri oggl23 -Zz 7
You can specify a range with a dash (1-5), test -x /usr/sbin/anacron || 7
/home/huhn/mus ic/*
but weekday names are easier to read: ( cd / && run-parts --report 7
/etc/cron.daily )
Cron Alternatives
Several GUI-based tools will help you cre
ate a cron table. Gnome users have Gnome
Schedule (packagegnome-schedule), an
easy-to-use program that lets you put to
gether at and cron tasks with a few mouse
clicks. The KDE tool is KCron (System Set
tings | Startup and Shutdown | Task Sched
uler.) . KCron lets you modify the system-
wide crontab, as well as cron and At sched
ules for certain user accounts (Figure 1).
In the end (and as in most cases), the
command line gives you much more flex
ibility, and you can type entries much
faster than if you were to click and point.
Alternatives such as Anacron and Fcron
Figure 1: KDE provides a convenient dialog for managing cron and At settings. are available online or through your dis-
tro's package manager. Some of
these tools provide enhanced
scheduling features and even
offer a way to "catch up" by exe
cuting tasks that were scheduled
to run when the system was
turned off. ■
CUSTOM SCRIPT
how it is run slightly (Listing 2). The first £
command argument is assumed to be the 2
name of a file containing a list of directo- |
ries to back up. Additional arguments are q
A few scripting tricks will help you save time by automating common treated as literal items to be backed up. °
tasks. BY /ELEEN FRISCH DIRS and OUTFILE are variables used «
within the script. I’ll use the convention
of uppercase variable names to make
hell scripts are a lazy person’s best The second command runs the script, them easy to identify, but this is not re
of a more sophisticated script that restores than the specified patterns (i.e., other the script’s first argument followed by 1:
this checking and provides more flexibility. than n, b, f, d, or:). The commands to ${1}1. The syntax also enables variables
This version uses the getopts feature built process the various options differ, and to be isolated from surrounding text: If the
into Bash to process arguments quickly. each section ends with two semicolons. value of ANIMAL is cat, then $ {ANI
The first two commands assign values From the commands, you can see that -n MAL }2 expands to cat2, whereas $ANI-
to DEST and PREFIX, which specify the di specifies the archive name prefix (over MAL2 refers to the value of the variable
rectory where the tar archive should be riding the default set in the script’s sec ANIMAL2, which is probably undefined.
written and the archive name prefix (to be ond command), -b says to use bzip2 Note that periods are not interpreted as
followed by a date-based string). The rest rather than gzip for compression (as part of variable names (as shown later).
of this part of the script is a while loop: shown later), -/‘specifies the file contain The :0:l following the variable name
ing the list of items to be backed up, and extracts the substring from OPTARG be
while condition-and; -d specifies the destination directory for ginning at the first position (character
commands the archive file (which defaults to /save numbering starts at 0) and continuing
done as before via the first command). for 1 character: in other words, its first
The destination directory is checked to character. The if command checks
The loop continues as long as the condi make sure that it is an absolute pathname. whether this character is a forward
tion is true and exits once it becomes false. The construct ${OPTARG:0:1} deserves slash, displaying an error message if it is
Here, the condition is getopts "f:bn:d:" special attention. The most general form of not and exiting the script with a status
OPT. Conditional expressions are enclosed $ substitution places curly braces around value of 1, indicating an error termina
in square brackets (as seen in the preced the item being dereferenced: $1 can be tion (0 is the status code for success).
ing and following if statements), but full written as ${1}, and SCAT as ${CAT}. When an option requiring an argument
commands are not (technically, the square This syntax is useful. It allows you to ac doesn’t have one, getopts sets the vari
brackets invoke the test command). Com cess positional parameters beyond the able OPT to a colon and the correspond
mands are true while returning output, ninth; ${11} specifies the script’s 11th pa ing option string is put into OPTARGS.
and false when their output is exhausted. rameter, for example, but $11 expands to The penultimate section of the case state-
The getopts tool returns each com
mand-line option, along with any argu
ments. The option letter is placed into
the variable specified as getopts’ second
argument - here OPT - and any argu
ment is placed into OPTARG. getopts’
first argument is a string that lists valid
option letters (it is case sensitive); letters
followed by colons require an argument
- in this case, f, n, and d. When speci
fied on the command line, option letters
are followed by a hyphen.
The command inside the while loop is
a case statement. This statement type
checks the value of the item specified as
its argument - here, the variable OPT set
by getopts - against the series of pat
terns specified below. Each pattern is a
string, possibly containing wildcards,
terminated by a closing parenthesis. Or
dering is important because the first
matching pattern wins.
In this example, the patterns are the
valid option letters, a colon, and an as
terisk wildcard matching anything other
tory locations for a set of users. The files • The definition of TMPLIST uses com command include file mechanism. The
containing the list of users and the directo mand substitution to store the size field function is stored in functions.bash.
ries to examine are specified explicitly in (again via awk) from all lines of Is -IR The to_gb function in Listing 7 begins by
the script, but you could also use options. output corresponding to items owned by defining local variables. The function will
The script sets the path and incorporates the current user (identified by egrep). ignore any meaning the names might have
another file into the script via the so-called The Is command runs over the directo in the calling script, and their values also
dot command include file mechanism. ries specified in the ckdirs file and uses will not be carried back into the calling
A number of items are notable: the -block-size option to make its size script. The bulk of the function comprises
• The for command specifies a variable, display unit match that used by du (KB). arithmetic operations using $((... )). Bash
the keyword in, a list of items, and the TMPLIST is a list of numbers: one per provides only integer arithmetic, but I
separate command do. Each time file owned by the current user ($WHO). want to display a reasonably accurate size
through the loop (ending with done), • The second for adds numbers in TMP total in gigabytes, so I use a standard trick
the variable is assigned to the next item LIST to TSUM. The variable is N, and to extract the integer and remainder parts
in the list. WHO is assigned to each suc the list of items is the value of TMPLIST. of the gigabyte value and build the display
cessive item in the ckusers file. The con • The script twice provides built-in manually. For example, if I have 2987MB,
struct $(< file) is short for $(cat file). integer arithmetic via the construct dividing by 1024 would yield 2GB, so in
• The definition of HOMESUM uses back $(( math-expression )). stead, I divide 2987 by 1000 (DI = 2) and
quotes to extract the total size of the us • The script uses the function to_gb to then compute 2987 - (2* 1000) (D2 = 987).
er’s home directory from the output of print each report line. Bash requires that Then, I print DI, a decimal point, and the
du. -s via aivk. eval makes du interpret functions be defined before they are first character of D2:2.9.
the expanded version of ~ $WHO as a used, so functions are typically stored in The printf command creates formatted
tilde home directory specifier. external files and invoked with the dot output. It requires a format string followed
by variables to be printed. Code letters The loop I starting value is the first script An array can be defined by enclosing its
preceded by percent signs in the format variable. At the end of each iteration, I is elements in parentheses. Specific array el
string indicate where the variable content decreased by 1, and the loop continues ements are specified using the syntax in
goes. Here, %s indicates each location and as long as I is greater than 1. The body the second line: The array name is inside
that the variable should be printed as a of the loop multiplies F (set to 1 initially) the curly braces, and the desired element
character string. The \t and \n within the by each successive I. is specified in square brackets. Note that
format string respectively correspond to a element numbering begins at 0. Under
tab and newline, which you must include Generating Menus normal circumstances, the number of ele
explicitly when you want the line to end. The final script illustrates Bash’s built-in ments in an array is given by ${#a[@]}.
Here is sample output from the script: menu generation capability via its select PKGS is defined as an array consisting of
command (Listing 8). Setup for the select the second field in each line in the file.
USER GB USED command happens in the definitions of The select command uses the contents
aeleen 80.S PKGS and MENU. The select command re of MENU as its list. It will construct a
kyrre 14.3 quires a list of items as its second argu numbered text menu from the list items
ment, and MENU will serve that purpose. and then prompt the user for a selection.
Another kind of for loop, similar to that It is defined via a command substitution The item selected is returned in the vari
found in many programming languages, construct. Here, I add the literal string able specified before in (here WHAT),
supplies a loop variable, its starting value, Done to the end of the list. and the item number is returned in the
a continuation condition, and an expres The definition of PKGS introduces a variable REPLY.
sion indicating how the variable should be new feature: arrays. An array is a data The script will use the value of REPLY
modified after each loop iteration structure containing multiple items that minus 1 to retrieve the corresponding
can be referenced by an index: package name from the PKGS array in
F=1 the variable PICKED (I use $REPLY-1, be
for (( I=$l ; I>1 ; I— )); do a=(l 2 3 4 5) cause menu numbering begins at 1, al
F=$(( $F*$I )) $ echo ${a[2]} though array element numbering begins
done 3 at 0). The select command exits when
the user picks the Done item.
Listing 6: Reporting on Disk Space The following is an example run:
01 #!/bin/bash
02 1) CD/MP3_Player 3) Photo_Album
03 PATH=/bin:/usr/bin # set the path 2) Spider_Solitaire 4) Done
04 . /usr/local/sbin/functions.bash # . f => include file f here
#? 2
05
Installing package spider ... 7
06 printf "USER\tGB USED\n" # print report header line
07 for WHO in $(</usr/local/sbin/ckusers); do Please be patient!
08 H0MESUM='eval du -s ~$WH0 | awk ’{print $1}’' many more messages ...
09 TMPLIST=$( Is -1R —block-size 1024 $(</usr/local/bin/ckdirs) | #? 4
10 egrep "A................ +[0-9]+ $WH0" | awk ’{print $5}’ )
11 TSUM=0 Conclusion
12 for N in $TMPLIST; do
13 TSUM=$(( $TSUM+$N ))
You can use the techniques described in
14 done this article to build your own Bash scripts
15 TOT=$(( $HOMESUM+$TSUM )) for automating common tasks. Be sure to
16 to_gb $WH0 $TOT check out Table 1 for a quick reference on
17 done
Bash scripting terms. ■
Editing Commands to use -annotate or -draw. To add cap you have a large number of files, this
The basic editing commands in Im tions, you first need a file with the font shell command lets you convert them all
ageMagick are convert and mogrify. The you want to use, preferably in a Tru at once:
main difference between the two is that eType format [.ttf). The @ symbol be
convert produces a new output file, fore the file name in Listing 1 tells con for i in *.jpg; P
whereas mogrify writes over the original. vert that it is dealing with a TrueType do convert $i P
The available options each have their font. The rest of the command places the $(basename $i .jpg).tiff; P
own set of possible values [3]. Some op text Vacation in the mountains (with done
tions, like -debug and -verbose, provide -draw) at position [100, 150) in black.
troubleshooting information and help you with a point size of 20 pixels [-pointsize For each file ending with .jpg, the shell
keep track of what you are doing, but most 20) in the font.ttf font. removes the extension, replaces it with
options are editing functions comparable The color specified after -fill [black) .tiff, and calls convert with the results.
to those you would find in a desktop can also be entered as the corresponding To convert all of your vacation photos
graphics editor. For instance, you can use RGB values in decimal triplet, rgb(0,0,0), into thumbnails, use:
-border [geometry] and -bordercolor [color] or hexadecimal notation, ”#000000".
to place a border around an image. The command for i in *.tiff; P
Other options are -contrast to improve do convert $i P
its appearance, -crop [geometry] to shear convert -list color -resize 800x600 P
it, -flip to reverse its sides, or -size [width] $(basename $i .tiff).png; P
x[height] to alter its dimensions. lists all the known color names and their done
ImageMagick even has a limited num RGB values.
ber of filters to distort an image by adding Scaling. Monster images do not fit on The command reduces the size of the
interesting effects. For example, you can most monitors; plus, they eat up disk images to a monitor-friendly 800x600
use -blend [percent] to overlay one image space. The command pixels and simultaneously converts them
over the top of another, -paint to simulate into the space-saving PNG format.
an oil painting, or -sepia-tone to make an convert -resize 200x200 P
image resemble an old photograph. photo.tiff small-photo.png Graphical Interface
Additional options range from those that To see the changes you have made to
anybody can use to those requiring a strong reduces photo, tiff to 200x200 pixels - or an image, you can use the display
knowledge of color theory. The following rather, it tries to. To prevent distortions, command, which puts an image on
sampling of commands should give you a convert confines itself only to the dimen your desktop. By default, all the files
good idea of the power of ImageMagick. sions specified. An image that was origi indicated in the command are dis
File conversion. Like all of its com nally 3264x2448 pixels ends up at 320x100 played at their full size in separate
panions in the ImageMagick package, pixels. If it is imperative that the image windows, but you can also view them
convert independently detects the target measure 200x200 pixels, even if it turns in a single window with a command
file format by its extension. Each appli out distorted in the end, place an exclama such as
cation knows that a photo named tion mark after the size [-resize 200x200!).
image.jpg is a JPEG photo. If the con Alternatively, you can work with percent composite 'vid:*.png'
verted file needs an exotic ending for age values (e.g., -resize 75%)
some reason (e.g., exot.exo), simply put which displays all the files in the current
the format at the beginning of the file Compositing directory that have a PNG extension.
name (e.g., TIFF:exot.exo). Moving beyond basic editing, the com If you click on a window created for a
Rotation. The -rotate option, of course, posite command overlays one image on single image, a floating window with a
rotates images. For example, the command another, which could also be used as a menu opens (Figure 3), providing easy
way to watermark your photos: access to the options that most users are
mogrify -rotate "90>" image.tiff likely to want.
composite parrot.png P Almost every major programming lan
rotates image, tiff clockwise 90 degrees. painting.png combined.png guage has implemented a slightly more
Note that if you do not use the quotation sophisticated interface [4], ranging from
marks, the shell will interpret the angle If you want to position parrot.png more C’s MagickWand to Java’s JMagick and
bracket as a redirect and delete image, tiff. exactly, you could add the -gravity Ruby’s RMagick. If you are curious, you
Captions. The -caption option just [value] option, which takes values such can see an example of PeriMagick at Im
makes a metadata entry, so if you want a as Center, East, or Southwest (Figure 2). ageMagick Studio [5].
caption under or on the image, you need Thumbnails provide an overview of
Batch your images so you can locate specific
Listing 1: Adding a Caption Processing photos easily. The command
convert -font (ffi/home/tim/fonts/font.ttf -pointsize 20 A real strength of the
-fill black -draw "text 100, 150 'Vacation in the command line is montage -label '%f' *.png P
mountains'" image.tiff caption.tiff
batch processing. If -frame 5 overview.png
mkisofs................................... 65-66
mklabel, Parted............................. 31
rescue, Parted............................... 31
resize, Parted.................................31
u
IDE devices................................... 34 UEFI
mkpartfs, Parted.......................... 31 rfkill................................................. 72
if........................................................88 GPT.....................................30
mkpart, Parted.............................. 31 rm......................................7, 9, 10, 8
ifconfig............................................ 67 UID.................................................39
rmdir...................................... 7, 9, 8
ImageMagick mkswap......................................... 33
route................................................ 67 umask.............................................. 7,42
compare...............................93 modinfo......................................... 26
RPM packages.............................. 61 umount.............................34, 35, 66
composite................................ 94 modprobe....................................... 26
rsync....................................... 84, 85 uname............................................ 26
convert.............................. 93, 94 mount..................34, 34-35, 34-35
uninstall software................ 60, 62
display.......................................94 move, Parted.................................. 31 s uniq................................................. 24
identify......................................93 mtr...................................................70 s bit................................................. 41
units................................................ 46
import........................................ 93 mutt................................................. 79 sep....................................................82
universal package managers ... 64
mogrify..................................... 93 Mutt......................................... 77, 78 search, DNF................................... 63
select...............................................92 unset................................................ 19
montage.................................... 94 mv.........................................9, 10,11
Table of commands............... 93 select, Parted.................................31 update, APT.................................. 61
man pages........................................ 8
Regular expressions .... 14,15, 16 top............................................. 54-55 z
Table of regex operators..... 15 touch............................................... 10
Master Boot Record.....................30 zcat................................................... 10
reinstall, DNF............................... 63 tput...................................................21
MBR................................................ 30 zemp................................................ 10
removable media.........................34 tr...................................................... 25
convert to GPT....................... 30 zdiff..................................................10
remove, APT..................................60 tracepath........................................ 69
metapackages....................... 58, 62 remove software................... 60, 62 traceroute................................ 69, 70 zegrep.............................................. 10
mkdir............................................ 7, 8 renice........................................ 55-56 tune2fs............................................ 33 zfgrep.............................................. 10
mkfs........................................32, 33 repositories, Debian................... 60 type....................................................8 zgrep............................................... 10
LINUX ® ^SUBSCRIBE
I^MAGAZINE^f
Artificial^
Intelligence
Real-world
machine learning
shop.linuxnewmedia.com/subs
. :k I __
CircuitMess Nibble: Get started
- with microcontroller programming
Expand your Linux skills:
• In-depth articles on trending topics,
Bluetooth Tricks
Connect your Rasp Pi
including Bitcoin, ransomware, cloud
i
to a smartphone
SSH Front Ends Quantum
computing, and more!
|
|
Clean Code
Tips for better coding Computing
Raspberry Pi Tricks> | one • How-tos and tutorials on useful tools
*" Go wireless with Bluetooth
Follow us
@linux pro © Linux Magazine
cd jockeyjs
git status
।ruby-1.9.3-pl94| Homebase in -/workspace
friend.memories steggybot
terminal-screenshots
apartmentlist inrkpvis
AutolayoutCoUectionViewIssue
Contentment
DynamicResizeUITextView
justANudge basb-lt-theme-screenshots
TestuserDefaults run.distance
drugs-and-booze-check
WhereTheHellAreYouiOS facebook_event_gcal
XcodeOocExpander
o . cd jockeyjs
|f„b,-1.9.3-P 'desktop
Be an expert
Use Bash shell on a TUXEDO
With a TUXEDO, you get your Linux laptop delivered to your home
customized, and with the Linux Shell Handbook you have tons of tips
and tricks at your fingertips on how to further configure your TUXEDO
the way you like it.
100%
5
Year Lifetime Built in Germany Local
Linux Warranty Support Germany Privacy Support
IuXedo
tuxedocomputers.com