100% found this document useful (2 votes)
14 views

The MagPi Essentials Conquer the commandline the Raspberry terminal guide Second Edition Raspberry download

The document is a promotional overview for various Raspberry Pi-related ebooks, including 'Conquer the Command Line,' which teaches users how to effectively use the command line interface on Raspberry Pi. It emphasizes the advantages of command line usage over graphical interfaces for executing complex tasks efficiently. Additional resources and guides for programming, networking, and projects are also mentioned, catering to both beginners and advanced users.

Uploaded by

mamonjoerg8r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
14 views

The MagPi Essentials Conquer the commandline the Raspberry terminal guide Second Edition Raspberry download

The document is a promotional overview for various Raspberry Pi-related ebooks, including 'Conquer the Command Line,' which teaches users how to effectively use the command line interface on Raspberry Pi. It emphasizes the advantages of command line usage over graphical interfaces for executing complex tasks efficiently. Additional resources and guides for programming, networking, and projects are also mentioned, catering to both beginners and advanced users.

Uploaded by

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

The MagPi Essentials Conquer the commandline the

Raspberry terminal guide Second Edition


Raspberry download

https://ebookgate.com/product/the-magpi-essentials-conquer-the-
commandline-the-raspberry-terminal-guide-second-edition-
raspberry/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Raspberry Pi Networking Cookbook Second Edition Golden

https://ebookgate.com/product/raspberry-pi-networking-cookbook-
second-edition-golden/

Programming the Raspberry Pi Second Edition Getting


Started with Python Simon Monk

https://ebookgate.com/product/programming-the-raspberry-pi-
second-edition-getting-started-with-python-simon-monk/

Raspberry Pi user guide Fourth Edition / Halfacree

https://ebookgate.com/product/raspberry-pi-user-guide-fourth-
edition-halfacree/

Raspberry Pi Projects for Kids Second Edition Bates

https://ebookgate.com/product/raspberry-pi-projects-for-kids-
second-edition-bates/
Raspberry Pi User Guide 2nd revised edition Edition
Upton

https://ebookgate.com/product/raspberry-pi-user-guide-2nd-
revised-edition-edition-upton/

Experiment with the Sense HAT 1st edition Edition


Raspberry Pi

https://ebookgate.com/product/experiment-with-the-sense-hat-1st-
edition-edition-raspberry-pi/

Raspberry Pi 5 for Radio Amateurs program and Build


Raspberry Pi 5 Based Ham Station Utilities with the RTL
SDR 1st Edition Dogan Ibrahim

https://ebookgate.com/product/raspberry-pi-5-for-radio-amateurs-
program-and-build-raspberry-pi-5-based-ham-station-utilities-
with-the-rtl-sdr-1st-edition-dogan-ibrahim/

Halfacre G Official Raspberry Pi Beginner s Guide 3rd


Edition Gareth Halfacree

https://ebookgate.com/product/halfacre-g-official-raspberry-pi-
beginner-s-guide-3rd-edition-gareth-halfacree/

Raspberry Pi Robotic Projects 3rd Edition Richard


Grimmett

https://ebookgate.com/product/raspberry-pi-robotic-projects-3rd-
edition-richard-grimmett/
2nd
EDITION

ESSENTIALS

CONQUER
COMMAND
TH

LINE
E

The Raspberry Pi
TERMINAL GUIDE
9!
01
Written by Richard Smedley
2 RS
R TE
FOAP
T ED CH
DA EW
P N
U +4
ESSENTIALS
LEARN | CODE | MAKE
AVAILABLE NOW:

> CONQUER THE COMMAND LINE


> EXPERIMENT WITH SENSE HAT
> MAKE GAMES WITH PYTHON
> CODE MUSIC WITH SONIC PI
> LEARN TO CODE WITH SCRATCH
> HACK & MAKE IN MINECRAFT
> ELECTRONICS WITH GPIO ZERO
> LEARN TO CODE WITH C
> THE CAMERA MODULE GUIDE
> AIY PROJECTS

From the makers of the


official Raspberry Pi magazine
ESSENTIALS
OUT NOW
IN PRINT
ONLY £3.99
store.rpipress.cc

GET THEM
DIGITALLY:
WELCOME TO
CONQUER THE
COMMAND LINE
ometimes only words will do. Graphic user
S interfaces (GUIs) were a great advance,
creating an easy route into computer use
for many non-technical users. For complex tasks,
though, the interface can become a limitation:
blocking off choices, and leaving a circuitous route
even for only moderately complicated jobs.
(Re-)Enter the command line: the blinking cursor
that many thought had faded away in the 1990s. For
getting instructions from user to computer – in a
clear, quick, and unambiguous form – the command
line is often the best way. It never disappeared on
UNIX systems, and now, thanks to Raspbian on the
Raspberry Pi, a new generation is discovering the
power of the command line to simplify complex
tasks, or instantly carry out simple ones.
If you’re not comfortable when faced with the $
prompt, then don’t panic! In this fully updated book,
we’ll quickly make you feel at home, and able to
find your way around the terminal on the Pi, or any
other GNU/Linux computer: getting things done, and
unlocking the power of the command line.

FIND US ONLINE raspberrypi.org/magpi GET IN TOUCH magpi@raspberrypi.org

PUBLISHING
Publishing Director: Russell Barnes
Director of Communications: Liz Upton
CEO: Eben Upton

EDITORIAL
DESIGN Editor: Phil King
Critical Media: criticalmedia.co.uk Writer: Richard Smedley
Head of Design: Lee Allen Contributors: Lucy Hattersley,
Designer: Mike Kay Simon Long

In print, this product is made using paper This book is published by Raspberry Pi (Trading) Ltd., Maurice Wilkes Building, St. John's Innovation Park,
sourced from sustainable forests and Cowley Road, Cambridge, CB4 0DS. The publisher, editor and contributors accept no responsibility in respect
the printer operates an environmental of any omissions or errors relating to goods, products or services referred to or advertised in this product.
4 [ management
Chapter One ] which has been
system Except where otherwise noted, content in this book is licensed under a Creative Commons Attribution-
assessed as conforming to ISO 14001. NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISBN: 978-1-912047-66-6
[ CONQUER THE COMMAND LINE ]

ESSENTIALS

CONTENTS
06 [ CHAPTER ONE ] 31 [ CHAPTER SIX ]
DON’T PANIC CONNECTING DISKS [ RICHARD
Take a look around Tackle the management SMEDLEY ]
and discover things of removable storage

11 [ CHAPTER TWO ] 36 [ CHAPTER SEVEN ]


READ/WRITE TEXT PREDICTABLE NETWORKING
Get working on files Give the Pi a permanent network
address of its own
16 [ CHAPTER THREE ]
PERMISSION TO INSTALL 41 [ CHAPTER EIGHT ]
Raspbian’s system for installing STOPPING A PROCESS Since soldering
and updating No need to turn it off and on again: together his first
just kill the process! computer – a ZX81
21 [ CHAPTER FOUR ] kit – and gaining

MANIPULATING TEXT 46 [ CHAPTER NINE ] an amateur


radio licence as
Connect together multiple REMOTE PI GW6PCB, Richard
simple commands Access the Pi with Secure Shell has fallen in
and out of love
26 [ CHAPTER FIVE ] 51 [ CHAPTER TEN ] with technology.
CUSTOMISE DOWNLOADING & INSTALLING Swapping the
THE COMMAND LINE Add software and write to SD cards ZX81 for a guitar,
and dropping ham
Make Raspbian more personal
56 [ CHAPTER ELEVEN ] radio for organic
START AND STOP AT horticulture,
he eventually
YOUR COMMAND returned to the
Manage startup and shutdown command line,
beginning with a
64 [ CHAPTER TWELVE ] computer to run
SAVE IT NOW! his own business,
Protect your data with backups and progressing
to running all the
74 [ CHAPTER THIRTEEN ] computers of
an international
EASY COMPILATION
sustainability
Build software from source code institution. Now
he writes about
82 [ CHAPTER FOURTEEN ] Free Software and
COMMANDING THE INTERNET teaches edible
Get online from the command line landscaping.

[ Don’t
[ Contents
Panic ] 5
ESSENTIALS

ESSENTIALS

ONE ]
[ CHAPTER
DON’T PANIC In the first chapter, we take a look around and discover
that things aren’t as strange as they might appear…

6 [ Chapter One ]
[ CONQUER THE COMMAND LINE ]

t’s not a throwback to the past, but a quick and powerful way
I of getting your Raspberry Pi to do what you want, without
all that RSI-inducing menu chasing and icon clicking. The
command-line interface was a great step up from manually toggling
in your instructions in octal (base-8), using switches on the front of
the machine! Graphical user interfaces (GUIs) brought friendly visual
metaphor to the computer, losing some power and expressiveness.
With the Raspberry Pi, you can get the best of both worlds by knowing
[ READ THE both: after reading through this guide, you’ll soon be as comfortable
MANUAL ] at the command prompt as you are at your desktop.
Unlike some earlier versions of Raspbian, Stretch boots you straight
Help is included,
with man(ual) to a GUI, although you can change this behaviour in the settings. The
pages, but they command-line environment is still there: hold down the ALT+CTRL
can be a little
keys and press F1 (the first function key on the keyboard), and you’ll
overwhelming.
Use them to arrive at a ‘virtual console’. Press ALT+F2 through to F6 and you’ll
check out some find five further consoles waiting for you to log in.
extra options
You can drop into these any time you like, but for now press
beyond the
switches like ALT+F7 and you’ll be back in mouse and menu land. The command
-a we use here. line is also available through a program called a terminal emulator
To read the ls
(often referred to as a term or xterm). You’ll also find people referring
man page, type
man ls. to the shell, or Bash. Don’t worry about that for now; just click on the
icon at the top of the screen that looks like a black television screen,

The command
line is only a click
away: it is called
Terminal and you
can find it under
Accessories in
the menu

Commands are
terse, but, once
learned, they’re
a quick way of
navigating and
reading your files
and folders

[ Don’t Panic ] 7
ESSENTIALS

Fig 1 Switches
modify behaviour
in commands; ls
-a shows (dot) files
in your listing that
are usually hidden
from view

or go to Accessories>Terminal in the menu: the terminal now awaits


[ PRESS your commands.
RETURN ]
To save Look around
repeating it in the If you’re used to looking at files and folders in a file manager, try
text, we’ll confirm
here that each to clear your mind of the icons and concentrate on the names. Type
time you type ls and press RETURN (see ‘Press Return’ box). On a fresh Raspbian
in a command, Stretch with Recommended Software install, you’ll just see a few
you need to hit
the RETURN or directories, including MagPi. Type ls MagPi (see ‘Lazy Completion’
ENTER key at the box) and you’ll see a listing of what’s in it.
end, to tell the Commands like ls are not cryptic (at least not intentionally) but they
Pi you’ve issued
Bash with a are terse, dating back to a time when the connection to the computer
command. was over a 110 baud serial line, from an ASR 33 teletype terminal. If
you think it’s strange to be defined by 50-year-old technology, just
remember that your QWERTY keyboard layout was reputedly designed
both to stop mechanical typewriter keys jamming, and to enable
salespeople to quickly type ‘typewriter’ using the top row!

File path
You can list files and folders anywhere in your system (or other
connected systems) by providing the path as an argument to your

8 [ Chapter One ]
[ [CONQUER
CONQUERTHE
THECOMMAND
COMMANDLINE
LINE] ]

command. The path is the folder hierarchy: on a Windows computer,


in a graphical file browser, it starts with ‘My Computer’; on your Pi it
starts at /, pronounced ‘root’ when used on its own as the root of your
file system. Try entering ls / – again we get terseness, and names
like ‘bin’, which is short for binary, and is the directory where many
programs are kept (enter ls /bin to see the details). ls /dev shows
hardware devices in the Pi. Try ls /home – see that ‘pi’? That’s you:
you are logged in as user pi. If you’ve changed your login name, or if
you have created extra users, they’ll all be listed there too: every user
gets their own home directory; yours is the /home/pi folder in which
we found ourselves in earlier. Before, with MagPi, we used the relative
path (the absolute path would be /home/pi/MagPi) because we’re
already home. If you need to check your location, type pwd (present
working directory).

Commands are not cryptic (at least


not intentionally), but they are terse
There’s no place like ~
For any logged-in user, their home directory is abbreviated as ~ (the
tilde character). Type ls ~ and you’ll see. There’s apparently not much
in your home directory yet, but Raspbian keeps a lot hidden from the
[ LAZY
COMPLETION ]
casual glance: files and folders beginning with a dot, known as ‘dot files’,
contain configuration information for your system and its programs. You don’t need
to type all of
You don’t need to see these files normally, but when you do, just ask ls ls MagPi (for
to show you all files with a command switch. You can do this with either example) – after
the full switch --all, or the abbreviation -a like so: ls -a ~. Traversing ls M, hit the TAB
key and it will
the pathways of the directory hierarchy can be easier from the command auto-complete.
line than clicking up and down a directory tree, particularly with all If you’ve more
the shortcuts given. Your ls -a showed you . and .. as the first two than one file
beginning with
directories; these shortcuts represent the current and the parent directory M, they’ll all be
respectively. Try listing the parent directory – from /home/pi, entering listed and you
ls ../../ will show you two layers up. If you want to list the hidden can type more
letters and hit
files without the . and .. appearing (after all, they’re present in every TAB again.
directory, so you don’t need to be told), then the switch to use is -A.

[ Don’t Panic ] 9
ESSENTIALS

Before we move on to other commands, let’s look briefly at chaining


switches together: ls -lh ~
-l gives you more information about the files and folders, and -h
changes the units from bytes to kB, MB, or GB as appropriate. We’ll
look at some of the extras the -l listing shows you in more detail later,
particularly in chapters two and three.

Time for change


That’s enough looking: let’s start moving. cd is short for change
directory, and moves you to anywhere you want in the file system:
try cd /var/log and have a look (ls, remember). Files here are logs,
or messages on the state of your system that are saved for analysis
later. It’s not something you’ll often need to think about: Raspbian
is a version of an operating system that also runs across data centres
and supercomputers, where problem monitoring is very important.
It is, however, useful to know, particularly if you have a problem and
someone on a forum advises you to check your logs.
cd ~ will take you where you expect it. Try it, then pwd to check.
Now try cd - (that’s a hyphen), the ‘-’ is a shortcut for ‘wherever I
was before I came here’. Now we’ve looked around, we can move on to
beginning to do things to our files.

Right Who needs


icons when you
can fit a listing
of 78 files into a
small window?
Coloured fonts
indicate file types

10 [ Chapter One ]
ESSENTIALS

TWO ]
[ CHAPTER
READ/WRITE
TEXT
In this chapter, we get working on files

[ Read/Write
[ Don’t Panic
Text ] 11
ESSENTIALS

The command line


offers tools to get
text from different
parts of a file, like
skipping to the
conclusion

Create and name


files and directories
with keystrokes,
rather than
mouse-clicks and
keystrokes

ow that we can navigate folders and list files, it’s time to learn
[ MORE
INFO ]
N how to create, view, and alter both files and folders. Once
more, it’s not that the task is difficult, rather that the forms
Many utilities of the commands (particularly when editing) are unfamiliar, coming
have info pages,
giving far more from an era before Common User Access (CUA) standards were created
information to ease switching between applications and operating systems.
than their man Stick with it: with just the first two chapters of this book under your
page. If you’re
feeling brave, try belt, you’ll be able to do plenty of work at the command line, and start
info nano for a getting comfortable there.
comprehensive
guide to nano.
Creating a directory
We’re going to dive straight into working with files and folders by
creating a new directory. Assuming you already have a terminal open
(see ‘Instant applications’ box), and you’re in your home directory
(pwd to check, cd ~ to get back there if necessary), type mkdir
tempfolder and have a look with ls.
mkdir, as you’ve probably guessed, creates a new directory or folder.
Let’s use it to experiment with altering one of the included Python
games. Don’t worry: we’re not going to be programming Python, just
making a small change by way of illustration. cd tempfolder (use
tab completion: cd t then hit the TAB key). In the following example,
we’ll be copying some files to this directory.

12 [ Chapter Two ]
[ [CONQUER
CONQUERTHE
THECOMMAND
COMMANDLINE
LINE] ]

First, make sure Python Games is installed – if not, click the


top-left Raspberry Pi icon on the desktop, select Preferences,
then Recommended Software, tick the box next to Python
Games in the list, and then click Apply to install it.
We’ll copy over the files from the python_games directory:

cp /usr/share/python_games/fourinarow.py .
cp /usr/share/python_games/4row_* .
[ INSTANT
APPLICATIONS ]
Wildcard Although you
can open
The . (dot) at the end of the commands refers to ‘just here’, which the terminal
is where we want the files copied. Also, 4row_* is read by the Pi as emulator from
the menu –
‘every file beginning 4row_’ – the * is known as a wildcard, and this Accessories >
one represents any number of characters (including none); there are Terminal – for
other wildcards, including ?, which means any single character. this, and any
other app, just
Try python fourinarow.py and you’ll see you can run the hit ALT+F2
local copy of the game. To change the game, we need an editor – and type its
sidestepping the UNIX debate about which one is best, we’ll use the command name:
lxterminal.
Pi’s built-in editor: nano. Unless you’ve previously used the Pico

We’re going to dive straight into


working with files and folders
by creating a new directory
editor, which accompanied the Pine email client on many university
terminals in the 1980s and 1990s, it will seem a little odd (Fig 1,
overleaf). That’s because its conventions predate the CTRL+C for copy
type standards found in most modern programs. Bear with us.

Editing and paging


nano fourinarow.py will open the game for editing; use the arrow
keys to go down nine lines, and along to the BOARDHEIGHT value of
6. Change it to 10 (both the BACKSPACE and DELETE keys will work
in nano). The last two lines of the screen show some shortcuts, with

[ Read/Write Text ] 13
ESSENTIALS

^ (the caret symbol) representing the CTRL key: CTRL+O, followed


[ SWITCHING by RETURN will ‘write out’ (save) the file; then use CTRL+X to exit.
HELP ] Now, python fourinarow.py will open an oversize board, giving
You don’t need
you more time to beat the computer, should you need it. However,
to wade through
the man page there’s now no room to drag the token over the top of the board:
to see what go back and change the BOARDHEIGHT value to 9, with nano.
switches are
If you want to take a look through the fourinarow.py listing
available: type
--help after without entering the strange environment of nano, you can see
the command the entire text of any file using cat: e.g., cat fourinarow.py.
to be shown
Unfortunately, a big file quickly scrolls off the screen; to look through
your options, e.g.
rm --help a page at a time, you need a ‘pager’ program. less fourinarow.py
will let you scroll up and down through the text with the PAGE UP and
PAGE DOWN keys. Other keys will do the same job, but we’ll leave
you to discover these yourself. To exit less, hit Q (this also works
from man and info pages, which use a pager to display text).

Cats, heads & tails


If editor wars are a UNIX tradition we can safely ignore, there’s
Fig 1 The default no getting away from another tradition: bad puns. less is an
editor, nano, has
improvement over more, a simple pager; the respective man pages
unusual command
shortcuts, but will show you the differences. One advantage the relatively primitive
they’re worth
learning, as you’ll
more has is that at the end of a file it exits automatically, saving you
find nano installed reaching for the Q button. Admittedly, this is not a huge advantage,
on virtually all Linux
and you can always use cat.
boxes, such as your
web host Fortunately, cat is not a feline-based pun, but simply short for
‘concatenate’: use it with more
than one file and it concatenates
them together. Used with
no argument – type cat – it
echoes back what you type
after each ENTER. Hit CTRL+C
to get out of this when you’ve
finished typing in silly words
to try it. And remember that
CTRL+C shortcut: it closes most
command-line programs, in the
same way that ALT+F4 closes
most windowed programs.

14 [ Chapter Two ]
[ CONQUER THE COMMAND LINE ]

You can peek at the first or


last few lines of a text file with
head and tail commands. head
fourinarow.py will show you
the first ten lines of the file.
head -n 5 fourinarow.py
shows just five lines, as does
tail -n 5 fourinarow.py
with the last five lines. On the Pi,
head -5 fourinarow.py will
also work.

Remove with care


nano afile.txt will create a
new file if afile.txt does not already exist: try it, and see if it works Fig 2 rm is a
powerful removal
when you exit the file before writing and saving anything. We’ve tool: use with
done a lot already (at least, nano makes it feel like a lot), but it’s great care!
never too early to learn how to clean up after ourselves. We’ll
remove the files we’ve created with rm. The remove tool should
always be used with care: it has some built-in safeguards, but even
these are easy to override (Fig 2). In particular, never let anyone
persuade you to type rm -rf / – this will delete the entire
contents of your Pi, all the programs, everything, with little to no
chance of recovery.
Have a look at what files we have: if you’re still in the
tempfolder you made, then ls will show you the Four-in-a-Row
files you copied here. Remove the program, then the .png files
with careful use of the * wildcard.

rm fourinarow.py
rm 4row_*.png

cd .. to get back to /home/pi and rm -r tempfolder


will remove the now empty folder. The -r (recursive) option
is necessary for directories, and will also remove the contents
if any remain.
In the next chapter, we’ll delve into file permissions and updating
your Pi’s software from the command line.

[ Read/Write Text ] 15
ESSENTIALS

[ CHAPTER THREE ]
PERMISSION
TO INSTALL We look at Raspbian’s efficient system for installing
and updating software, among other things

16 [ Chapter Three ]
[ CONQUER THE COMMAND LINE ]

nstalling software should be easy, but behind every piece of


I software is an evolving set of dependencies that also need
installing and updating. Keeping them separate reduces
unnecessary bloat and duplication, but adds the potential for bugs,
missing files, and even totally unresolvable clashes.
Fortunately, Debian GNU/Linux cracked the problem back in
[ SHARED the 1990s with the Debian Package Management system and the
RESPONSIBILITY ]
Advanced Package Tool (APT) – and Debian-based systems, like
If you share Ubuntu and the Pi’s Raspbian, inherit all of the benefits. Here we’ll
your Pi, read up show you the basics you need to know to install new software and
on sudo and
the visudo keep your system up to date from the command line, and then look at
command to the not entirely unrelated field of file ownership and permissions.
find how to Using the apt command to update your system’s list of installable
give limited but
useful admin software should be as simple as issuing the command like so:
privileges to the apt‑get update. Try this logged in as user pi, though, and you’ll
other users. just get error messages. The reason for this is that changing system
software on a GNU/Linux (or any type of UNIX) system is a task
restricted to those with administrative permissions: the godlike
superuser, or admin, also known as root.

Raspbian’s software
repository contains many
thousands of freely
installable apps, just a
command away from use

Every file, folder,


and even hardware
component should have
just enough permission
for you to use it – but not
be over-accessible at
the risk of security

[ Permission to Install ] 17
ESSENTIALS

Fig 1 Raspbian
updates its listing
of thousands of
available apps,
providing you give it
admin permissions

Pseudo root, su do
We’ll get onto permissions properly a bit later, but for now you’ll be
pleased to know that you can fake it, using the sudo command. sudo
potentially offers a fine-grained choice of permissions for users and
groups to access portions of the admin user’s powers. However, on
the Pi, Raspbian assumes, quite rightly, that the default user will be
someone just wanting to get on with things, and sudo in front of a
command will pretty much let you do anything. You have been warned!
The following two commands will update Raspbian’s installed
software (Fig 1):

sudo apt-get update


sudo apt-get upgrade

You can wait for one to finish, check everything is OK, then issue the
other command, or you can save waiting and enter both together with:

sudo apt-get update && sudo apt-get upgrade

The && is a Boolean (logical) AND, so if the first command doesn’t


run properly, the second one will not run at all. This is because for a
logical AND to be true, both of its conditions must be true.
It’s always worth running the update command before installing
new software, too – minor updates are made even in stable
distributions such as Raspbian, to address any issues. We’ve just

18 [ Chapter Three ]
[ CONQUER THE COMMAND LINE ]

run an update, so no need to repeat that for now. Sticking with


a command‑line theme, we’re going to install an old suite of
terminal games:

sudo apt-get install bsdgames

Searchable list
It is possible to find particular apps with apt-cache search:
apt‑cache search games. You can also examine individual
packages with apt-cache show: apt-cache show bsdgames.
APT is actually a front end to the lower-level dpkg, which you can
call to see what you have installed on the system: dpkg -l. Even
on a fresh system, that’s a large listing: we’ll show you how to get
useful information from such listings another time.
Downloaded packages hang around in /var/cache/apt and if you
find yourself short on disk space, issuing sudo apt-get clean will
clear out the archive, without affecting the installed software.
Now, remember the extra details that ls -lh showed us in
chapter 1? Try ls -lh /etc/apt.
That -rw-rw-r-- at the beginning of the listing for sources.list
comprises file attributes, telling you who may use the file. Other
entries in the listing have a d at the beginning, indicating they are
directories. You’ll also see hardware devices have a c here, for character
device – ls -l on /dev/input, for example. On Linux, everything is a
file, even your mouse! A dash (-) at the start tells us this is just a regular [ FREE TO USE ]
file; it’s the remaining nine characters that cover permissions.
Software in
Every file has an owner and a group membership. Files in your home the Raspbian
directory belong to you. If you’re logged in as user pi and ls ~ -l, you’ll repository is
see pi pi in each listing, telling you the owner and the group. Note that not just free to
use, but freely
we put the switch at the end this time: that’s a bad habit under certain modifiable and
circumstances, but we’re just showing you what’s possible. Owner and redistributable.
group aren’t always the same, as ls -l /dev will show you. Free software,
like Raspbian’s
Debian base, is
File attributes built on sharing:
The file attributes, after the file type, are three groups of three for education
and for building
characters (rwx) telling you which users may read, write or execute the community.
file or directory for, respectively, the user who owns the file, the group

[ Permission to Install ] 19
ESSENTIALS

owner, and everyone else (‘others’). Execute permissions are needed


[ PROBLEMS? ] to run a file if it’s a program – such as launcher.sh which runs the
Python games in your usr/share/python_games folder, and thus it has
Fine-grained
permissions the x – and for directories, so that you may cd into them.
make for greater cd into usr/share/python_games and then enter the command
security, but
can trip you up.
sudo chmod a-x launcher.sh – the a stands for all (user, group and
Typing sudo others), use u, g, or o to just change one. Try opening Python Games
in front of a from the main menu and it won’t work. We could restore normal
command that
running with sudo chmod a+x launcher.sh, but instead we’ll use:
doesn’t work is
both a diagnosis sudo chmod 755 launcher.sh.
and a quick
workaround of
a permissions
Octal version
problem. Those numbers are an octal representation of user, group, and
others’ permissions: in each case, read is represented by 4, write
by 2, and execute by 1, all added together. So here we have 7s for
read+write+execute for user, and 5 for read+execute for group and all
other users. ls -l and you’ll see we’re back to -rwxr-xr-x.
You can use chown to change who owns a file and chgrp to change
which group it belongs to. Make a new text file and sudo chown
root myfile.txt – now try editing it and you’ll find that while you
can read the file, you can no longer write to it. You can also make a
file that you can write to and run, but not read!
In the next chapter, we’ll be doing useful things with the output of
our commands; before moving on, though, why not try your hand at
robots from the bsdgames package we installed?

The id command
shows what
group access
you have, for
permission to
use and alter
files and devices

20 [ Chapter Three ]
ESSENTIALS

[ CHAPTER FOUR ]
MANIPULATING
TEXT
Discover pipes and learn how to connect multiple simple
commands together for more powerful text processing

[ Manipulating Text ] 21
ESSENTIALS

Building on simple
commands. The arrows
connect to streams and
files (input or output)
while pipes chain the
output of one program
to the input of another

If you know there’s more


than one item the same
and you don’t want to
see it, or need a new list
without duplicates, uniq
will get rid of the spares

he UNIX family of operating systems, which includes other


[ ABSOLUTE
PATH ]
T flavours of GNU/Linux and also Apple’s macOS, deals with
data from commands as streams of text. This means that
We’re using ~/ commands can be chained together in countless useful ways. For now,
mylisting4.txt though, we’ll focus on giving you a firm foundation to building your
with ~ short for
/home/pi. If you own custom commands.
cd to ~ then you
can simply use
the file name
Getting our feet wet
without the ~/ When a command is called at the terminal, it is given three streams,
known as standard input (stdin), standard output (stdout), and
standard error (stderr). These streams are plain text, and treated by
the Pi as special files. As we noted in chapter 3, ‘everything is a file’:
this is what gives the Pi and other UNIX family systems the ability to
put together simple commands and programs to build complex but
reliable systems.
Normally, stdin is what you enter into the terminal, while stdout
(command output) and stderr (any error messages) appear together.
The reason the last two have a separate existence is that you may want
to redirect one of them – error messages, for example – somewhere
away from the regular output your commands produce. We’ll look
at separate error messages later, but first we need to know how to
redirect and connect our output to other commands or files.
Connecting commands together are pipes, the ‘|’ symbol found
above the backslash on both GB and US keyboards (although the two

22 [ Chapter Four ]
[ [CONQUER
CONQUERTHE
THECOMMAND
COMMANDLINE
LINE] ]

keyboards for English speakers place the \ respectively to the left


of Z, and at the far right of the home row). When you type a command
such as ls -l, the output is sent by Raspbian to the stdout stream,
which by default is shown in your terminal. Adding a pipe connects that
output to the input (stdin stream) of the next command you type. So…

ls -l /usr/bin | wc -l

…will pass the long listing of the /usr/bin directory to the wordcount
(wc) program which, called with the -l (line) option, will tell you how
many lines of output ls has. In other words, it’s a way of counting how
many files and folders are in a particular directory.

Search with grep


One of the most useful commands to pass output to is grep, which
searches for words (or ‘regular expressions’, which are powerful
search patterns understood by a number of commands and
languages), like so:

grep if /usr/share/python_games/catanimation.py

This displays every line in the catanimation.py file containing the


character sequence ‘if’ (Fig 1, overleaf) – in other words not just the
word ‘if’, but words like ‘elif’ (Python’s else if), and words like ‘gift’
if they were present. You can use regular expressions to just find lines
with ‘if’, or lines beginning with ‘if’, for example.
Piping search results and listings to grep is the way we find a needle
[ REGEXP ]
in one of Pi’s haystacks. Remember dpkg from the last chapter, to see
what was installed? Try… Regular
expressions
(regexp)
dpkg -l | grep -i game are special
characters used
in text searches,
…to remind yourself which games you’ve installed (or are already such as [a-z]
installed). The -i switch makes the search case insensitive, as the to match any
program may be a ‘Game’ or ‘game’ in the description column. letter (but not
numbers), and
A simple dpkg -l | more lets you see output a page at a time. ^ to match to
sort will, as the name suggests, sort a listing into order, with various the beginning of
tweaks available such as -f to bring upper and lower case together. a line.

[ Manipulating Text ] 23
ESSENTIALS

Fig 1 No matter
how long the
[ FILING file, grep will
HOMEWORK ] dig out the
lines you need.
There are many It’s also handy
more commands for finding the
beyond grep, results you want
from a multi-
sort and
page output
uniq that can
be chained One way to collect unsorted data is to combine lists. sort will put the
together. Take
a look at cut if combined listing back in alphabetical order:
you’re feeling
adventurous. ls ~ /usr/share/python_games | sort -f

Suppose you copied one of the games to your home directory to


modify: you know it’s there, but you don’t want to see the same name
twice in the listings. uniq will omit the duplicated lines or, with the -d
switch, show only those duplicates.

ls ~ /usr/share/python_games | sort -f | uniq

File it away
Pipes are not the only form of redirection. > (the ‘greater than’ symbol)
sends the output of a program into a text file, either creating that text
file in the process, or writing over the contents of an existing one.

ls /usr/bin > ~/mylisting4.txt

Now look in mylisting4.txt and you’ll see the output of ls


/usr/bin. Note that each item is on a separate line (Fig 2). Your
terminal displays multiple listings per line for space efficiency;
however, for easy compatibility between commands, one listing
per line is used. Most commands operate on lines of text; e.g., grep
showed you in which lines it found ‘if’. Note that some commands
need a dash as a placeholder for the stdin stream being piped to them:

echo "zzzz is not a real program here" | cat mylisting4.txt -




24 [ Chapter Four ]
[ CONQUER THE COMMAND LINE ]

Appending
If you want to add something to the end of a file without overwriting
the contents, you need >>.

echo "& one more for luck!" >> ~/mylisting4.txt

echo simply displays whatever is in the quote marks to stdout; the -e


switch lets you add in special characters, like \n for newline (see below).
You can look at the last few lines of a file with tail ~/mylisting4.txt.
< will link a program’s input stream to the contents of a file or stream.
Make an unsorted list to work on, and sort it:

echo -e "aardvark\nplatypus\njellyfish\naardvark" >


list1
sort < list1

You can also combine < and >:

head -n 2 < list1 > list2

…will read from list1, passing it to head to take the first two lines,
then putting these in a file called list2. Add in a pipe:

sort < list1 | uniq > list3

Lastly, let’s separate that stderr stream: it has file descriptor 2 (don’t
worry too much about this), and 2> sends the error messages to any file
you choose:

cat list1 list2 list3


list42 2>errors.txt

The screen will display the ‘list’


files you do have, and the ‘No such
file or directory’ message(s) will end
up in errors.txt – 2>> will append
Fig 2 With redirection, you can get all of the output from
the messages to the file without
a command saved straight into a text file. Save your error
overwriting previous contents. messages to ask about them on the forums!

[ Manipulating text ] 25
ESSENTIALS

[ CHAPTER FIVE ]
CUSTOMISE THE
COMMAND LINE We make Raspbian a little more personal as we get it
to behave and look just the way we want it to

26 [ Chapter Five
One ]
[ CONQUER THE COMMAND LINE ]

Share your Pi:


make new user
accounts and
others can log
in or switch
users from a
command-line
session

The command- ake a look at that blinking cursor on your terminal, and at
line environment
is personal to
each user. You
T what’s behind it: pi@raspberrypi ~ $
The $ is known as the ‘dollar prompt’, awaiting your
can change your
identity with or command; before it you see the ~ (tilde), shorthand for ‘home’ – which
without a change is /home/pi in this case. Before that is [user name]@[computer name],
of environment,
depending upon in the form pi@raspberrypi. Not only is this informative (at least if
what you need to you’ve forgotten who and where you are), but it’s also something you
do in another role
can change and personalise.

New user
Let’s start with that user name: pi. If more than one person in your
family uses the Pi, you may want to keep the pi user for shared
projects, but set up individual login accounts for family members,
including yourself. Creating a new user in Raspbian is easy: sudo
adduser jo will create a new user account named jo. You will be
prompted for a password (pick a good one) and lots of irrelevant info
(dating back to shared university computers of the 1970s) that you can
safely ignore by just pressing ENTER at each prompt. Now we have
a user account for jo, have a look at /home/jo. Does it look empty?
Use ls -A. Jo has never logged into the computer, so you will see the
absence of most of the contents of /home/pi for now, but there is a
.bashrc and a couple of other config files.

[ Customise the Command Line ] 27


ESSENTIALS

Not every user has a home


directory and logs in: enter
cat /etc/passwd and you’ll see
a lot of users listed that aren’t
people. This is because files and
programs running on a UNIX-
Above Bash stores type system have to belong to a user (and a group – take a look at
information, from
/etc/group), as we saw back in chapter 1 when we did ls -l. The
your previous
‘present working user passwords are fortunately not listed in the /etc/passwd file in
directory’ to
plain text, so if you want to change a password you’ll need to use the
who you are, in
environment passwd command: sudo passwd jo will change the password for
variables like
user jo. If you’re logged in as user pi, then simply calling passwd will
OLDPWD and USER.
See individual prompt you to change pi’s password.
variables with e.g.
Transformations in the virtual world are always easier than those
echo $USER,
or view them all in nature, and this is the case with switching from being ‘pi’ to ‘jo’: we
with env
use the change (or substitute) user command, su, like so: su jo. After
typing this, you should see the prompt change to jo@raspberry; you
can also confirm who you are logged in as with whoami.

[ HOME RUN ] Changing identity


If you’re logged su - jo (note the dash) is usually preferred, as you’ll gain all of jo’s
in as user pi, then specific environment settings, including placing you in /home/jo.
~ is a shortcut to
/home/pi Note that on many other Linux systems, su on its own will enable you
– but ls ~jo to become the root or superuser, with absolute powers (permissions
can be used as to run, edit, or delete anything). Raspbian (and some other popular
a shortcut to
list /home/jo, GNU/Linux systems like Ubuntu) prefer sudo to run individual
substituting any programs with root permissions. Root’s godlike powers may be
other user name temporarily attained with sudo -s – try it (as user pi) and note how
as desired, with
tab completion the prompt changes (enter exit to exit) – but it’s generally a bad
working after ~j idea to run with more permissions than you need! For any user, you
is typed. can customise elements of their command-line use most simply by

28 [ Chapter Five ]
[ CONQUER THE COMMAND LINE ]

editing ~/.bashrc. Take a look through that configuration file now


(as user jo): more ~/.bashrc. Note a number of variables in all capital
letters, such as HISTSIZE and PS1. The last of these controls the
prompt you see, currently jo@raspberry ~ $. To change it (for
the duration of your current terminal session), try something like:
export PS1="tutorial@magpi > ".
This is a temporary change: type exit and you’ve left the su value
of jo, so you’ll see pi@raspberry ~ $ once more. If you su back to jo,
the magpi prompt will still be gone. To make your change permanent,
you need to put the PS1 value you want into ~/.bashrc. A search around
the web will bring up many fancy options for better customising the
Bash prompt.
The ~/.bashrc file is read upon each login to a Bash session, or in
other words, every time you log into a console or open a terminal.
That’s unless you change Raspbian’s default shell away from Bash,

Transformations in the
virtual world are always
easier than those in nature
something you may have reason to do in the future – there are
interesting alternatives available for extra features or for smaller
memory footprint – but let’s not worry about that for now. You can [ BASIC
put all sorts of commands in there to personalise your environment: ACCOUNT ]
command aliases are great for regularly used combinations. adduser creates
a new user, then
Alias takes care of
all of the extra
As user pi, see what’s there with: grep alias ~/.bashrc. There are details like
a few aliases already in there, particularly for the ls command. One making a home
directory. If all
entry is: # alias ll='ls -l'. This sounds quite useful, although the
you want is a
# indicates that it is ‘commented out’, which means that it will not be user created
read by Bash. Open .bashrc in your text editor (double-click the file in with no extra
frills, then the
File Manager after pressing CTRL+H to show hidden files) – the simple
command you
Text Editor will do for now as although we’ve touched on using nano want is useradd.
for editing text from the command line, we aren’t going to go into this

[ Customise the Command Line ] 29


ESSENTIALS

in detail until the next chapter. Removing the # will mean that now
[ WHO AM I? ] when you type ll, you’ll get the action of running ls -l. Handy,
but we could make it better. Change it to: alias ll='ls -lAhF' and
From a virtual
console (CTRL+
you’ll get an output in kB or MB, rather than bytes, along with trailing
ALT+F1 to F6), su slashes on directory names and the omission of the ever present .
and that’s who and .. (current and parent) directories. Changes take effect after you
you’re logged
in as. From
next start a Bash session, but then you can just run that alias as a
an xterm, you command (Fig 1). To disable an alias for a session, use: unalias ll.
can change to
someone else,
but start another
Key point
app from the We’ll end with the very first thing many users need to change:
menu and you’ll the keyboard map. The system-wide setting is found in
be back to your
original login.
/etc/default/keyboard, but often you need to change it just for
individual users. If £ signs and letters without accents are not
sufficient for them, log in as the user who wants a different
keyboard, or add sudo and the correct path to the commands below.
For example, for a Greek keyboard:

touch ~/.xsessionrc
echo "setxkbmap el" > ~/.xsessionrc

Replace el with pt, us, or whatever language you desire. Note that
the config file we created – .xsessionrc – holds settings that are read
when we log in to the GUI, so the keyboard setting will cover not just
the terminal, but every app used in the session.

Fig 1 Those
terse, two- or
three-letter
commands are
not set in stone:
make your own
shortcuts to
keep, or just
for use over a
specific session

30 [ Chapter Five ]
ESSENTIALS

[ CHAPTER SIX ]
CONNECTING
DISKS
For chapter six, we’re tackling the
management of removable storage

[ Connecting
[ Don’t Panic
Disks ] 31
ESSENTIALS

Raspbian, while
presenting a simple
surface, also lets
you dig deep for
information when you
need to change default
behaviour. That’s real
user-friendliness!

Even simple
lthough Raspbian will, when booted as far as the GUI,
A
utilities have
multiple uses: df, automatically mount any disk-type device (USB flash key,
by showing space
available, reminds camera, etc.) plugged into the USB port and offer to open it
the user which disks for you (Fig 1, overleaf), you may wish to get more direct control of the
are mounted and
can be accessed process. Or, as is more often the case, you may want to mount a disk
by the Pi when the Raspberry Pi is running a project that doesn’t involve booting
as far as the GUI, as it’s not necessary for most sensor projects.

Connected or mounted?
Plugging a drive or flash memory device into your Pi (connecting it to
[ IN DEPTH ] your computer) is not the same as making it available for the Pi to
If you want to interact with (mounting it) so that Raspbian knows what’s on it and
delve deeper into can read, write, and alter files there. It’s an odd concept to accept: the
what goes on
inside Raspbian
computer knows there’s a disk plugged in, but its contents remain
and other GNU/ invisible until the Pi is told to mount it. It’s a bit like seeing a book on
Linux systems, your shelf, but not being allowed to open or read it.
try Brian Ward’s
excellent
Disks and disk-like devices are mounted by Raspbian on a virtual file
book, How system, and you’ll rarely need to worry about what goes on beneath
LinuxWorks that layer of abstraction, but to see some of it, type mount. The
(magpi.cc/
ZEhaBF).
information displayed is of the form device on mount point, file-system
type, options. You’ll see lots of device ‘none’ for parts of the virtual

32 [ Chapter Six ]
[ CONQUER THE COMMAND LINE ]

system that you don’t need to worry about; the devices that concern us
[ DISK &
start with /dev/ and have names like /dev/mmcblk0p1 for partitions DISK SPACE ]
of the Pi’s SD card, and /dev/sda1 for plugged-in USB drives.
Plug in a USB drive (a flash drive should work fine, but some hard The df
command shows
drives may require a separate power supply). Like most computer you space on
desktops, Raspbian automatically mounts the disks, so (unless mounted drives:
you boot to a virtual console) you’ll need to unmount it. mount will just type df and
you’ll also get a
show an entry beginning something like /dev/sda1 on /media/pi/ list of connected
UNTITLED… and you can unmount with sudo umount /dev/sda1 drives. It’s more
(yes, that is umount without an ‘n’). An error will result if the device readable than
mount -l, though
is in use, so change directory and/or close apps using files from the lacking file type
device. Now we can mount it just the way we want. info. It’s also
quicker to type!

Finding the disk


The /dev/sda1 refers to the first, or only, partition (a section of the hard
drive that is separated from other segments) on /dev/sda. The next
device plugged in will be /dev/sdb1. You can see what’s being assigned
by running tail -f /var/log/messages, then plugging in the USB
device. On other Linux systems, if /var/log/messages draws a blank,

An error will result if the device is in use,


so change directory and/or close apps
try /var/log/syslog. Stop the tail with CTRL+C. Another way of seeing
connected devices that aren’t necessarily mounted is fdisk, a low-level
tool used to divide disks up into partitions, before creating file systems
on those disks (see the ‘Format’ box on page 35). Called with the list
option, sudo fdisk -l, it performs no partitioning, but simply lists
partitions on those disks connected to your Pi. It also gives file-system
information, which you need in order to mount the disk. Lastly, you
need a mount point (somewhere to place the device on the file-system
hierarchy) with appropriate permissions. Create one with:

sudo mkdir /media/usb


sudo chmod 775 /media/usb

[ Connecting Disks ] 33
ESSENTIALS

Fig 1 Raspbian
wants to mount
plugged-in disks,
and take care of
the details for
you – note that
the GUI tells you
it’s ‘Windows
software’ – while
the command
line beneath has
information for
you to take control
when you need
the job done in
a particular way,
telling you it’s an
NTFS file system

Mount the disk with sudo mount -t vfat /dev/sda1 /media/usb,


where vfat (or NTFS or ext2) is the file-system type.

File-system table
Raspbian knows which disks to mount at boot time by reading the
file-system table (/etc/fstab), and we could put our /dev/sda1 in
there, but if we start up with two drives plugged in, the wrong one
may be selected. Fortunately, disks (or rather, disk partitions) have
unique labels known as UUIDs randomly allocated when the partition
is created. Find them with sudo blkid, which also helpfully tells you
the label, if any, that often contains the make and model of external
drives, or look in /dev/disk/by-uuid.
For an NTFS-formatted drive, we called sudo nano /etc/fstab and
added the following line to the end of the file:

/dev/disk/by-uuid/E4EE32B4EE327EBC /media/usb
ntfs defaults 0 0

This gives the device name (yours will be different, of course),


mount point, file-system type, options, and two numeric fields: the
first of these should be zero (it relates to the unused dump backup
program), while the second is the order of check and repair at boot:
1 for the root file system, 2 for other permanently mounted disks for
data, and 0 (no check) for all others. man mount will tell you about
possible options.

34 [ Chapter Six ]
[ CONQUER THE COMMAND LINE ]

Editing with nano


We touched briefly on nano in
chapter 2. Looking in a little more
depth, the first thing to be aware
of is the dozen shortcuts listed
across the bottom two lines of the
terminal: each is the CTRL key
(represented by the caret ^) held
at the same time as a single letter
key. For example, ^R for ReadFile
(i.e. open), ^O for WriteOut (in
other words, save), and ^X for
Exit. Remember those last two for
now, and you’ll be able to manage nano. However, if you learn more of Fig 2 Once we’ve
put our removable
them, you will really race through your editing tasks. disk in the file-
While nano lacks the power features of Emacs and Vim, its two system table
(/etc/fstab),
main command-line code editor rivals, it has useful features such mount -a will read
as a powerful Justify (^J), which will reassemble a paragraph of line- the config from
there to mount
break strewn text into an unbroken paragraph, or apply line breaks at your disks, saving
a fixed character length. This is a legacy of its development for email you from having
to remember
composition. ^K cuts the line of text the cursor is on, but it isn’t just the details
a delete function: each cut is added to a clipboard. ^U will paste the
entire clipboard at the cursor position: it’s great for gathering together
useful snippets from a longer text.
Hit ^O to save fstab, and the shortcut listing changes, with many
[ FORMAT ]
now beginning M instead of ^ – this is short for Meta, which means
the ALT key on your keyboard (once upon a time, some computers had Copying a disk
image negates
several modifier keys, such as Super and Hyper). One ‘hidden’ shortcut the need to
after ^O is that at this point, ^T now opens a file manager to search for format the disk.
the file/directory where you want to save. Should you
need to format
After saving, exit nano; now sudo mount -a will mount the external a new partition,
drive at the desired mount point (Fig 2), regardless of what else is or convert a disk
plugged in. If you have other new entries in /etc/fstab, then sudo to ext4 format,
read the manual:
mount /media/usb1t (or whatever entry you put in fstab) will mount man mkfs and
just that chosen device if you don’t want to mount any of the others. for individual
Having got inside connected disks, the next chapter will see us file-system types
such as man
accessing all of the Pi, but remotely, from anywhere on the planet with mkfs.ext4
an internet connection.

[ Connecting Disks ] 35
ESSENTIALS

ESSENTIALS

[ CHAPTER SEVEN ]
PREDICTABLE
NETWORKING
In this chapter, we give the Raspberry Pi a permanent
network address of its own

36 [ Chapter Seven
One ] ]
[ CONQUER THE COMMAND LINE ]

aspbian takes care of automatically connecting in most


R situations, but sometimes you need to override automatic
configurations to ensure a consistent network setting for your
Raspberry Pi project: Raspbian has the tools, and we’ll show you the
essentials you need to stay connected.
Plug an Ethernet cable from your ADSL router / modem to your
Raspberry Pi (or connect via wireless LAN) and, automatically,
Raspbian knows where it is on the network, and can talk to the
outside world.
All of this is thanks to DHCP – Dynamic Host Configuration Protocol
– which provides network configuration for every device connected
into a network. Typically, this comes in the form of an IPv4 (Internet
Protocol version 4) address, a pair of four numbers separated by a
period. For example: 192.168.0.37
The first two sets of numbers, 192.168, mark the start of a private
range. These are the numbers for all devices in your house, ranging
from 192.168.0.0 to 192.168.255.255.
Check your Raspberry Pi’s current connection with the ifconfig
command. This should show, amongst others, a line like inet
192.168.0.37 (with your own numbers). This will be below the eth0

The IP address is likely


to be a private address
in the range beginning
192.168.0.0. Here we
can see it beneath eth0
(because our Raspberry
Pi is connected via an
Ethernet cable). Our
address is 192.168.0.37

The ifconfig
command tells
you information
about your
Raspberry Pi’s
network address

[ Predictable Networking ] 37
ESSENTIALS

section if you are connected via Ethernet, or under the wlan0 section if
you’re connected wire wireless LAN.
A faster way to get your IP address is to enter hostname -I on the
command line.

How to set up up your Raspberry Pi to have a static


IP address
Usually when you connect a Raspberry Pi to a local area network (LAN),
it is automatically assigned an IP address. Typically, this address will
change each time you connect.

You might want your Pi to boot up


with the same IP address each time
Sometimes, however, you might want your Pi to boot up with the
same IP address each time. This can be useful if you are making a small
self-contained network, or building a standalone project such as a robot.
Here’s how to do it.
Edit the file /etc/dhcpcd.conf as follows (Fig 1):
Type sudo nano /etc/dhcpcd.conf at the command prompt. Scroll
to the bottom of the script, and add the following lines:

Fig 1 Edit the


/etc/dhcpcd.conf
file to determine
which static IP
address to
use with a
Raspberry Pi

38 [ Chapter Seven ]
[ [CONQUER
CONQUERTHE
THECOMMAND
COMMANDLINE
LINE] ]

Fig 2 Use ping


interface eth0 from another
static ip_address=192.168.0.2/24 computer to detect
if your Raspberry
static routers=192.168.0.1 Pi is responding to
static domain_name_servers=192.168.0.1 8.8.8.8 network requests

interface wlan0
static ip_address=192.168.0.2/24
static routers=192.168.0.1
static domain_name_servers=192.168.0.1 8.8.8.8

Save the file with CTRL+O and then exit nano with CTRL+X.

Your Raspberry Pi will now boot up with the IP address 192.168.0.2


every time; we didn’t use 192.168.0.1 as this is reserved for the router.
You can of course use any address you like, but in the configuration
above, the range must be between 192.168.0.2 and 192.168.0.255.
Reboot with sudo shutdown -r now. Log in and type hostname
-I. You should then see the IP address you set in the eth0 or wlan0
entry (192.168.0.2).

[ Predictable Networking ] 39
ESSENTIALS

Normally you don’t want your computer set to use a static IP address.
You can change the network configuration back by editing dhcpcd.conf
again using sudo nano /etc/dhcpcd.conf. Remove all the lines you
added in the previous step, then save the file again.

Ping!
Ping is the most basic tool in the network testing armoury, but one
which is often called upon. It sends an ICMP (Internet Control Message
[ DOMAIN NAME
SERVERS ] Protocol) ECHO_REQUEST to a device on the network. ICMP is built into
every connected device and used for diagnostics and error messages:
We added a ping will produce a reply from the pinged machine, which tells you
192.168.0.1
8.8.8.8 to
it is on, and connected, and that the network is working between you
our domain_ and it. Information about packets lost, and time taken, also helps with
name_servers fault diagnosis.
line in /etc/
dhcpcd.conf.
A successful ping localhost from the Raspberry Pi tells you not just
This is for the that the local loopback interface is working, but that localhost resolves
Google public to 127.0.0.1, the local loopback address. Name resolution is the cause of
domain name
server (DNS). The
many computing problems – see ‘Domain Name Servers’ box. Now ping
DNS maps public the Pi from another machine on your local network: ping 192.168.0.2
IP addresses like (Fig 2) – you’ll need to use the static IPv4 address you set, rather than ours,
raspberrypi.org
to IP addresses
of course. If you’re doing this from a Windows machine, ping defaults to
(in this case five attempts; from another UNIX machine (another Pi, a Mac, or Ubuntu
93.93.128.230). or other GNU/Linux), it will carry on until you stop it with CTRL+C, unless
You’ll need
to add a DNS
you set a number of ECHO_REQUEST sends with -c like so:
reference to
access websites ping -c 5 raspberrypi.org
in a browser.

IPv6
The four-digit IP address style we use (such as 192.168.0.2) is IPv4.
A newer standard, IPv6, is becoming more common. These are
longer 128-bit addresses represented in hexadecimal (for example,
fd51:42f8:caae:d92e::1). Look at the example code in dhcpcd.conf for
setting up a static address with IPv6.

Free / public DNS


As well as dynamic DNS providers, some of those listed at FreeDNS.com
offer public DNS servers. For a wider listing of alternatives to Google’s DNS
servers, have a search on Google itself.

40 [ Chapter Seven ]
ESSENTIALS

[ CHAPTER EIGHT ]
STOPPING A
PROCESS
As close to perfect as Raspbian is, things can go wrong . In this chapter,
we learn that there’s no need to turn the Raspberry Pi off and on again:
just kill the process!

[ Stopping
[ Don’t Panic ]
A Process 41
ESSENTIALS

Programs running in
the terminal can be put
to sleep by sending to
the background – from
where they can easily be
brought back with fg
Keep an eye on your
processes, and you’ll also
be able to see what’s
hogging the Pi’s CPU and
memory resources

ver lost the ‘off switch’ for a program? Sometimes a piece of


E software you’re running seems to have no inclination to stop:
either you cannot find how to quit, or the app has a problem,
and won’t respond to your Q, CTRL+C, or whatever command should
close it down.
There’s no need to panic, and certainly no need to reboot: just
identify the process and quietly kill it. We’ll show you how, and look at
what else can be done with knowledge of processes.

Processes
Find the many processes running on your Pi with the ps command. As
a minimum, on Raspbian, it’s usually called with the a and x switches –
which together give all processes, rather than just those belonging to a
user, and attached to a tty – and with u to see processes by user; w adds
wider output, and ww will wrap over the line end to display information
without truncating.
Type ps auxww to see, then try with just a or other combinations.
You will notice that these options work without the leading dash
seen for other commands. Both the lack of dashes, and the particular
letters, a and x, date back to the original UNIX ps of the early 1970s,
maintained through various revisions by one of UNIX’s two family

42 [ Chapter Eight ]
[ CONQUER THE COMMAND LINE ]

branches, BSD, and baked into the first GNU/Linux ps. UNIX’s other
branch, System V, had extended and changed ps with new options and [ KEEP ON TOP ]
new abbreviations for command switches, so for ps ax you may see When using a
elsewhere ps -e (or -ef or -ely to show in long format). virtual console,
The ps aux listing has various headers, including the USER which it can be worth
keeping htop
owns the process, and the PID, or Process IDentification number. This running so that
starts with 1 for init, the parent process of everything that happens in if there are any
userspace after the Linux kernel starts up when you switch the Pi on. problems, you
can CTRL+ALT-
Knowing the PID makes it easy to kill a process, should that be FN there for a
the easiest way of shutting it down. For example, to kill a program quick look for any
with a PID of 3012, simply enter kill 3012, and to quickly find the problems – even
if the GUI freezes.
process in the first place, use grep on the ps list. For example, locating
vi processes:

ps aux | grep -i vi

The -i (ignore case) isn’t usually necessary, but occasionally a


program may break convention and contain upper-case letters in
its file name. You can also use killall to kill by program name:
killall firefox

Piping commands
Naturally, you can pipe ps’s output to select the PID and feed directly
to the kill command:

kill $(ps aux | grep '[f]irefox' | awk '{print $2}')

We don’t have space for an in-depth look at awk (we’re using it here
to print the second field of grep’s output: the PID), but the [f] trick
at the beginning of Firefox (or whatever named process you want to
kill) prevents the grep process itself being listed in the results; in the
vi example above, grep found the grep process itself as well as vi (and
anything with the letter sequence vi in its name).
The output of ps also shows you useful information like percentage
of memory and CPU time used, but it’s more useful to see these
changing in real time. For this, use top, which also shows total CPU
and memory use in the header lines, the latter in the format that you
can also find by issuing the command free. For an improved top:

[ Stopping A Process ] 43
ESSENTIALS

[ QUICKER BOOT ]
sudo apt-get install htop
The start up
process of
htop is scrollable, both horizontally and vertically, and allows you
Raspbian
Wheezy is to issue commands (such as k for kill) to highlighted processes. When
controlled by the you’ve finished, both top and htop are exited with Q, although in htop
traditional SysV
you may care to practise by highlighting the htop process and killing it
init. Raspbian
Jessie, like other from there (see Fig 1). htop also shows load over the separate cores of
GNU/Linux the processor if you have a Pi 2 or 3.
distributions,
has moved to
the faster (but Background job
monolithic) Placing an ampersand (&) after a command in the shell, places the
SystemD – we
program in the background – try with: man top & and you’ll get an
touch on some of
the differences in output like: [1] 12768.
chapter 11. The first number is a job number, assigned by the shell, and the
second the PID we’ve been working with above. man top is now running
in the background, and you can use the job control number to work with
the process in the shell. Start some other processes in the background
if you wish (by appending &), then bring the first – man top – to the
foreground with fg 1. Now you should see man running again.
Fig 1 htop tells you
You can place a running shell program in the background by
what’s running, ‘suspending’ it with CTRL+Z. fg will always bring back the most
what resources
recently suspended or backgrounded job, unless a job number is
it’s using, and lets
you interact with specified. Note that these job numbers apply only within the shell
the process, even
where the process started. Type jobs to see background processes;
killing htop from
within htop jobs -l adds in process IDs (PID) to the listing.

Signals
When we send a kill signal from
htop, we are given a choice
of signal to send. The most
important are SIGTERM, SIGINT,
and SIGKILL.
The first is also the signal kill
will send from the command line
if not called with a modifier: it
tells a process to stop, and most
programs will respond by catching

44 [ Chapter Eight ]
[ CONQUER THE COMMAND LINE ]

the signal, and first saving any data


they need to save and releasing system
resources before quitting.
kill -2 sends SIGINT, which is
equivalent to stopping a program from
the terminal with CTRL+C: you could
lose data. Most drastic is kill -9 to
send SIGKILL, telling the kernel to let
the process go with no warning. Save
this one for when nothing else works.
Mildest of all is the Hang Up (HUP)
signal, called with kill -1, which many daemons are programmed to Fig 2 Everything
running has a
treat as a call to simply re-read their configuration files and carry on process ID (PID)
running. It’s certainly the safest signal to send on a critical machine. that can be used
to control that
program; find them
Staying on all with ps aux
nohup will run a program which will continue after the terminal
from which it is started has closed, ignoring the consequent SIGHUP
[ KEEP ON
(hangup) signal. As the process is detached from the terminal, error RUNNING ]
messages and output are sent to the file nohup.out in whichever
directory you were in when you started the process. You can redirect nohup is useful
for a program
it – as we did in chapter 4 – with 1> for stdout and 2> for stderr; &> is a that will be
special case for redirecting both stdout and stderr: running for
some time in the
background –
nohup myprog &>backgroundoutput.txt & perhaps a sensor
project you are
One use of nohup is to be able to set something in motion from a working on – until
you feel happy
SSH session, which will continue after an interruption. For example, enough to add
restarting the network connection to which you are connected: it to Raspbian’s
startup
processes.
sudo nohup sh -c "ifconfig wlan0 down && ifconfig
wlan0 up"

Note that the nohup.out log file created here will need sudo
privileges to read – or reassign with:

sudo chown pi:pi nohup.out

[ Stopping A Process ] 45
Other documents randomly have
different content
CHAPTER IV.
THE CABINET OF CLOUDLAND.

“A magnificent array of clouds;


And as the breeze plays on them, they assume
The forms of mountains, castled cliffs, and hills,
And shadowy glens, and groves, and beetling rocks;
And some, that seem far off, are voyaging
Their sunbright path in folds of silver.”
“Right,” said I to myself, as I lay down the volume of Hyperion, in
which I had been glancing for repose. “I, too, have a friend, not yet
a sexagenary bachelor, but a bachelor notwithstanding. He has one
of those well oiled dispositions which turn upon the hinges of the
world without creaking, except during east winds, and when there is
no butter in the house. The hey-day of life is over with him; but his
old age (begging his pardon) is sunny and chirping, and a merry
heart still nestles in his tottering frame, like a swallow that builds in
a tumble-down chimney. He is a professed Squire of Dames. The
rustle of a silk gown is music to his ears, and his imagination is
continually lantern-led by some will-with-the-wisp in the shape of a
lady’s stomacher. In his devotion to the fair sex—the muslin, as he
calls it—he is the gentle flower of chivalry. It is amusing to see how
quickly he strikes into the scent of a lady’s handkerchief. When once
fairly in pursuit, there is no such thing as throwing him out. His heart
looks out at his eye; and his inward delight tingles down to the tail
of his coat. He loves to bask in the sunshine of a smile; when he can
breathe the sweet atmosphere of kid gloves and cambric
handkerchiefs, his soul is in its element; and his supreme delight is
to pass the morning, to use his own quaint language, ‘in making
dodging calls, and wriggling round among the ladies.’” Yet there are
a few little points in the picture which want retouching, and beyond
all, one great omission to be remedied. It is the pipe. What would the
worthy Abbot be without his pipe? Just as uncomfortable as we
should presume a dog to be without his tail. As incomplete as a
sketch of Napoleon without his boots and cocked-hat. See him in a
cloud, and he seems the very Premier of Cloudland. It was said of
Staines, Lord Mayor of London, that he could not forego his pipe
long enough to be sworn into office, without a whiff; and a print was
published representing his lordship smoking in his state carriage; the
sword bearer smoking—the mace bearer smoking—the coachmen
smoking—the footmen smoking—the postilions smoking—and, to
crown the whole—all the six horses smoking also. The ninth of
November on which this event occurred, must needs have been a
cloudy day.
Another cloudy day arose upon London when the great plague
broke out, and on this occasion, the smoke of tobacco mingled with
the gloom. In Reliquiæ Hearnianæ, it is stated that “none who kept
tobacconist’s shops had the plague. It is certain that smoking was
looked upon as a most excellent preservative, insomuch, that even
children were obliged to smoke. And I remember”, continues the
writer, “that I heard formerly Tom Rogers, who was yeoman beadle,
say, that when he was that year when the plague raged, a schoolboy
at Eton, all the boys of that school were obliged to smoke in the
school every morning, and that he was never whipped so much in
his life as he was one morning for not smoking.” We may imagine
the experiences of some of these urchins at their first or second
attempt, and in remembrance, it may be, of some similar experience
of our own, see no cause for wonder at Tom Rogers not liking to
elevate his yard of clay, and view the curls of smoke arise from the
ashes of the smouldering weed. Another amateur who flourished
after the great fire had burnt out all traces of the great plague, has
left us the record of his “day of smoke,” and the cudgelling he
received for doing that which Tom Rogers was whipped for not doing

“I shall never forget the day when I first smoked. It was a day of
exultation and humiliation. It was a Sunday. My uncle was a great
smoker. He dined with us that day; and after the meal, he pulled out
his cigar case, took a cheroot, and smoked it. I always liked the
fumes of tobacco, so I went near him and observed how he put the
cheroot into his mouth, the way he inhaled the smoke, how he
puffed it out again, and the other coquetries of a regular smoker. I
envied my uncle, and was determined that I would smoke myself.
Uncle fell asleep. Now, thought I, here’s an opportunity not to be
lost. I quietly abstracted three cigars from the case which was lying
on the table, and sneaked off. Being a lad of a generous disposition,
I wished that my brothers and cousins should also partake of the
benefits of a smoke, so I imparted the secret to them, at which they
were highly pleased. When and where to smoke was the next
consideration. It was arranged that when the old people had gone to
church in the evening, we should smoke in the coach-house. We
were six in number. I divided the three cigars into halves, and gave
each a piece. Oh, how our hearts did palpitate with joy! Fire was
stealthily brought from the cook-house, and we commenced to light
our cigars. Such puffing I never did see. After each puff we would
open our mouths quite wide, to let the smoke out. At the
performance of the first puff we laughed heartily—the smoke coming
out of our mouths was so funny. At the second puff we didn’t laugh
so much, but began to spit; we thought the cigars were very bitter.
After the third puff we looked steadfastly at each other—each
thought the other looked pale. I could not give the word of
command for another pull. I felt choked, and my teeth began to
chatter. There was a dead silence for a second. We were ashamed,
or could not divulge the state of our feelings. Charlie was the first
who gave symptoms of rebellion in his stomach. Then there was a
general revolt. What occurred afterwards I did not know, till I got up
from my bed next morning, to experience the delights of a sound
flagellation. After that I abhorred the smell of tobacco—would never
look at a cigar or think of it.” All this happened, as the narrator
informed us, at the age of seven—an early age, some may imagine,
who do not know that in Vizagapatam and other places on the same
coasts, where the women smoke a great deal, it is a common thing
for the mothers to appease their squalling brats by transferring the
cigar from their own mouths to that of their infants. These
youngsters being accustomed to the art of pulling, suck away
gloriously for a second, and then fall asleep.
Howard Malcom states, “that in Burmah the consumption of
tobacco for smoking is very great, not in pipes, but in cigars or
cheroots, with wrappers made of the leaves of the Then-net tree. In
making them, a little of the dried root, chopped fine, is added, and
sometimes a small portion of sugar. These are sold at a rupee per
thousand. Smoking is more prevalent than ‘chewing coon’ among
both sexes, and is commenced by children almost as soon as they
are weaned. I have seen,” he continues, “little creatures of two or
three years, stark naked, tottering about with a lighted cigar in their
mouth. It is not uncommon for them to become smokers even
before they are weaned—the mother often taking the cheroot from
her mouth and putting it into that of the infant.”
In China, the practice is so universal, that every female, from the
age of eight or nine years, as an appendage to her dress, wears a
small silken pocket to hold tobacco and a pipe.
The use of tobacco has become universal through the Chinese
empire; men, women, children, everybody smokes almost without
ceasing. They go about their daily business, cultivate the fields, ride
on horseback, and write constantly with the pipe in their mouths.
During their meals, if they stop for a moment, it is to smoke a pipe;
and if they wake in the night, they are sure to amuse themselves in
the same way. It may easily be supposed, therefore, that in a
country containing, according to M. Huc, 300,000,000 of smokers,
without counting the tribes of Tartary and Thibet, who lay in their
stocks in the Chinese markets, the culture of tobacco has become
very important. The cultivation is entirely free, every one being at
liberty to plant it in his garden, or in the open fields, in whatever
quantity he chooses, and afterwards to sell it, wholesale or retail,
just as he likes, without the Government interfering with him in the
slightest degree. The most celebrated tobacco is that obtained in
Leao-tong in Mantchuria, and in the province of Sse-tchouen. The
leaves, before becoming articles of commerce, undergo various
preparatory processes, according to the practice of the locality. In
the South, they cut them into extremely fine filaments; the people of
the North content themselves with drying them and rubbing them up
coarsely, and then stuff them at once into their pipes.
According to etiquette and the custom of the court, Persian
princes must have seven hours for sleep. When they get up, they
begin to smoke the narghilè or shishe, and they continue smoking all
day long. When there is company, the narghilè is first presented to
the chief of the assembly, who, after two or three whiffs, hands it to
the next, and so on it goes descending; but in general, the great
smoke only with the great, or with strangers of distinction. The
Schah smokes by himself, or only with one of his brothers, the
tombak, the smoke of which is of a very superior kind, the odour
being exquisite. It is the finest tombak of Shiraz.
Mr. Neale says—“Talk about the Turks being great smokers; why,
the Siamese beat them to nothing. I have often seen a child only
just able to toddle about, and certainly not more than two years of
age, quit its mother’s breast to go and get a whiff from papa’s
cigaret, or, as they are here termed, borees—cigarets made of the
dried leaf of the plantain tree, inside of which the tobacco is rolled
up.”
In Japan, after tea drinking, the apparatus for smoking is brought
in, consisting of a board of wood or brass, though not always of the
same structure, upon which are placed a small fire-pan with coals, a
pot to spit in, a small box filled with tobacco cut small, and some
long pipes with small brass heads, as also another japanned board
or dish, with socano—that is, something to eat, such as figs, nuts,
cakes, and sweetmeats. “There are no other spitting pots,” says
Kœmpfer, “brought into the room but those which come along with
the tobacco. If there be occasion for more, they make use of small
pieces of bamboo, a hand broad and high being sawed from
between the joints and hollowed.”
In Nicaragua, the dress of the urchins, from twelve or fourteen
downwards, consists generally of a straw hat and a cigar—the latter
sometimes unlighted and stuck behind the ear, but oftener lighted
and stuck in the mouth—a costume sufficiently airy and picturesque,
and excessively cheap. The women have their hair braided in two
long locks, which hang down behind, and give them a school-girly
look, quite out of keeping with the cool deliberate manner in which
they puff their cigars, occasionally forcing the smoke in jets from
their nostrils.7
On the Amazon, all persons—men and women—use tobacco in
smoking; when pipes are wanting, they make cigarillos of the fine
tobacco, wrapped in a paper-like bark, called Towarè; and one of
these is passed round, each person, even to the little boys, taking
two or three puffs in his turn.8
The Papuans pierce their ears and insert in the orifice, ornaments
or cigars of tobacco, rolled in pandan leaf, of which they are great
consumers.
A Spaniard knows no crime so black that it should be visited by
the deprivation of tobacco. In the Havana, the convict who is
deprived of the ordinary comforts, or even of the necessaries of life,
may enjoy his cigar, if he can beg or borrow it; if he stole it, the
offence would be considered venial. At the doorway of most of the
shops hang little sheet-iron boxes filled with lighted coals, at which
the passer-by may light cigars; and on the balustrade of the
staircase of every house stands a small chafing dish for the same
purpose. Fire for his cigar, is the only thing for which a Spaniard
does not think it necessary to ask and thank with ceremonious
courtesy. If he has permitted his cigar to go out, he steps up to the
first man he meets—nobleman or galley slave, as the case may be—
and the latter silently hands his smoking weed; for it is impossible
that two Spaniards should meet and not have one lighted cigar
between them. The light obtained, the lightee returns the cigar to
the lighter in silence. A short and suddenly checked motion of the
hand, as the cigar is extended, is the only acknowledgment of the
courtesy. This is never, however, omitted. Women smoke as well as
men; and in a full railroad car, every person, man, woman, and child,
may be seen smoking. To placard “no smoking allowed,” and enforce
it, would ruin the road.
A regular smoker in Cuba will consume perhaps twenty or thirty
cigars a day, but they are all fresh. What we call a fine old cigar, a
Cuban would not smoke.
At Manilla, the women smoke as well as the men. One
manufactory employs about 9,000 women in making the Manilla
cheroots; another establishment employs 3,000 men in making
paper cigars or cigarettes. The paper cigars are chiefly smoked by
men; the women prefer the “puros,” the largest they can get.
The Binua of Johore, of both sexes, indulge freely in tobacco. It is
their favourite luxury. The women are often seen seated together
weaving mats, and each with a cigar in her mouth. When speaking,
it is transferred to the perforation in the ear. When met paddling
their canoes, the cigar is seldom wanting. The Mintira women are
also much addicted to tobacco, but they do not smoke it.
In South America, many of the tribes are free indulgers in
tobacco; and this extends also to the female and juvenile sections of
the community. A story, which Signor Calistro narrated to Mr. Wallace
whilst travelling in the interior of Brazil, shows that it was nothing
but a common occurrence for little girls to smoke. This story is in
itself interesting considered apart from all circumstances of veracity.
“There was a negro who had a pretty wife, to whom another negro
was rather attentive when he had an opportunity. One day the
husband went out to hunt, and the other party thought it a good
opportunity to pay a visit to the lady. The husband, however,
returned rather unexpectedly, and the visitor climbed up on the
rafters to be out of sight, among the old boards and baskets that
were stowed away there. The husband put his gun by in a corner,
and called to his wife to get his supper, and then sat down in his
hammock. Casting his eyes up to the rafters, he saw a leg
protruding from among the baskets, and thinking it something
supernatural, crossed himself, and said, ‘Lord deliver us from the
legs appearing overhead!’ The other, hearing this, attempted to draw
up his legs out of sight; but, losing his balance, came down suddenly
on the floor in front of the astonished husband, who, half-frightened,
asked, ‘Where do you come from?’ ‘I have just come from heaven,’
said the other, ‘and have brought you news of your little daughter
Maria.’ ‘Oh, wife, wife! come and see a man who has brought us
news of our little daughter Maria!’ then, turning to the visitor,
continued, ’and what was my little daughter doing when you left?’
‘Oh, she was sitting at the feet of the Virgin with a golden crown on
her head, and smoking a golden pipe a yard long.’ ‘And did she send
any message to us?’ ‘Oh, yes; she sent many remembrances, and
begged you to send her two pounds of your tobacco from the little
rhoosa; they have not got any half so good up there.’ ‘Oh, wife, wife,
bring two pounds of our tobacco from the little rhoosa, for our
daughter Maria is in heaven, and she says they have not any half so
good up there.’ So the tobacco was brought, and the visitor was
departing, when he was asked, ‘Are there many white men up
there?’ ‘Very few,’ he replied; ‘they are all down below with the
diabo.’ ‘I thought so,’ the other replied, apparently quite satisfied;
‘good night.’”
On the Orinoco, tobacco has been cultivated by the native tribes
from time immemorial. The Tamanacs and the Maypures of Guiana
wrap maize leaves around their cigars as did the Mexicans at the
time of the arrival of Cortes; and, as in Chili, is done at the present
day. The Spaniards have substituted paper for the maize husks, in
imitation of them. The little cigarettos of Chili are called hojitas.
They are about two inches and a half long, filled with coarsely
powdered tobacco. As their use is apt to stain the fingers of the
smoker, the fashionable young gentlemen carry a pair of delicate
gold tweezers for holding them. The cigar is so small that it requires
not more than three or four minutes to smoke one. They serve to fill
up the intervals in a conversation. At tertulias, the gentlemen
sometimes retire to a balcony to smoke one or two cigars after a
dance.
The poor Indians of the forests of the Orinoco know, as well as did
the great nobles of the Court of Montezuma, that the smoke of
tobacco is an excellent narcotic; and they use it, not only to procure
an afternoon nap, but, also to induce a state of quiescence which
they call dreaming with the eyes open. At the Court of Montezuma
the pipe was held in one hand, while the nostrils were stopped with
the other, in order that the smoke might be more easily swallowed.
Bernal Diaz also informs us, that after Montezuma had dined, they
presented to him three little canes, highly ornamented, containing
liquid amber, mixed with a herb they call tobacco, and when he had
sufficiently viewed and heard the singers, he took a little of the
smoke of one of these canes, and then laid himself down to sleep. A
tribe of Indians originally inhabiting Panama, improved upon this
method, which occupied both hands, and involved considerable
trouble; the method adopted by the chiefs and great men of this
tribe, was to employ servants to blow tobacco smoke in their faces,
which was convenient and encouraged their indolence; they indulged
in the luxury of tobacco in no other way.
Amongst the Rocky Mountain Indians, it is a universal practice to
indulge in smoking, and when they do so they saturate their bodies
in smoke. They use but little tobacco, mixing with it a plant which
renders the fume less offensive. It is a social luxury, for the
enjoyment of which, they form a circle, and only one pipe is used.
The principal chief begins by drawing three whiffs, the first of which
he sends upward, and then passes the pipe to the person next in
dignity, and in like manner the instrument passes round until it
comes to the first chief again. He then draws four whiffs, the last of
which he blows through his nose, in two columns, in circling ascent,
as through a double flued chimney; and their pipes are not of the
race stigmatized by Knickerbocker as plebeian. None of the smoke of
those villanous short pipes, continually ascending in a cloud about
the nose, penetrating into and befogging the cerebellum, drying up
all the kindly moisture of the brain, and rendering the people who
use them vapourish and testy; or, what is worse, from being goodly,
burly, sleek-conditioned men, to become like the Dutch yeomanry
who smoked short pipes, a lantern-jawed, smoke-dried, leathern-
hided race. The red people, whether of the Rocky mountains or of
the Mississippi, belonged to the aristocracy of the long pipes. Let us
hope that they have not degenerated, and become followers of the
customs of the barbarian ultra-marines.
Turn over the leaves of “Westward Ho!” until you reach the end of
the seventh chapter, and then read of Salvation Yeo and his fiery
reputation, and his eulogium—“for when all things were made, none
was made better than this; to be a lone man’s companion, a
bachelor’s friend, a hungry man’s food, a sad man’s cordial, a
wakeful man’s sleep, and a chilly man’s fire, sir; while, for stanching
of wounds, purging of rheum, and settling of the stomach, there’s no
herb like unto it under the canopy of heaven.” The truth of which
eulogium Amyas testeth in after years. But, “mark in the
meanwhile,” says one of the veracious chroniclers from whom I draw
these facts, writing seemingly in the palmy days of good Queen
Anne and “not having (as he says) before his eyes the fear of that
misocapnic Solomon James I. or of any other lying Stuart,” “that not
to South Devon, but to North; not to Sir Walter Raleigh, but to Sir
Amyas Leigh; not to the banks of the Dart, but to the banks of
Torridge, does Europe owe the dayspring of the latter age, that age
of smoke which shall endure and thrive when the age of brass shall
have vanished, like those of iron and of gold, for whereas Mr. Lane is
said to have brought home that divine weed (as Spenser well names
it), from Virginia, in the year 1584, it is hereby indisputable that full
four years earlier, by the bridge of Pulford in the Torridge moors
(which all true smokers shall hereafter visit as a hallowed spot and
point of pilgrimage) first twinkled that fiery beacon and beneficent
loadstar of Bidefordian commerce, to spread hereafter from port to
port, and peak to peak, like the watch-fires which proclaimed the
coming of the Armada and the fall of Troy, even to the shores of the
Bosphorus, the peaks of the Caucasus, and the farthest isles of the
Malayan sea; while Bideford, metropolis of tobacco, saw her Pool
choked up with Virginian traders, and the pavement of her
Bridgeland Street groaning beneath the savoury bales of roll
Trinidado, leaf, and pudding; and the grave burghers, bolstered and
blocked out of their own houses by the scarce less savoury stockfish
casks which filled cellar, parlour, and attic, were fain to sit outside
the door, a silver pipe in every strong right hand, and each left hand
chinking cheerfully the doubloons deep lodged in the auriferous
caverns of their trunkhose; while in those fairy rings of fragrant mist,
which circled round their contemplative brows, flitted most pleasant
visions of Wiltshire farmers jogging into Sherborne fair, their heaviest
shillings in their pockets to buy (unless old Aubrey lies) the lotus leaf
of Torridge for its weight in silver, and draw from thence, after the
example of the Caciques of Dariena, supplies of inspiration much
needed then, as now, in those Gothamite regions. And yet did these
improve, as Englishmen, upon the method of those heathen
savages; for the latter (so Salvation Yeo reported as a truth, and
Dampier’s surgeon, Mr. Wafer, after him), when they will deliberate
of war or policy, sit round in the hut of the chief; where being
placed, enter to them a small boy with a cigarro of the bigness of a
rolling pin, and puffs the smoke thereof into the face of each warrior,
from the eldest to the youngest; while they, putting their hand
funnel-wise round their mouths, draw into the sinuosities of the
brain, that more than Delphic vapour of prophecy; which boy
presently falls down in a swoon, and being dragged out by the heels
and laid by to sober, enter another to puff at the sacred cigarro, till
he is dragged out likewise, and so on till the tobacco is finished, and
the seed of wisdom has sprouted in every soul into the tree of
meditation, bearing the flowers of eloquence, and, in due time, the
fruit of valiant action.” And with this quaint fact, narrated in the
bombastic style of chronicles, closeth the seventh chapter of the
voyages and adventures of Sir Amyas Leigh, under the style and title
already mentioned, and after which digression the course of our
narrative proceedeth as before.
The inhabitants of Yemen smoke their well-loved dschihschi pipes,
with long stems passed through water, that the smoke may come
cold to the mouth; and which, when a few inveterate smokers meet
together, keep up a boiling and bubbling noise, not unlike a distant
corps of drummers in full performance.
In the Austrian dominions, the lovers of the pipe may be found
amongst all classes of the community. Köhl writes, that after taking
two or three pipes of tobacco with the pasha at New Orsova, he
went into the market-place, where he found several merchants who
invited him to sit down, and again he was presented with a pipe.
From this place he went to a mosque, calling in at a school on his
way:——“The little Turkish students were making a most heathenish
noise, which contrasted amusingly with the quiet and sedate
demeanour of their teacher, who lay stretched upon a bench, where
he smoked his pipe, and said nothing.” He afterwards went to look
at the fortifications, and here and there saw a sentinel, with his
musket in one hand and pipe in the other. “Twenty-five soldiers were
seen smoking under a shed, and on the ground lay a number of
shells or hollow balls, which they assured us were filled with powder
and other combustibles, yet the soldiers smoked among them
unconcernedly, and allowed us to do the same.” A gentleman from
Constantinople told him that he had seen worse instances of
carelessness, in Asia Minor. He had there been one day in the tents
of a pasha, where some wet powder was drying and being made
into cartridges, and the men engaged in the work were smoking all
the while.
In the “Stettin Gazette,” lately appeared a notification that the
Prussian clergy had privately been requested by the higher
authorities to abstain from smoking in public. We are not
accustomed to it, and should certainly think it odd to see clergymen
perambulating the streets with short pipes in their mouths.
In all parts of the Sultan’s dominions, the pipe or narghilè has a
stem generally flexible, about six feet in length; and at this the
owner will suck for hours. You may see a man travelling, mounted
aloft on a tall camel, with his body oscillating to and fro like a sailor’s
when he rows, but still that man has his two yards of pipe before
him. You may see two men caulking a ship’s side as she lies
careened near the shore. Up to their waists in water, they act up to
the principle of division of labour; for one will smoke as the other
plies the hammer, and then the worker takes his turn at the narghilè.
Arabs sitting at work, fix their pipes in the sand. In the potteries
both hands must be employed—how, then, can the potter smoke?
Necessity is the mother of invention. One end of the pipe is
suspended by a cord from the ceiling, the other is in the potter’s
mouth.
In smoking, Lane informs us, the people of Egypt and other
countries of the East draw in their breath freely, so that much of the
smoke descends into the lungs; and the terms which they use to
express “smoking tobacco,” signify “drinking smoke,” or “drinking
tobacco;” for the same word signifies both smoke and tobacco. Few
of them spit while smoking; he had seldom seen them do so.
It was something like drinking of smoke that Napoleon
accomplished in his unsuccessful smoking campaign. He once took a
fancy to try to smoke. Everything was prepared for him, and his
Majesty took the amber mouth-piece of the narghilè between his
lips; he contented himself with opening and shutting his mouth
alternately, without in the least drawing his breath. “The devil,” he
replied—“why, there’s no result!” It was shewn that he made the
attempt badly, and the proper method practically exhibited to him.
At last he drew in a mouthful, when the smoke—which he had
discovered the means of drawing in, but knew not how to expel—
found its way into his throat, and thence by his nose, almost blinding
him. As soon as he recovered breath, he cried out—“Away with it!
What an abomination! Oh! the hog—my stomach turns!” In fact, the
annoyance continued for an hour, and he renounced for ever a habit
which, he said, was fit only to amuse sluggards.
Although Napoleon managed to fail, thousands less mighty have
managed to succeed. There is a curious kind of legend mentioned in
Brand’s Antiquities, by way of accounting for the frequent use and
continuance of taking tobacco, for the veracity of which he declares
that he will not vouch. “When the Christians first discovered
America, the devil was afraid of losing his hold of the people there
by the appearance of Christianity. He is reported to have told some
Indians of his acquaintance, that he had found a way to be revenged
on the Christians for beating up his quarters, for he would teach
them to take tobacco, to which, when they had once tasted it, they
should become perpetual slaves.”
Without venturing to authenticate this strange story, in the moral
of which Napoleon would have concurred—with a mental reservation
in favour of snuff—after the above defeat, let us console tobacco
lovers, that whilst the success of the first temptation closed the
gates of Paradise, the success of the second opens them again.
The following from an old collection of epigrams is, in every
respect, worthy of the theme.
“All dainty meats I do defie,
Which feed men fat as swine;
He is a frugal man indeed
That on a leaf can dine.
He needs no napkin for his hands
His fingers’ ends to wipe,
That keeps his kitchen in a box,
And roast meat in a pipe.”
In Hamburg, 40,000 cigars are smoked daily in a population
scarcely amounting to 45,000 adult males. And in London, the
consumption must be considerable to furnish, from the profits of
retailing, a living to 1566 tobacconists. In England, we may presume
that the largest smoker of tobacco must be the Queen, since an
immense kiln at the docks, called the Queen’s pipe, is occasionally
lighted and primed with hundredweights of tobacco, sea damaged or
otherwise spoiled, at the same time blowing a cloud
“Which Turks might envy, Africans adore.”
The total number of cigars consumed in France in 1857 is stated
to have been 523,636,000; and the total revenue of the French
Government from the tobacco monopoly is estimated at £7,320,000
annually. In Russia the revenue is £7,200,000 annually; and in
Austria near £3,000,000. These are large sums to pay for the
privilege of puffing.
The Buffalo Democracy estimates the annual consumption of
tobacco at 4,000,000,000 of pounds. This is all smoked, chewed, or
snuffed. Suppose it all made into cigars 100 to the pound, it would
produce 400,000,000,000 of cigars. These cigars, at the usual
length, four inches, if joined together, would form one continuous
cigar 25,253,520 miles long, which would encircle the earth more
than 1000 times. Cut up into equal pieces, 250,000 miles in length,
there would be over 1000 cigars which would extend from the centre
of the earth to the centre of the moon. Put these cigars into boxes
10 inches long, 4 inches wide, and 3 inches high, 100 to the box,
and it would require 4,000,000,000 boxes to contain them. Pile up
these boxes in a solid mass, and they would occupy a space of
294,444,444 cubic feet; if piled up 20 feet high, they would cover a
farm of 338 acres; and if laid side by side, the boxes would cover
nearly 20,000 acres. Allowing this tobacco, in its unmanufactured
state, to cost sixpence a pound, and we have 100,000,000 pounds
sterling expended yearly upon this weed; at least one-and-a-half
times as much more is required to manufacture it into a marketable
form, and dispose of it to the consumer. At the very lowest estimate,
then, the human family expend every year £250,000,000 in the
gratification of an acquired habit, or a crown for every man, woman,
and child upon the earth. This sum, the writer calculates, would
build 2 railroads round the earth at a cost of £5,000 per mile, or 16
railroads the Atlantic to the Pacific. It would build 100,000 churches,
costing £2,500 each, or 1,000,000 dwellings costing £25 each
(rather small!) It would employ 1,000,000 of preachers and
1,000,000 of teachers, giving each a salary of £125. It would
support 3⅓ millions of young men at college, allowing to each £75 a
year for expenses.
What a cloud the “human family” would blow if they had each his
share of the 4,000,000,000 pounds dealt out to him in cigars on the
morning of the 25th of December, in the year of our Lord, 1860. One
feels dubious as to the number who would refuse to take their
quota, if there were nothing to pay.
Dr. Dwight Baldwin states, that in 1851, the city of New York spent
3,650,000 dollars for cigars alone, while it only spent 3,102,500
dollars for bread. The Grand Erie Canal, 364 miles long, the longest
in the world, with its eighteen aqueducts, and eighty-four locks, was
made in six years, at a cost of 7,000,000 dollars. The cigar bill in the
city of New York would have paid the whole in two years.
The number of cigar manufactories in America is 1,400, and the
number of hands employed in them 7,000 and upwards. The total
estimated weekly produce of these manufactories is 17½ millions,
and the yearly 840 millions. At 7 dollars per 1,000, these would be
worth 5 million dollars, and adding 50 per cent. for jobber and
retailer, the total cost to consumers would be 7½ million dollars—
add to this the sum paid for imported cigars, 6 million dollars, and
we have 13½ million dollars, the value of cigars consumed yearly in
the United States, without adding profit to the imported cigars; so
that, including the amount expended in tobacco for smoking and
chewing, and in snuff, the annual cost of the tobacco consumed
yearly, is not less than 30 million dollars or £6,000,000. This is but
little more than is realized annually in Great Britain by the excise
duty alone on the tobacco consumed at home; but it must be
remembered, that in America tobacco is free of the duty of three
shillings and twopence per pound, and free of charges for an Atlantic
passage, so that the tobacco represented by 6 millions there, would
be represented here by at least six times that amount.
Cloudland costs something to keep up its dignity after all, but
beauty is seductive, and so is tobacco.
Yes! St. John (Percy, we mean—not “the Divine”), there must be
“magic in the cigar.” Then, to the sailor, on the wide and tossing
ocean, what consolation is there, save in his old pipe? While smoking
his inch and a half of clay, black and polished, his Susan or his Mary
becomes manifest before him, he sees her, holds converse with her
spirit—in the red glare from the ebony bowl, as he walks the deck at
night, or squats on the windlass, are reflected the bright sparkling
eyes of his sweetheart. The Irish fruit-woman, the Jarvie without a
fare, the policeman on a quiet beat, the soldier at his ease, all bow
to the mystic power of tobacco9—all acknowledge the infatuations of
Cloudland.
CHAPTER V.
PIPEOLOGY.

“It was his constant companion and solace. Was he gay, he


smoked—was he sad, he smoked—his pipe was never out of his
mouth—it was a part of his physiognomy; without it his best
friends would not know him. Take away his pipe—you might as
well take away his nose.”——Knickerbocker’s New York.

Semele, in a death by fire, became a martyr to love. Thus Virginia


suffers herself to be burnt for the good of the world. From the ashes
of the old Phœnix the young Phœnix was born. From the smoke of
the Havana spring new visions, and eloquent delights. As the altars
of the gods received honour from men, and the censers from
whence ascended the burning incense were sacred to the deities,
wherefore should not the pipe receive honour, as well as the man
who uses it, or the odorous weed consumed within it. An enthusiast
writes of it thus—“Philosophers have drawn their best similes from
their pipes. How could they have done so, had their pipes first been
drawn from them? We see the smoke go upwards—we think of life;
we see the smoke-wreath fade away—we remember the morning
cloud. Our pipe breaks—we mourn the fragility of earthly pleasures.
We smoke it to an end, and tapping out the ashes, remember that
‘Dust we are, and unto dust we shall return.’ If we are in love, we
garnish a whole sonnet with images drawn from smoking, and first
fill our pipe, and then tune it. That spark kindles like her eye, is
ruddy as her lip; this slender clay, as white as her hand, and slim as
her waist; till her raven hair grows grey as these ashes, I will love
her. This perfume is not sweeter than her breath, though sweeter
than all else. The odour ascends me into the brain, fills it full of all
fiery delectable shapes, which delivered over to the tongue, which is
the birth become delectable wit.”
The instruments by which the “universal weed” is consumed, are
almost as variable in form and material as the nations indulging in
their use. The pipe of Holland is of porcelain, and that of our own
island of unglazed clay. These latter are made in large quantities,
both at home and abroad.10 One factory at St. Omer employs 450
work-people, and produces annually 100,000 gross, or nearly fifteen
millions of pipes; and another factory at the same place employs 850
work-people, and produces 200,000 gross, or nearly thirty millions of
pipes, consuming nearly eight thousand tons of clay in their
manufacture. The quantity of pipes used annually in London is
estimated at 364,000 gross, or 52,416,000 pipes; it requires 300
men, each man making 20 gross four dozen per week, for one year,
to make them; the cost of which is £40,950. The average length of
these pipes is twelve and a half inches; and if laid down in a
horizontal position, end to end together, they would reach to the
extent of 10,340 miles, 1,600 yards; if they were piled one above
another perpendicularly, they would reach 135,138 times as high as
St. Pauls; they would weigh 1,137 tons, 10 cwts., and it would
require 104 tons, 9 cwts., 32 lbs. of tobacco to fill them. In 1857 we
imported clay pipes to the value of £7,614, which cannot be short of
121,000 gross, or seventeen and a half millions. But even with us,
pipes were not always of clay. The earliest pipes used in Britain are
stated to have been made from a walnut-shell and a straw. Dr. Royle
describes a very primitive kind of clay pipe used by some of the
natives of India—it is presumed only in cases of necessity. “The
amateur makes two holes, one longer than the other, with a piece of
stick in a clay soil, inclining the stick so that they may meet; into the
shorter hole he places the tobacco, and applies his mouth to the
other, and thus, as he lies upon the ground, luxuriates in the fumes
of the narcotic herb.”
Turkish pipe-bowls, or Lules, are composed of the red clay of Nish,
mixed with the white earth of the Roustchouck. They are very
graceful in form, and are in some cases ornamented with gilding.
The “regular Turk” prefers a fresh bowl daily; therefore the plain
ones are resorted to on the score of economy. In Turkey and some
other parts of the Orient, it is not unusual to compute distances, or
rather the duration of a journey, by the numbers of pipes which
might be smoked in the time necessary to accomplish it.
The pipe of the German is, almost universally, the Meerschaum,
that pipe of fame so coveted by the Northern smoker. These articles
are composed of a kind of magnesian earth, known to the Tartars of
the Crimea as keff-til. Pallas erroneously supposed that this kind of
earth was so denominated from Caffa, and therefore the name
signified “Caffa earth.” From “Meninski’s Oriental Dictionary” it would
appear to be a derivation of two Turkish words which signify “foam”
or “froth” of the “earth.” The French name, écume de mer, or “scum
of the sea,” and the Germans’ “sea foam,” have doubtless an
intimate relationship with this same “keff til” of the Crimean Tartars.
Meerschaum earth is met with in various localities in Spain,
Greece, Crimea, and Moravia. The greatest quantity is derived from
Asia Minor, it being dug principally in the peninsula of Natolia, near
the town of Coniah. Before the capture of the Crimea, this earth is
stated to have formed a considerable article of commerce with
Constantinople, where it was used in the public baths to cleanse the
hair of women. The first rude shape was formerly given to the pipe-
bowls on the spot where the mineral was dug, by pressure in a
mould; and these rude bowls were more elegantly carved and
finished at Pesth and Vienna. At the present time, the greater part of
the meerschaum is exported in the shape of irregular blocks; these
undergo a careful manipulation, after having been soaked in a
preparation of wax and oil. After being finished, and sold at the
German fairs, some of them have acquired such an exquisite tint
through smoking, in the estimation of connoisseurs, that they have
realized from £40 to £50.
Attempts have not been wanting to imitate this material, hitherto
not very successfully. The large quantity of parings that are left in
trimming up the bowls, has been rendered available for the
manufacture of what are called “massa bowls,” but they do not enjoy
the reputation of the genuine meerschaum bowls.
There is yet another mineral production, the use of which Turkish
smokers, at any rate, know how to appreciate. This is amber. The
Turk will expend an almost fabulous sum in an amber mouth-piece
for his narghileh. Four valuable articles of this description were
exhibited in the Turkish department of the Exhibition of 1851, which
were worth together £1000, two of them being valued at £305 each.
There is a current belief in Turkey that amber is incapable of
transmitting infection; and as it is considered a great mark of
politeness to offer the pipe to a stranger, this presumed property of
amber accounts in some measure for the estimation in which it is
held.
The knowledge of amber extends backwards to a remote antiquity,
as the Phœnicians of old fetched it from Prussia. Since that period it
has been obtained there uninterruptedly, without any diminution in
the quantity annually collected. The greatest amount of amber is
found on the coast of Prussia proper, between Konigsberg and
Dantzic. From the amber-beds on the coast of Dirschkeim, extending
under the sea, a storm threw up, on the 1st of January, 1848, no
less than 800 pounds. The amber fishery of Prussia formerly
produced to the king about 25,000 crowns per month. After a storm,
the amber coasts are crowded with gatherers, large masses of
amber being occasionally cast up by the waves. In digging for a well
in the coal-mines near Prague, the workmen lately discovered,
between the bed of gritstone which forms the roof of that mine and
the first layer of coals, a bed of yellow amber, apparently of great
extent. Pieces weighing from two to three pounds have been
extracted. There are two kinds—the terrestrial, which is dug in
mines, and the marine, which is cast ashore during autumnal
storms.
Opinions vary as to the origin of amber. Tacitus and others have
considered it a fossil resin exhaled by certain coniferous trees, traces
of which are frequently observed among the amber, whilst other
theorists contend that it is a species of wax or fat, having undergone
a slow process of putrefaction; this latter view being based upon the
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like