100% found this document useful (3 votes)
17 views84 pages

Mastering Linux Shell Scripting A Practical Guide To Linux Command Line Bash Scripting And Shell Programming Second Edition Mokhtar Ebrahim Andrew Mallett pdf download

The document is a promotional and informational piece about the book 'Mastering Linux Shell Scripting: A Practical Guide to Linux Command Line Bash Scripting and Shell Programming, Second Edition' by Mokhtar Ebrahim and Andrew Mallett. It includes links to download the book and other related titles, as well as details about the authors and the content covered in the book, which focuses on various aspects of Linux shell scripting. The document also provides information about the publisher, Packt Publishing, and encourages readers to explore additional resources and eBooks.

Uploaded by

zliukavioma
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 (3 votes)
17 views84 pages

Mastering Linux Shell Scripting A Practical Guide To Linux Command Line Bash Scripting And Shell Programming Second Edition Mokhtar Ebrahim Andrew Mallett pdf download

The document is a promotional and informational piece about the book 'Mastering Linux Shell Scripting: A Practical Guide to Linux Command Line Bash Scripting and Shell Programming, Second Edition' by Mokhtar Ebrahim and Andrew Mallett. It includes links to download the book and other related titles, as well as details about the authors and the content covered in the book, which focuses on various aspects of Linux shell scripting. The document also provides information about the publisher, Packt Publishing, and encourages readers to explore additional resources and eBooks.

Uploaded by

zliukavioma
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/ 84

Mastering Linux Shell Scripting A Practical

Guide To Linux Command Line Bash Scripting And


Shell Programming Second Edition Mokhtar Ebrahim
Andrew Mallett download
https://ebookbell.com/product/mastering-linux-shell-scripting-a-
practical-guide-to-linux-command-line-bash-scripting-and-shell-
programming-second-edition-mokhtar-ebrahim-andrew-
mallett-11145962

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Mastering Linux Shell Scripting Second Edition 2nd Edition Mokhtar


Ebrahim

https://ebookbell.com/product/mastering-linux-shell-scripting-second-
edition-2nd-edition-mokhtar-ebrahim-38624096

Mastering Linux Shell Scripting Master The Complexities Of Bash Shell


Scripting And Unlock The Power Of Shell For Your Enterprise Andrew
Mallett

https://ebookbell.com/product/mastering-linux-shell-scripting-master-
the-complexities-of-bash-shell-scripting-and-unlock-the-power-of-
shell-for-your-enterprise-andrew-mallett-5470908

Mastering Linux Shell Scripting Andrew Mallett

https://ebookbell.com/product/mastering-linux-shell-scripting-andrew-
mallett-96341792

Mastering Linux Shell Scripting Andrew Mallett Mokhtar Ebrahim

https://ebookbell.com/product/mastering-linux-shell-scripting-andrew-
mallett-mokhtar-ebrahim-232309938
Mastering Linux Security And Hardening A Practical Guide To Protecting
Your Linux System From Cyber Attacks 3rd Edition 3rd Donald A Tevault

https://ebookbell.com/product/mastering-linux-security-and-hardening-
a-practical-guide-to-protecting-your-linux-system-from-cyber-
attacks-3rd-edition-3rd-donald-a-tevault-47936950

Mastering Linux Administration Take Your Sysadmin Skills To The Next


Level By Configuring And Maintaining Linux Systems 2nd Ed 2nd
Alexandru Balog Calcatinge Julian

https://ebookbell.com/product/mastering-linux-administration-take-
your-sysadmin-skills-to-the-next-level-by-configuring-and-maintaining-
linux-systems-2nd-ed-2nd-alexandru-balog-calcatinge-julian-56998844

Mastering Linux Security And Hardening Secure Your Linux Server And
Protect It From Intruders Malware Attacks And Other External Threats
Tevault

https://ebookbell.com/product/mastering-linux-security-and-hardening-
secure-your-linux-server-and-protect-it-from-intruders-malware-
attacks-and-other-external-threats-tevault-20640198

Mastering Linux Device Driver Development Write Custom Device Drivers


To Support Computer Peripherals In Linux Operating Systems 1st Edition
John Madieu

https://ebookbell.com/product/mastering-linux-device-driver-
development-write-custom-device-drivers-to-support-computer-
peripherals-in-linux-operating-systems-1st-edition-john-
madieu-23274980

Mastering Linux Device Driver Development John Madieu

https://ebookbell.com/product/mastering-linux-device-driver-
development-john-madieu-30717172
Mastering Linux Shell Scripting
Second Edition

"QSBDUJDBMHVJEFUP-JOVYDPNNBOEMJOF#BTITDSJQUJOHBOE
4IFMMQSPHSBNNJOH

Mokhtar Ebrahim
Andrew Mallett

BIRMINGHAM - MUMBAI
Mastering Linux Shell Scripting
Second Edition
Copyright a 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.

Commissioning Editor: Vijin Boricha


Acquisition Editor: Rohit Rajkumar
Content Development Editor: Ron Mathew
Technical Editor: Prachi Sawant
Copy Editor: Safis Editing
Project Coordinator: Judie Jose
Proofreader: Safis Editing
Indexer: Mariammal Chettiyar
Graphics: Tom Scaria
Production Coordinator: Aparna Bhagat

First published: December 2015


Second edition: April 2018

Production reference: 1180418

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78899-055-4

XXXQBDLUQVCDPN
NBQUJP

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.

Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at XXX1BDLU1VCDPN and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at TFSWJDF!QBDLUQVCDPN for more details.

At XXX1BDLU1VCDPN, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.
Contributors

About the authors


Mokhtar Ebrahim started working as a Linux system administrator in 2010. He is
responsible for maintaining, securing, and troubleshooting Linux servers for multiple
clients around the world. He loves writing shell and Python scripts to automate his work.
He writes technical articles on the Like Geeks website about Linux, Python, web
development, and server administration. He is a father to a beautiful girl and a husband to
a faithful wife.

I would like to thank my wife for helping me with all her efforts to finish this book. Thank
you, Doaa, for being a part of that. Also, I would like to thank everyone at Packt for
working with me to make sure the book is released. Last but not least, I'd like to thank
Brian Fox, the author of the bash shell, for creating such an awesome piece of software;
without it, such a book would not exist.

Andrew Mallett is the owner of The Urban Penguin, and he is a comprehensive provider of
professional Linux software development, training, and services. Having always been a
command-line fan, he feels that so much time can be saved through knowing command-line
shortcuts and scripting. TheUrbanPenguin YouTube channel, maintained by Andrew, has
well over 800 videos to support this, and he has authored four other Packt titles.
About the reviewer
Sebastiaan Tammer is a Linux enthusiast from The Netherlands. After attaining his BSc in
Information Sciences, he graduated with MSc in Business Informatics, both from Utrecht
University. His professional career started in Java development before he pivoted into
Linux.

He has worked on number of technologies, such as Puppet, Chef, Docker, and Kubernetes.
He spends a lot of time in and around his terminal of choice: bash. Whether it is creating
complex scripting solutions or just automating simple tasks, there is hardly anything he
hasn't done with bash!

I would like to thank my girlfriend, Sanne, for all the help and support she has given me
throughout the years. She has had to endure the late nights studying, me fixing stuff
(which I had inevitably broken only hours earlier), and my endless storytelling about all
those exciting new technologies. Thanks for the enormous amount of patience and love, I
could not have done it without you!

Packt is searching for authors like you


If you're interested in becoming an author for Packt, please visit BVUIPSTQBDLUQVCDPN and
apply today. We have worked with thousands of developers and tech professionals, just
like you, to help them share their insight with the global tech community. You can make a
general application, apply for a specific hot topic that we are recruiting an author for, or
submit your own idea.
Table of Contents
Preface 1
Chapter 1: The What and Why of Scripting with Bash 6
Technical requirements 7
Types of Linux shells 7
What is bash scripting? 8
The bash command hierarchy 9
Command type 9
Command PATH 10
Preparing text editors for scripting 11
Configuring vim 12
Configuring nano 12
Configuring gedit 12
Creating and executing scripts 14
Hello World! 15
Executing the script 15
Checking the exit status 16
Ensuring a unique name 17
Hello Dolly! 17
Running the script with arguments 18
The importance of correct quotes 19
Printing the script name 21
Declaring variables 22
User-defined variables 22
Environment variables 23
Variable scope 24
Command substitution 25
Debugging your scripts 26
Summary 33
Questions 34
Further reading 34
Chapter 2: Creating Interactive Scripts 35
Technical requirements 35
Using echo with options 36
Basic script using read 37
Script comments 38
Enhancing scripts with read prompts 38
Limiting the number of entered characters 39
Table of Contents

Controlling the visibility of the entered text 40


Passing options 40
Passing parameters with options 42
Read options values 44
Try to be standard 45
Enhancing learning with simple scripts 46
Backing-up with scripts 46
Connecting to a server 48
Version 1 – ping 48
Version 2 – SSH 48
Version 3 – MySQL/MariaDB 49
Reading files 50
Summary 51
Questions 51
Further reading 52
Chapter 3: Conditions Attached 53
Technical requirements 54
Simple decision paths using command-line lists 54
Verifying user input with lists 56
Using the test shell built-in 56
Testing strings 57
Testing integers 58
Testing file types 59
Creating conditional statements using if 60
Extending if with else 61
Test command with the if command 62
Checking strings 62
Checking files and directories 65
Checking numbers 65
Combining tests 66
More conditions with elif 67
Creating the backup2.sh using elif 67
Using case statements 69
Recipe – building a frontend with grep 71
Summary 72
Questions 73
Further reading 74
Chapter 4: Creating Code Snippets 75
Technical requirements 75
Abbreviations 76
Using code snippets 77
Bringing color to the Terminal 78

[ ii ]
Table of Contents

Creating snippets using VS Code 80


Summary 85
Questions 85
Further reading 86
Chapter 5: Alternative Syntax 87
Technical requirement 87
Recapping the test command 88
Testing files 88
Adding logic 88
Square brackets as not seen before 88
Providing parameter defaults 90
Variables 90
Special parameters 90
Setting defaults 91
When in doubt – quote! 93
Advanced tests using [[ 95
White space 95
Other advanced features 96
Pattern matching 96
Regular expressions 96
Regular expression script 97
Arithmetic operations using (( 98
Simple math 98
Parameter manipulation 98
Standard arithmetic tests 99
Summary 100
Questions 100
Further reading 101
Chapter 6: Iterating with Loops 102
Technical requirement 103
for loops 103
Advanced for loops 106
The IFS 107
Counting directories and files 108
C-style for loops 109
Nested loops 110
Redirecting loop output 111
Controlling the loop 111
while loops and until loops 113
Reading input from files 114
Creating operator menus 116
Summary 119

[ iii ]
Table of Contents

Questions 119
Further reading 120
Chapter 7: Creating Building Blocks with Functions 121
Technical requirements 121
Introducing functions 122
Passing parameters to functions 125
Passing arrays 128
Variable scope 129
Returning values from functions 130
Recursive functions 132
Using functions in menus 133
Summary 135
Questions 135
Further reading 136
Chapter 8: Introducing the Stream Editor 137
Technical requirements 138
Using grep to display text 138
Displaying received data on an interface 138
Displaying user account data 139
Listing the number of CPUs in a system 140
Parsing CSV files 143
The CSV file 143
Isolating catalog entries 145
Understanding the basics of sed 146
The substitute command 147
Global replacement 148
Limiting substitution 150
Editing the file 150
Other sed commands 151
The delete command 151
The insert and append commands 152
The change command 153
The transform command 153
Multiple sed commands 154
Summary 154
Questions 155
Further reading 156
Chapter 9: Automating Apache Virtual Hosts 157
Technical requirements 158
Apache name-based Virtual Hosts 158
Creating the virtual host template 159
First steps 160

[ iv ]
Table of Contents

Isolating lines 160


sed script files 162
Automating virtual host creation 164
Prompting for data during site creation 166
Summary 169
Questions 170
Further reading 170
Chapter 10: AWK Fundamentals 171
Technical requirements 171
The history behind AWK 172
Displaying and filtering content from files 173
AWK variables 176
User-defined variables 178
Conditional statements 180
The if command 180
while loops 181
for loops 182
Formatting output 183
Further filtering to display users by UID 185
AWK control files 186
Built-in functions 187
Summary 187
Questions 188
Further reading 189
Chapter 11: Regular Expressions 190
Technical requirements 190
Regular expression engines 191
Defining BRE patterns 192
Anchor characters 193
The dot character 195
The character class 195
Ranges of characters 197
Special character classes 198
The asterisk 199
Defining ERE patterns 201
The question mark 201
The plus sign 203
Curly braces 204
The pipe character 206
Expression grouping 207
Using grep 208
Summary 209

[v]
Table of Contents

Questions 210
Further reading 210
Chapter 12: Summarizing Logs with AWK 211
Technical requirements 211
The HTTPD log file format 212
Displaying data from web logs 213
Selecting entries by date 213
Summarizing 404 errors 215
Summarizing HTTP access codes 215
Resources hits 217
Identify image hotlinking 218
Displaying the highest ranking IP address 219
Displaying the browser data 220
Working with email logs 221
Summary 221
Questions 222
Further reading 222
Chapter 13: A Better lastlog with AWK 223
Technical requirements 223
Using AWK ranges to exclude data 224
The lastlog command 224
Horizontally filtering rows with AWK 225
Counting matched rows 225
Conditions based on the number of fields 226
Manipulating the AWK record separator to report on XML data 228
Apache Virtual Hosts 228
XML catalog 229
Summary 231
Questions 232
Further reading 232
Chapter 14: Using Python as a Bash Scripting Alternative 233
Technical requirements 233
What is Python? 234
Saying Hello World the Python way 236
Pythonic arguments 236
Supplying arguments 237
Counting arguments 237
Significant whitespace 239
Reading user input 240
Using Python to write to files 241
String manipulation 242

[ vi ]
Table of Contents

Summary 243
Questions 244
Further reading 244
Assessments 245
Other Books You May Enjoy 252
Index 255

[ vii ]
Preface
First, you'll learn about Linux shells and why we chose the bash shell. Then, you'll learn
how to write a simple bash script and how to edit your bash script using Linux editors.

Following this, you will learn how to define a variable and the visibility of a variable. After
this, you will learn how to store command execution output into a variable, which is called
command substitution. Also, you will learn how to debug your code using bash options
and Visual Studio Code. You will learn how to make your bash script interactive to the user
by accepting input from the user using the read command. Then, you will learn how to read
options and its values if the user passed them to the script. Following this, you will learn
how to write conditional statements such as if statements and how to use case statements.
After this, you will learn how to create code snippets using vim and Visual Studio Code.
For repetitive tasks, you will see how to write for loops, how to iterate over simple values,
and how to iterate over directory content. Also, you will learn how to write nested loops.
Along with this, you will write while and until loops. Then, we will move on to functions,
the reusable chunks of code. You will learn how to write functions and how to use them.
After this, you will be introduced to one of the best tools in Linux, which is Stream Editor.
As we are still talking about text processing, we will introduce AWK, one of the best text
processing tools in Linux that you will ever see.

After this, you will learn how to empower your text processing skills by writing better
regular expressions. Finally, you will be introduced to Python as an alternative to bash
scripting.

Who this book is for


This book targets system administrators and developers who would like to write a better
shell script to automate their work. Some programming experience is preferable. If you
don't have any background in shell scripting, no problem, the book will discuss everything
from the beginning.
Preface

What this book covers


$IBQUFS, The What and Why of Scripting with Bash, will introduce Linux shells, how to
write your first shell script, how to prepare your editor, how to debug your shell script, and
some basic bash programming, such as declaring variables, variable scope, and command
substitution.

$IBQUFS, Creating Interactive Scripts, covers how to read input from the user using SFBE
command, how to pass options to your script, how to control the visibility of the entered
text, and how to limit the number of entered characters.

$IBQUFS, Conditions Attached, will introduce the JG statement, the DBTF statement, and
other testing command such as FMTF and FMJG.

$IBQUFS, Creating Code Snippets, covers creating and using code snippets using editors,
such as vim and Visual Studio Code.

$IBQUFS, Alternative Syntax, will discuss advanced testing using << and how to perform
arithmetic operations.

$IBQUFS, Iterating with Loops, will teach you how to use GPS loops, XIJMF loops, and
VOUJM loops to iterate over simple values and complex values.

$IBQUFS, Creating Building Blocks with Functions, will introduce functions and explains
how to create a function, list builtin functions, pass parameters to functions, and writing
recursive functions.

$IBQUFS, Introducing the Stream Editor, will introduce the basics of sed tool to manipulate
files, such as adding, replacing deleting, and transforming text.

$IBQUFS, Automating Apache Virtual Hosts, contains a practical example of sed and
explains how to create virtual hosts automatically using sed.

$IBQUFS, AWK Fundamentals, will discuss AWK and how to filter file content using it.
Also, we will discuss some AWK programming basics.

$IBQUFS, Regular Expressions, covers regular expressions, their engines, and how to use
them with sed and AWK to empower your script.

$IBQUFS, Summarizing Logs with AWK, will show how to process the IUUQEDPOG
Apache log file using AWK and extract useful well-formatted data.

[2]
Preface

$IBQUFS, A Better lastlog with AWK, will show you how to use AWK to output beautiful
reports using the lastlog command by filtering and processing the lastlog output.

$IBQUFS, Using Python as a Bash Scripting Alternative, will discuss Python programming
language basics and explains how to write some Python scripts as a bash script alternative.

To get the most out of this book


I assume that you have a little programming background. Even if you don't have a
programming background, the book will start from the beginning.

You should know some Linux basics such as the basic commands such as MT, DE, and
XIJDI.

Download the example code files


You can download the example code files for this book from your account at
XXXQBDLUQVCDPN. If you purchased this book elsewhere, you can visit
XXXQBDLUQVCDPNTVQQPSU and register to have the files emailed directly to you.

You can download the code files by following these steps:

1. Log in or register at XXXQBDLUQVCDPN.


2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR/7-Zip for Windows


Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at IUUQTHJUIVCDPN
1BDLU1VCMJTIJOH.BTUFSJOH-JOVY4IFMM4DSJQUJOH4FDPOE&EJUJPO. In case there's an
update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available
at IUUQTHJUIVCDPN1BDLU1VCMJTIJOH. Check them out!

[3]
Preface

Download the color images


We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it from IUUQTXXXQBDLUQVCDPNTJUFTEFGBVMUGJMFT
EPXOMPBET.BTUFSJOH-JOVY4IFMM4DSJQUJOH4FDPOE&EJUJPO@$PMPS*NBHFTQEG.

Conventions used
There are a number of text conventions used throughout this book.

$PEF*O5FYU: Indicates code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example: "Edit your script so that it reads like the following complete code block
for )0.&CJOIFMMPTI"

A block of code is set as follows:


JG<GJMF@DPNQSFTTJPO->UIFO
UBS@PQUUBS@M
FMJG<GJMF@DPNQSFTTJPO.>UIFO
UBS@PQUUBS@N
FMTF
UBS@PQUUBS@I
GJ

Any command-line input or output is written as follows:


$ type ls
ls is aliased to 'ls --color=auto'

Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"Another very useful feature is found on the Preferences | Plugins tab"

Warnings or important notes appear like this.

Tips and tricks appear like this.

[4]
Preface

Get in touch
Feedback from our readers is always welcome.

General feedback: Email GFFECBDL!QBDLUQVCDPN and mention the book title in the
subject of your message. If you have questions about any aspect of this book, please email
us at RVFTUJPOT!QBDLUQVCDPN.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit XXXQBDLUQVCDPNTVCNJUFSSBUB, selecting your book,
clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at DPQZSJHIU!QBDLUQVCDPN with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit
BVUIPSTQBDLUQVCDPN.

Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit QBDLUQVCDPN.

[5]
1
The What and Why of Scripting
with Bash
Welcome to the what and why of bash scripting. In this chapter, you will discover the types
of shells in Linux and why we chose bash. You will learn what bash is, how to write your
first bash script, and how to run it. Also, you will see how to configure Linux editors, such
as vim and nano, in order to type your code.

Like in any other scripting language, variables are the basic blocks of coding. You will learn
how to declare variables such as integers, strings, and arrays. Furthermore, you will learn
how to export these variables and extend their scope outside the running process.

Finally, you will see how to visually debug your code using Visual Studio Code.

We will cover the following topics in this chapter:

Types of Linux shells


What is bash scripting?
The bash command hierarchy
Preparing text editors for scripting
Creating and executing scripts
Declaring variables
Variable scope
Command substitution
Debugging your scripts
The What and Why of Scripting with Bash Chapter 1

Technical requirements
You'll need a running Linux box. It doesn't matter which distribution you use, since all
Linux distributions are shipped nowadays with the bash shell.

Download and install Visual Studio Code, which is free from Microsoft. You can download
it from here: IUUQTDPEFWJTVBMTUVEJPDPN.

You can use VS Code as an editor instead of vim and nano; it's up to you.

We prefer to use VS Code because it has a lot of features such as code completion,
debugging, and many more besides.

Install CBTIEC, which is a required package for the bash debug plugin. If you are using a
Red Hat-based distribution, you can install it like this:
$ sudo yum install bashdb

If you are using a Debian-based distribution, you can install it like this:
$ sudo apt-get install bashdb

Install the plugin for VS Code, called bash debug, from


IUUQTNBSLFUQMBDFWJTVBMTUVEJPDPNJUFNTJUFN/BNFSPHBMNJDCBTIEFCVH. This
plugin will be used to debug bash scripts.

The source code for this chapter can be downloaded here:


IUUQTHJUIVCDPN1BDLU1VCMJTIJOH.BTUFSJOH-JOVY4IFMM4DSJQUJOH4FDPOE
&EJUJPOUSFFNBTUFS$IBQUFS

Types of Linux shells


As you know, Linux consists of some major parts, such as the kernel, the shell, and the GUI
interface (Gnome, KDE, and so on).

The shell translates your commands and sends them to the system. Most Linux
distributions are shipped with many shells.

[7]
The What and Why of Scripting with Bash Chapter 1

Every shell has its own features, and some of them are very popular among developers
today. These are some of the popular ones:

Sh shell: This is called the Bourne shell, this was developed at AT&T labs in the
70s by a guy named Stephen Bourne. This shell offers many features.
Bash shell: Also called the Bourne again shell, this is very popular and
compatible with sh shell scripts, so you can run your sh scripts without changing
them. We are going to use this shell in this book.
Ksh shell: Also called the Korn shell, this is compatible with sh and bash. Ksh
offers some enhancements over the Bourne shell.
Csh and tcsh: Linux was built using the C language and that drove developers at
Berkeley University to develop a C-style shell in which the syntax is similar to the
C language. Tcsh adds some minor enhancements to csh.

Now we know the types of shells and we know that we are going to use bash, so what is
bash scripting?

What is bash scripting?


The basic idea of bash scripting is to execute multiple commands to automate a specific job.

As you might know, you can run multiple commands from the shell by separating them
with semi colons ():
ls ; pwd

The previous line is a mini bash script.

The first command runs, followed by the result of the second command.

Every keyword you type in bash scripting is actually a Linux binary (program), even the JG
statement, or FMTF or XIJMF loops. All are Linux executables.

You can say that the shell is the glue that binds these commands together.

[8]
The What and Why of Scripting with Bash Chapter 1

The bash command hierarchy


When working on the bash shell and when you are sitting comfortably at your prompt
eagerly waiting to type a command, you will most likely feel that it is a simple matter of
typing and hitting the Enter key. You should know better than to think this, as things are
never quite as simple as we imagine.

Command type
For example, if we type and enter MT to list files, it is reasonable to think that we were
running the command. It is possible, but we often will be running an alias. Aliases exist in
memory as a shortcut to commands or commands with options; these aliases are used
before we even check for the file. Bash's built-in UZQF command can come to our aid here.
The UZQF command will display the type of command for a given word entered at the
command line. The types of command are listed as follows:

Alias
Function
Shell built-in
Keyword
File

This list is also representative of the order in which they are searched. As we can see, it is
not until the very end where we search for the executable file MT.

The following command demonstrates the simple use type:


$ type ls
ls is aliased to 'ls --color=auto'

We can extend this further to display all the matches for the given command:
$ type -a ls
ls is aliased to 'ls --color=auto'
ls is /bin/ls

[9]
The What and Why of Scripting with Bash Chapter 1

If we need to just type in the output, we can use the U option. This is useful when we need
to test the command type from within a script and only need the type to be returned. This
excludes any superfluous information, and thus makes it easier for us humans to read.
Consider the following command and output:
$ type -t ls
alias

The output is clear and simple, and is just what a computer or script requires.

The built-in UZQF can also be used to identify shell keywords such as JG, and DBTF. The
following command shows UZQF being used against multiple arguments and types:
$ type ls quote pwd do id

The output of the command is shown in the following screenshot:

You can also see that the function definition is printed when we stumble across a function
when using UZQF.

Command PATH
Linux will check for executables in the 1"5) environment only when the full or relative
path to the program is supplied. In general, the current directory is not searched unless it is
in the 1"5). It is possible to include our current directory within the 1"5) by adding the
directory to the 1"5) variable. This is shown in the following command example:
$ export PATH=$PATH:.

[ 10 ]
The What and Why of Scripting with Bash Chapter 1

This appends the current directory to the value of the 1"5) variable; each item in the 1"5)
is separated using a colon. Now your 1"5) has been updated to include the current
working directory and, each time you change directories, the scripts can be executed easily.
In general, organizing scripts into a structured directory hierarchy is probably a great idea.
Consider creating a subdirectory called CJO within your home directory and add the scripts
into that folder. Adding )0.&CJO to your 1"5) variable will enable you to find the
scripts by name and without the file path.

The following command-line list will only create the directory, if it does not already exist:
$ test -d $HOME/bin || mkdir $HOME/bin

Although the preceding command-line list is not strictly necessary, it does show that
scripting in bash is not limited to the actual script, and we can use conditional statements
and other syntax directly at the command line. From our viewpoint, we know that the
preceding command will work whether you have the CJO directory or not. The use of the
)0.& variable ensures that the command will work without considering your current
filesystem context.

As we work through the book, we will add scripts into the )0.&CJO directory so that
they can be executed regardless of our working directory.

Preparing text editors for scripting


Throughout the book, we will be working on Linux Mint, and this will include the creation
and editing of the scripts. You, of course, can choose the way you wish to edit your scripts
and may prefer to make use of a graphical editor, so we will show some settings in gedit.
We will make one excursion into a Red Hat system to show screenshots of gedit in this
chapter.

Also, we will use Visual Studio Code as a modern GUI editor to edit and debug our scripts.

To help make the command-line editor easier to use, we can enable options and we can
persist with these options through hidden configuration files. Gedit and other GUI editors,
and their menus, will provide similar functionality.

[ 11 ]
The What and Why of Scripting with Bash Chapter 1

Configuring vim
Editing the command line is often a must and is part of a developer's everyday life. Setting
up common options that make life easier in the editor give us the reliability and consistency
we need, a little like scripting itself. We will set some useful options in the vi or vim editor
file, )0.&WJNSD.

The options we set are detailed in the following list:

TFUTIPXNPEF: Ensures we see when we are in insert mode


TFUOPIMTFBSDI: Does not highlight the words that we have searched for
TFUBVUPJOEFOU: We indent our code often; this allows us to return to the last
indent level rather than the start of a new line on each line break
TFUUBCTUPQ: Sets a tab to be four spaces
TFUFYQBOEUBC: Converts tabs to spaces, which is useful when the file moves to
other systems
TZOUBYPO: Note that this does not use the TFU command and is used to turn on
syntax highlighting

When these options are set, the )0.&WJNSD file should look similar to this:
TFUTIPXNPEF
TFUOPIMTFBSDI
TFUBVUPJOEFOU
TFUUBCTUPQ
TFUFYQBOEUBC
TZOUBYPO

Configuring nano
The nano text editor is increasing in importance and it is the default editor in many systems.
Personally, I don't like the navigation or the lack of navigation features that it has. It can be
customized in the same way as vim. This time, we will edit the )0.&OBOPSD file. Your
edited file should look something like the following:
TFUBVUPJOEFOU
TFUUBCTJ[F
JODMVEFVTSTIBSFOBOPTIOBOPSD

The last line enables syntax highlighting for shell scripts.

[ 12 ]
The What and Why of Scripting with Bash Chapter 1

Configuring gedit
Graphical editors, such as gedit, can be configured using the preferences menu, and are
pretty straightforward.

Enabling tab spacing to be set to 4 spaces and expanding tabs to spaces can be done using
the Preferences | Editor tab, as shown in the following screenshot:

You can download the example code files from your account at
IUUQXXXQBDLUQVCDPN for all the Packt Publishing books you have
purchased. If you purchased this book elsewhere, you can visit
IUUQXXXQBDLUQVCDPNTVQQPSU and register to have the files e-mailed
directly to you.

[ 13 ]
The What and Why of Scripting with Bash Chapter 1

Another very useful feature is found on the Preferences | Plugins tab. Here, we can enable
the Snippets plugin, which can be used to insert code samples. This is shown in the
following screenshot:

For the rest of the book, we will be working on the command line and in vim; feel free to
use the editor that you work with best. We have now laid the foundations to create good
scripts, and, although whitespace, tabs, and spaces in bash scripts are not significant, a well-
laid-out file with consistent spacing is easy to read. When we look at Python later in the
book, you will realize that in some languages, the whitespace is significant to the language
and it is better to adopt good habits early on.

Creating and executing scripts


With our editors primed and ready, we can now move quickly to creating and executing
our scripts. If you are reading this book with some prior experience, we will warn you that
we are going to start with the basics, but we will also include looking at positional
parameters; feel free to move on at your own pace.

[ 14 ]
The What and Why of Scripting with Bash Chapter 1

Hello World!
As you know, it is almost obligatory to begin with a )FMMP8PSME script and we will not
disappoint as far as this is concerned. We will begin by creating a new
script, )0.&CJOIFMMPTI. The contents of the file should read as in the following
screenshot:

We hope that you haven't struggled with this too much; it is just three lines, after all. We
encourage you to run through the examples as you read to really help you instill the
information with good hands-on practice.

CJOCBTI: Normally, this is always the first line of the script and is known as
the shebang. The shebang starts with a comment, but the system still uses this
line. A comment in a shell script has the  symbol. The shebang instructs the
interpreter of the system to execute the script. We use bash for shell scripts, and
we may use PHP or Perl for other scripts, as required. If we do not add this line,
then the commands will be run within the current shell; it may cause issues if we
run another shell.
FDIP)FMMP8PSME: The FDIP command will be picked up in a built-in shell
and can be used to write a standard output, 45%065; this defaults to the screen.
The information to print is enclosed in double quotes; there will be more on
quotes later.
FYJU: The FYJU command is a built-in shell, and is used to leave or exit the
script. The FYJU code is supplied as an integer argument. A value of anything
other than  will indicate some type of error in the script's execution.

Executing the script


With the script saved in our 1"5) environment, it still will not execute as a standalone
script. We will have to assign and execute permissions for the file, as needed. For a simple
test, we can run the file directly with bash. The following command shows you how to do
this:
$ bash $HOME/bin/hello1.sh

[ 15 ]
The What and Why of Scripting with Bash Chapter 1

We should be rewarded with the )FMMP8PSME text being displayed on our screens. This is
not a long-term solution, as we need to have the script in the )0.&CJO directory,
specifically, to make running the script easy from any location without typing the full path.
We need to add in the execute permissions as shown in the following code:
$ chmod +x $HOME/bin/hello1.sh

We should now be able to run the script simply, as shown in the following screenshot:

Checking the exit status


This script is simple, but we still need to know how to make use of the exit codes from
scripts and other applications. The command-line list that we generated earlier, while
creating the )0.&CJO directory, is a good example of how we can use the exit code:
$ command1 || command 2

In the preceding example, DPNNBOE is executed only if DPNNBOE fails in some way. To be
specific, DPNNBOE will run if DPNNBOE exits with a status code other than .

Similarly, in the following extract, we will only execute DPNNBOE if DPNNBOE succeeds
and issues an exit code of :
$ command1 && command2

To read the exit code from our script explicitly, we can view the  variable, as shown in the
following example:
$ hello1.sh
$ echo $?

The expected output is , as this is what we have added to the last line of the file and there
is precious little else that can go wrong to cause the failure to reach that line.

[ 16 ]
The What and Why of Scripting with Bash Chapter 1

Ensuring a unique name


We can now create and execute a simple script, but we need to consider the name a little. In
this case, IFMMPTI will be good enough and is unlikely to clash with anything else on the
system. We should avoid using names that may clash with existing aliases, functions,
keywords, and building commands, as well as avoiding names of programs already in use.

Adding the TI suffix to the file does not guarantee the name will be unique, but, in Linux,
where we do not use file extensions, the suffix is part of the filename. This helps you to
provide a unique identity to your script. Additionally, the suffix is used by the editor to
help you identify the file for syntax highlighting. If you recall, we specifically added the
syntax highlighting file TIOBOPSD to the nano text editor. Each of these files is specific to a
suffix and subsequent language.

Referring back to the command hierarchy within this chapter, we can use a UZQF to
determine the location and type of file IFMMPTI:
$ type hello1.sh #To determine the type and path
$ type -a hello1.sh #To print all commands found if the name is NOT unique
$ type -t hello1.sh ~To print the simple type of the command

These commands and output can be seen in the following screenshot:

Hello Dolly!
It is possible that we might need a little more substance in the script than a simple fixed
message. Static message content does have its place, but we can make this script much more
useful by building in some flexibility.

In this chapter, we will look at the positional parameters or arguments that we can supply
to the script and in the next chapter, we will see how we can make the script interactive and
also prompt the user for input at runtime.

[ 17 ]
The What and Why of Scripting with Bash Chapter 1

Running the script with arguments


We can run the script with arguments; after all, it's a free world and Linux promotes your
freedom to do what you want to do with the code. However, if the script does not make use
of the arguments, then they will be silently ignored. The following command shows the
script running with a single argument:
$ hello1.sh fred

The script will still run and will not produce an error. The output will not change either and
will print )FMMP8PSME:

Argument
Description
Identifier
 The name of the script itself, which is often used in usage statements.
 A positional argument, which is the first argument passed to the script.
Where two or more digits are needed to represent the argument
\^ position. Brace brackets are used to delimit the variable name from any
other content. Single value digits are expected.
The argument count is especially useful when we need to set the amount

of arguments needed for correct script execution.
 Refers to all arguments.

For the script to make use of the argument, we can change its content a little. Let's first copy
the script, add in the execute permissions, and then edit the new IFMMPTI:
$ cp $HOME/bin/hello1.sh $HOME/bin/hello2.sh
$ chmod +x $HOME/bin/hello2.sh

We need to edit the IFMMPTI file to make use of the argument as it is passed at the
command line. The following screenshot shows the simplest use of command-line
arguments, now allowing us to have a custom message:

[ 18 ]
The What and Why of Scripting with Bash Chapter 1

Run the script now; we can provide an argument as shown in the following:
$ hello2.sh fred

The output should now say )FMMPGSFE. If we do not provide an argument, then the
variable will be empty and will just print )FMMP. You can refer to the following screenshot
to see the execution argument and output:

If we adjust the script to use  , all the arguments will print. We will see )FMMP and then a
list of all the supplied arguments. Edit the script and replace the FDIP line as follows:
echo "Hello $*"

This will execute the script with the following arguments:


$ hello2.sh fred wilma betty barney

And this will result in the output shown in the following screenshot:

If we want to print )FMMPOBNF , with each name on a separate line, we will need to wait
a little until we cover looping structures. A GPS loop is a good way to achieve this.

The importance of correct quotes


So far, we have used a simple double-quoting mechanism to encase the strings that we want
to use with echo.

In the first script, it does not matter if we use single or double quotes. FDIP)FMMP
8PSME will be exactly the same as FDIP )FMMP8PSME .

[ 19 ]
The What and Why of Scripting with Bash Chapter 1

However, this is not the case in the second script, so it is very important to understand the
quoting mechanisms available in bash.

As we have seen, using double quotes in FDIP)FMMP will result in )FMMPGSFE or


whatever the supplied value is. Whereas, if we use single quotes in FDIP )FMMP , the
printed output on the screen will be )FMMP; that is, we see the variable name and not its
value.

The idea of the quotes is to protect special characters, such as a space between the two
words; both quotes protect the space from being misinterpreted. The space is normally read
as a default field, separated by the shell. In other words, all characters are read by the shell
as literals with no special meaning. This has the knock-on effect of the  symbol printing its
literal format rather than allowing bash to expand its value. The bash shell is prevented
from expanding the variable's value as it is protected by the single quotes.

This is where the double quote comes to our rescue. The double quote will protect all the
characters except the , allowing bash to expand the stored value.

If we ever need to use a literal  within the quoted string, along with variables that need to
be expanded, we can use double quotes, but escape the desired  with the backslash (=). For
example, FDIP64&3FBSOT= would print as 'SFEFBSOT if the current user
were Fred.

Try the following examples at the command line using all quoting mechanisms. Feel free to
up your hourly rate as required:
$ echo "$USER earns $4"
$ echo '$USER earns $4'
$ echo "$USER earns \$4"

The output is shown in the following screenshot:

[ 20 ]
The What and Why of Scripting with Bash Chapter 1

Printing the script name


The  variable represents the script name, and this is often used in usage statements. As
we are not yet looking at conditional statements, we will get the script name printed above
the displayed name.

Edit your script so that it reads like the following complete code block for
)0.&CJOIFMMPTI:

CJOCBTI
FDIP:PVBSFVTJOH
FDIP)FMMP 
FYJU

The output from the command is shown in the following screenshot:

If we prefer not to print the path and only want the name of the script to show, we can use
the CBTFOBNF command, which extracts the name from the path. Adjust the script so that
the second line now reads as follows:
echo "You are using $(basename $0)"

The   syntax is used to evaluate the output of the inner command. We first run
CBTFOBNF and feed the result into an unnamed variable represented by the .

The new output will appear as seen in the following screenshot:

It is possible to achieve the same results using back quotes; this is less easy to read, but we
have mentioned this as you might need to understand and modify the scripts that have
been written by others. The alternative to the   syntax is shown in the following
example:
echo "You are using 'basename $0'"

[ 21 ]
The What and Why of Scripting with Bash Chapter 1

Please note that the characters used are back quotes and NOT single quotes. On UK and US
keyboards, these are found in the top-left corner next to the number 1 key.

Declaring variables
Just like in any programming language, you can declare variables in bash scripts. So, what
are these variables and what are the benefits of using them?

Well, a variable is like a placeholder where you store some value for later use in your code.

There are two kinds of variables you can declare in your script:

User-defined variables
Environment variables

User-defined variables
To declare a variable, just type the name you want and set its value using the equals sign
().

Check out this example:


CJOCBTI
OBNF.PLIUBS
BHF
UPUBM
FDIPOBNFQSJOUT.PLIUBS
FDIPBHFQSJOUT
FDIPUPUBMQSJOUT

As you can see, to print the variable's value, you should use the dollar sign () before it.

Note that there are no spaces between the variable name and the equals sign, or between
the equals sign and the value.

If you forget and type a space in between, the shell will treat the variable as if it were a
command, and, since there is no such command, it will show an error.

[ 22 ]
The What and Why of Scripting with Bash Chapter 1

All of the following examples are incorrect declarations:


%PO UEFDMBSFWBSJBCMFTMJLFUIJT
OBNF.PLIUBS
BHF
UPUBM

Another useful type of user-defined variable is the array. An array can hold multiple
values. So, if you have tens of values you want to use, you should use arrays instead of
filling your script with variables.

To declare an array, just enclose its elements between brackets, like this:
CJOCBTI
NZBSS POFUXPUISFFGPVSGJWF

To access a specific array element, you can specify its index like this:
CJOCBTI
NZBSS POFUXPUISFFGPVSGJWF
FDIP\NZBSS<>^QSJOUTUXPXIJDIJTUIFTFDPOEFMFNFOU

The index is zero based.

To print the array elements, you can use an asterisk, like this:
CJOCBTI
NZBSS POFUXPUISFFGPVSGJWF
FDIP\NZBSS< >^

To remove a specific element from the array, you can use the VOTFU command:
CJOCBTI
NZBSS POFUXPUISFFGPVSGJWF
VOTFUNZBSS<>5IJTXJMMSFNPWFUIFTFDPOEFMFNFOU
VOTFUNZBSS5IJTXJMMSFNPWFBMMFMFNFOUT

Environment variables
So far, we have used variables that we didn't define, such as #"4)@7&34*0/, )0.&,
1"5), and 64&3. You might wonder, as we didn't declare these variables, where did they
come from?

[ 23 ]
The What and Why of Scripting with Bash Chapter 1

These variables are defined by the shell for your use and they are called environment
variables.

There are many environment variables. If you want to list them, you can use the QSJOUFOW
command.

Also, you can print a specific environment variable by specifying it to the QSJOUFOW
command:
$ printenv HOME

We can use any of these variables in our bash scripts.

Note that all environment variables are written in capital letters, so you can declare your
variables as lower case to make it easy to differentiate your variables from environment
variables. This is not required, but is preferable.

Variable scope
Once you have declared your variable, it will be available for use in your entire bash script
without any problems.

Let's assume this scenario: you have divided your code into two files and you will execute
one of them from inside the other, like this:
5IFGJSTUTDSJQU
CJOCBTI
OBNF.PLIUBS
TDSJQUTI5IJTXJMMSVOUIFTFDPOETDSJQU

The second script looks like this:


5IFTDSJQUTITDSJQU
CJOCBTI
FDIPOBNF

Suppose that you want to use the OBNF variable in the second script. If you try to print it,
nothing will show up; this is because a variable's scope is only limited to the process that
creates it.

To use the OBNF variable, you can export it using the FYQPSU command.

[ 24 ]
The What and Why of Scripting with Bash Chapter 1

So, our code will be like this:


5IFGJSTUTDSJQU
CJOCBTI
OBNF.PLIUBS
FYQPSUOBNF5IFWBSJBCMFXJMMCFBDDFTTJCMFUPPUIFSQSPDFTTFT
TDSJQUTI

Now if you run the first script, it will print the name that came from the first script file.

Keep in mind that the second process or TDSJQUTI only makes a copy of the variable and
never touches the original one.

To prove this, try to change that variable from the second script and try to access that
variable value from the first script:
5IFGJSTUTDSJQU
CJOCBTI
OBNF.PLIUBS
FYQPSUOBNF
TDSJQUTI
FDIPOBNF

The second script will be like this:


5IFGJSTUTDSJQU
CJOCBTI
OBNF"OPUIFSOBNF
FDIPOBNF

If you run the first script, it will print the modified OBNF from the second script and then it
will print the original OBNF from the first script. So, the original variable remains as it is.

Command substitution
So far, we have seen how to declare variables. These variables can hold integers, strings,
arrays, or floats, as we have seen, but this is not everything.

A command substitution means storing the output of a command execution in a variable.

[ 25 ]
The What and Why of Scripting with Bash Chapter 1

As you might know, the QXE command prints the current working directory. So, we will see
how to store its value in a variable.

There are two ways to perform a command substitution:

Using the backtick character ( )


Using the dollar sign format, like this: 

Using the first method, we just surround the command between two backticks:
CJOCBTI
DVS@EJS QXE
FDIPDVS@EJS

And the second way is written as follows:


CJOCBTI
DVS@EJS QXE
FDIPDVS@EJS

The output coming from commands can be further processed and actions can be made
based on that output.

Debugging your scripts


With the scripts as simple as we have seen so far, there is little that can go wrong or need
debugging. As the script grows and decision paths are included with conditional
statements, we may need to use some level of debugging to analyze the scripts' progress
better.

Bash provides two options for us, W and Y.

If we want to look at the verbose output from our script and the detailed information about
the way the script is evaluated line by line, we can use the W option. This can be within the
shebang, but it is often easier to run the script directly with bash:
$ bash -v $HOME/bin/hello2.sh fred

[ 26 ]
The What and Why of Scripting with Bash Chapter 1

This is especially useful in this example as we can see how each element of the embedded
CBTFOBNF command is processed. The first step is removing the quotes and then the
parentheses. Take a look at the following output:

The Y option, which displays the commands as they are executed, is more commonly used.
It's useful to know the decision branch that has been chosen by the script. The following
shows this in action:
$ bash -x $HOME/bin/hello2.sh fred

We again see that the CBTFOBNF is evaluated first, but we do not see the more detailed steps
involved in running that command. The screenshot that follows captures the command and
output:

[ 27 ]
The What and Why of Scripting with Bash Chapter 1

The previous method might be hard for beginners or people who have a programming
background in which they debugged their code visually.

Another modern way of debugging shell scripts is by using Visual Studio Code.

There is a plugin called bash debug that enables you to debug bash scripts visually, as is
the case for any other programming language.

You can step into, step over, add watches, and do all the other usual debugging stuff you
know.

After installing the plugin, from the File menu, open your TIFMMTDSJQUT folder. Then
you can configure the debugging process by pressing Ctrl + Shift + P and typing the
following:
%FCVHPQFOMBVODIKTPO

This will open an empty file; type in the following configurations:


\
WFSTJPO
DPOGJHVSBUJPOT<
\
OBNF1BDLU#BTI%FCVH
UZQFCBTIEC
SFRVFTUMBVODI
TDSJQU1BUI\DPNNBOE4FMFDU4DSJQU/BNF^
DPNNBOE-JOF"SHVNFOUT
MJOVY\
CBTI1BUICBTI
^
PTY\
CBTI1BUICBTI
^
^
>
^

[ 28 ]
The What and Why of Scripting with Bash Chapter 1

This will create a debug configuration named 1BDLU#BTI%FCVH:

[ 29 ]
The What and Why of Scripting with Bash Chapter 1

Now insert a breakpoint and press F5, or start debugging from the Debug menu; it will
show you the list of TI files:

[ 30 ]
The What and Why of Scripting with Bash Chapter 1

Select the one you want to debug, and set a breakpoint on any line to test it, as shown in the
following screenshot:

[ 31 ]
The What and Why of Scripting with Bash Chapter 1

You can add watches to watch variables' values while stepping over your lines of code:

Note that your script MUST start with the bash shebang, CJOCBTI.

Now you can enjoy the visual method of debugging. Happy coding!

[ 32 ]
The What and Why of Scripting with Bash Chapter 1

Summary
This marks the end of this chapter and you have no doubt found this useful. Especially for
those making a start with bash scripting, this chapter will have established a firm
foundation on which you can build your knowledge.

We began by ensuring that bash is secure and not susceptible to shell-shock from embedded
functions. With bash secured, we considered the execution hierarchy where aliases,
functions, and so on are checked before the command; knowing this can help us plan a
good naming structure and a path to locate the scripts.

Then we went on to illustrate the types of Linux shells and we found out what bash
scripting is.

Soon, we were writing simple scripts with static content, but we saw how easy it was to add
flexibility using arguments. The exit code from the script can be read with the  variable
and we can create a command-line list using ]] and , which depends on the success or
failure of the preceding command in the list.

Then we saw how to declare variables and how to use environment variables. We identified
the variables' scope and saw how to export them to another process.

Also, we saw how to store commands' output in variables, which is called command
substitution.

Finally, we closed the chapter by looking at debugging the script using bash options and VS
Code. It's not really required when the script is trivial, but it will be useful later when
complexity is added.

In the next chapter, we will create interactive scripts that read the user's input during script
execution.

[ 33 ]
The What and Why of Scripting with Bash Chapter 1

Questions
1. What is the problem with the following code? And how do we fix it?
CJOCBTI
WBS8FMDPNFUPCBTITDSJQUJOH
FDIPWBS

2. What is the result of the following code?


CJOCBTI
BSS 4BUVSEBZ4VOEBZ.POEBZ5VFTEBZ8FEOFTEBZ
FDIP\BSS<>^

3. What is the problem with the following code? And how do we fix it?
CJOCBTI
GJMFT MTMB
FDIPGJMFT

4. What is the value of the b and c variables in the following code?


CJOCBTI
B
C
DB
CD

Further reading
Please see the following for further reading relating to this chapter:

IUUQUMEQPSH)0850#BTI1SPH*OUSP)0850IUNM
IUUQUMEQPSH-%1BCTIUNMWBSBTTJHONFOUIUNM
IUUQUMEQPSH-%1BCTIUNMEFDMBSFSFGIUNM

[ 34 ]
2
Creating Interactive Scripts
In $IBQUFS, The What and Why of Scripting with Bash, we learned how to create a script and
use some of its basic elements. These included optional parameters that we can pass
through to the script when it is executed. In this chapter, we will extend this by using
the shell's built-in SFBE command to allow for interactive scripts. Interactive scripts are
scripts that prompt for information during the script's execution.

In this chapter, we will cover the following topics:

Using FDIP with options


Basic script using SFBE
Script comments
Enhancing read scripts with SFBE prompts
Limiting the number of entered characters
Controlling the visibility of the entered text
Passing options
Read options values
Try to be standard
Enhancing learning with simple scripts

Technical requirements
The source code for this chapter can be downloaded from here:
IUUQTHJUIVCDPN1BDLU1VCMJTIJOH.BTUFSJOH-JOVY4IFMM4DSJQUJOH4FDPOE
&EJUJPOUSFFNBTUFS$IBQUFS
Creating Interactive Scripts Chapter 2

Using echo with options


So far, in this book we have been able to see that the FDIP command is very useful and is
going to be used in many of our scripts, if not all of them. When running the FDIP
command, the built-in command will be used unless we state the full path to the file. We
can test this with the following command:
$ which echo

To gain help on the built-in command, we can use man bash and search for FDIP; however,
the FDIP command is identical to the internal command, so we recommend that you use
man echo in most cases in order to display the command options.

The basic use of FDIP that we have seen so far will produce a text output and a new line.
This is often the desired response, so we don't need to be concerned that the next prompt
will append to the end of the echoed text. The new line separates the script output from the
next shell prompt. If we do not supply any text string to print, FDIP will print only the new
line to 45%065. We can test this with the following command, directly from the command
line. We do not need to run FDIP or, in fact, any other command from a script. To run FDIP
from the command line, we simply enter the command as shown:
$ echo

The output will show a clear new line between the command we issued and the subsequent
prompt. We can see this in the following screenshot:

If we want to suppress the new line, which is especially useful if we are to prompt users, we
can do this in the following two ways, with the help of FDIP:
$ echo -n "Which directory do you want to use? "
$ echo -e "Which directory do you want to use? \c"

The result will be to suppress the line feed. In the initial example, the O option is used to
suppress the line feed. The second example uses the more generic F option, which allows
escape sequences to be added to the text string. To continue on the same line, we use =D as
the escape sequence.

[ 36 ]
Creating Interactive Scripts Chapter 2

This does not look great as the final part of the script or when it is run from the command
line, as the command prompt will follow. This is illustrated in the following screenshot:

Basic script using read


When used as part of a script that prompts for user input, the suppression of the line feed is
exactly what we want. We will begin by copying the existing IFMMPTI script to
IFMMPTI and build an interactive script. Initially, we will use FDIP as the prompt
mechanism, but, as we gradually enhance the script, we will generate the prompt directly
from the shell built-in SFBE command:
$ cp $HOME/bin/hello2.sh $HOME/bin/hello3.sh
$ chmod +x $HOME/bin/hello3.sh

Edit the )0.&CJOIFMMPTI script so that it reads as follows:


CJOCBTI
FDIPO)FMMP CBTFOBNF .BZ*BTLZPVSOBNF
SFBE
FDIP)FMMP3&1-:
FYJU

As we execute the script, we will be greeted and prompted with whatever is typed. This is
echoed using the 3&1-: variable in the echo statement. As we have not yet supplied a
variable name to the read built-in command, the default 3&1-: variable is used. The script
execution and output are shown in the following screenshot. Take some time to practice the
script on your own system.

[ 37 ]
Other documents randomly have
different content
The Project Gutenberg eBook of The Pillars of
the House; Or, Under Wode, Under Rode, Vol.
2 (of 2)
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: The Pillars of the House; Or, Under Wode, Under Rode,
Vol. 2 (of 2)

Author: Charlotte M. Yonge

Release date: January 20, 2014 [eBook #44721]


Most recently updated: October 24, 2024

Language: English

Credits: E-text prepared by Clare Graham and Marc D'Hooghe


(http://www.freeliterature.org) from page images
generously made available by the Google Books Library
Project (http://books.google.com)

*** START OF THE PROJECT GUTENBERG EBOOK THE PILLARS OF


THE HOUSE; OR, UNDER WODE, UNDER RODE, VOL. 2 (OF 2) ***
The Project Gutenberg eBook, The Pillars of the House, Vol. II (of 2),
by Charlotte M. Yonge

Note: Images of the original pages are available through Internet


Archive. See http://www.google.com/books?
id=FQgCAAAAQAAJ

Project Gutenberg has the other volume of this work.


Volume I: see http://www.gutenberg.org/files/6331/6331-
h/6331-h.htm

THE PILLARS OF THE HOUSE;


OR,

UNDER WODE, UNDER RODE.

BY
CHARLOTTE M. YONGE,
AUTHOR OF 'THE HEIR OF REDCLYFFE,' ETC.

IN TWO VOLUMES.

VOL II.

London:

MACMILLAN AND CO.

1875.

CONTENTS TO VOL II.

XXIV. FAMILY GHOOLS


XXV. DON GIOVANNI
XXVI. TRANSMUTATION
XXVII. DON OR MYNHEER
XXVIII. STARS GRATIS
XXIX. BRYNHILD
XXX. THE SCULPTOR
XXXI. THE BARBE BLONDE
XXXII. THE NID D'AVIS
XXXIII. A BOOTLESS BENE
XXXIV. THE VICAR OF VALE LESTON
XXXV. THE OLD SQUIRE AND THE NEW
XXXVI. POSSESSION
XXXVII. INVASIONS
XXXVIII. K.T.
XXXIX. FOUR YEARS
XL. A K T STROPHE
XLI. CHESTS AND HEARTS
XLII. A HALCYON DAY
XLIII. PRINCESS FAIR-STAR
XLIV. THE FIDDLER'S RANCH
XLV. THE MYRTLE SPRAY
XLVI. SOUR GRAPES
XLVII. THE TASK OVER
XLVIII. SHATTERED PILLARS
XLIX. THE RIVAL OWLS
CONCLUSION

CHAPTER XXIV.

FAMILY GHOOLS.

'Know ye that Love is a careless child,


And forgets promise past?
He is blind—he is deaf where he list,
And in faith never fast.'
Raleigh.

Captain Harewood was gone. There was a good deal of truth in


Wilmet's plea that much pain might have been saved if she had been
allowed to abide by her first answer; but by this time she would not
have saved it.
She was a brave woman, and never sought indulgence; and all she
accepted was the spending his last Saturday and Sunday at his
home with him; and even on this she durst not venture without
taking Alda, and exposing the dear untidy household to her disdain;
but that October Sunday walk by the river was worth it all—worth
infinitely more than the July walk; and they both declared it gave
them strength.
Wilmet returned in time for Monday's school, nor did she give in all
the week; but she looked whiter and whiter, and on Saturday
morning turned so faint while dressing, that Alda in a great fright
called in Sibby; and the unprecedented event occurred of her
spending two whole days in bed. She only begged to be let alone;
and after this space of quiet came down again fully recovered, only,
as Geraldine daily felt, softer, gentler, tenderer, less severely strict,
and moreover a less hard mistress to her own beauty.
Meantime Alda grew increasingly restless and drooping as the
autumn advanced. The confined rooms and monotonous life really
affected health accustomed to variety, change, and luxury; nor could
idleness, disappointment, or ill-humour be wholesome diet. Listless
and weary, she dropped all semblance of occupation, except novel
reading; and there she perversely set her mind on whatever
Froggatt and Underwood wished to keep out of their library. If
Ferdinand did come down for a Sunday, they both looked at the end
of it as if they had been worrying one another to death; if he did not
come down, she was affronted and miserable. Her restlessness was
increased by the fact that people were returning to their winter-
quarters in London, and it was to be inferred that the Thomas
Underwoods might soon be there; but Marilda had not the art of
letter-writing, and though she had several times sent a few warm-
hearted lines, encouraging Alda's correspondence, this had dropped
soon after the yearly migration to Spa; and no more was known of
the family movements till there was a letter from Edgar to Cherry.
He was a very uncertain correspondent—always delightful,
affectionate, and amusing, when he did write, but often not doing so
for weeks together; and nothing had been heard of him since he had
as usual gone abroad in the middle of the summer.
He now wrote from Spa, in amazement at the accumulation of family
events which Marilda had poured upon him, and especially desirous
to know how any captain of any service had ventured upon
accosting W.W. He could not recover the loss it had been not to
witness the siege and the surrender! For himself, Cherry gathered
that he had begun, as he had led her to suppose he would, with the
Channel Isles; but whether he had seen Alice she could not make
out; and he had then made his way, wandering and sketching in old
Continental towns, as he had done last year. He always declared that
it answered; he could dispose of his sketches when he came home,
and could likewise write clever bright descriptions, that could usually
command tolerable remuneration. This time, however, he had been
nearly reduced to the condition of George Primrose, and had made
his way to join the family caravan at Spa, by way of getting helped
home.
There he was hailed with delight, for Mr. Underwood was very unwell
and irritable, prejudiced against German doctors, yet not choosing to
have advice from England, and not fit for a journey without some
effective person to rule him and his wife; for resolute as Marilda
could be, the passionateness of one parent, and the fat flabby
helplessness of the other, had overcome her powers of management
at such a distance from home. It was Edgar's private belief that 'the
poor old boy had had some kind of stroke;' but he had
recommended the homeward journey, and under his escort it was to
be immediately undertaken. A few days more, and tidings came that
it had been successfully accomplished. Mr. Underwood had grown
better at every stage, and now scouted the notion of a doctor; Alda's
letters of inquiry were joyously answered and her spirits sank.
One afternoon, however, a moon face beamed upon Felix, and a
hearty voice exclaimed, 'How d'ye do? This is a surprise, ain't it? My
father is come down on business, so I made him bring me. I don't
like Alda's account of herself.'
'I'll take you to her,' said Felix, who decidedly disapproved of private
greetings in the present locality; so as soon as she had dealt with
her fly, he conducted her upstairs. Her father had gone to Mr. Bruce,
and would come for her. Alda was alone in the drawing-room, but
she sprang to her feet in ecstacy; and the two cousins were soon
clinging together, and devouring one another with kisses. Felix asked
where Cherry was.
'Oh! for pity's sake, Felix, do let us have a little time to ourselves!'
said Alda; 'I'll call Cherry by the time she has done with Stella.'
Felix had come to trust nothing concerning Geraldine to Alda; so he
shut the door, and found Cherry in her own room, overlooking
Stella's copy to the sound of Theodore's accordion, all three in warm
jackets. Six months ago he would have made an authoritative
remonstrance. Now he had learnt that cold and exile were more
tolerable than Alda's displeasure.
Stella leapt up, connecting Cousin Marilda's name with the choicest
presents; but Cherry was quite willing to withhold herself. It was
eight years since she had seen Marilda, and she was conscious of
more repulsion than attraction. She was still debating between
civility and consideration for the tête-à-tête, when Wilmet, for whom
Felix had sent, came for her, with cheeks glowing from Marilda's
energetic kisses and congratulations.
There certainly was a treading on the delicate tips of the feelings. 'O
Geraldine, I am glad to see you getting about so well! You are a
courageous girl.' Then to Stella: 'You little darling duck! Here is a box
of goodies for you and the other poor little dear.—Where is he? You'll
let me see him.—What, Lance! I've not seen you since I found you
up a tree!'
The cousinly cordiality was pleasant, and her patronage was not
coarse, like her mother's; but there was a certain excess of
frankness that made them feel like sensitive-plants, when she
examined Wilmet how often she heard from India, and how the
Harewoods treated her—when she wanted to know exactly how
matters stood between the Pursuivant and Tribune, whether Mr.
Smith were to blame, why Lance had gone into the business, and—
worse than all—what was the measure of Theodore's intellect.
It was all meant in kindness and sympathy, but it was very trying to
each victim in turn; and the lookers-on found it as impossible to lead
it away as to divert the rush from a pump. When Felix was about to
return to his work, Marilda jumped up, exclaiming, 'Felix, I must
speak to you;' and when she had him alone in the drawing-room,
she began, 'Felix, I must take Alda home. We can't get on without
her; and she looks very poorly, and all that nonsense is blown over.'
'You know she is still engaged.'
'Oh yes; but no one will think of that unless it is brought forward,
and that she promises not to do.'
'I believe it will be best,' he answered. 'Our life is not suited to her,
and she is neither well nor happy; but it is very kind of you.'
'Kind to ourselves. If Wilmet had married at once we should never
have got her back at all, and we want her sadly. I can help my father
in some ways, but I can't amuse him as she can. You don't mind?'
'Certainly not, if Mr. and Mrs. Underwood wish it,' said Felix,
wondering how Alda made herself either amusing or useful; 'I
suppose it is all right, and that they know how it stands.'
'Of course they do. They will only be too glad to have her; and
though it is better to say nothing about it just yet, very likely it may
end in his coming into our house, and being what Edgar might have
been. How well he has behaved!'
'So has some one else,' thought Felix, as he saw her glistening eye;
but he only answered, 'He is an excellent fellow.'
'Another thing, Felix. This engagement of Edgar's—is it in earnest?'
'Yes!' emphatically said Felix; 'I trust so.'
'You! I should have thought nothing could be more foolish. Is she
such a nice girl, then?'
He had had time to recollect himself, and answered in his set
manner, 'She is all that could be wished; and though of course there
is a certain imprudence in the engagement, I can only wish to see
Edgar persevere honourably in what he has undertaken.'
'But wouldn't it be great misery?'
'It might be,' said Felix; 'but it is not going to happen yet. Of course,
no one could have wished it to begin; but having begun, he ought to
go on.'
'Of course! I hate shilly-shally. My father would not believe there was
anything in it. But you are right, Felix; it has done Edgar good.
Somehow there's more purpose in him; and I believe he has worked
more steadily this season. I am so glad you say she is a nice girl.'
And Felix went down to his work happier than he had been for
nearly a year. What loss to himself equalled the gain of such a report
of Edgar?
Marilda insisted on being shown every corner of the house, and was
evidently full of enjoyment, like a child let loose from school, talking
at random, so as to draw on herself more than one remonstrance
from Alda, who had perfectly recovered her good-humour, and was
absolutely gracious to Cherry.
About four o'clock came Thomas Underwood, embracing Alda like
another daughter. 'My poor child, you are not looking well.'
'Not at all, papa,' said Marilda. 'We will take her home, and set her
up again.'
'Ay, we will!' said her father. 'It has been a pretty muddle altogether;
but there—we'll say no more about it. You'll come home, and be a
wise girl.'
'O Uncle, how kind you are!' cried Alda.
Wilmet and Cherry looked at each other in amaze. What might this
mean? How could Alda bear to be received back on such terms? But
they could say nothing; indeed, they were scarcely seen till the
greeting to Alda was over. Then, however, he made up for it by
hearty kisses, for which they were not prepared; and Wilmet
coloured crimson as she was again congratulated and rallied on her
slyness in making the most of her time at Minsterham.
The illness at Spa had told upon Thomas Underwood. He was still
under fifty, but an elderly look and manner had come on him; he
walked feebly, and seemed to look to his daughter to help him out
with purposes and recollections; while towards Alda there was an
almost imploring tenderness, as if she had carried away with her a
good deal of the enjoyment of his life, which he hoped to bring back
again with her. He did not even seem to like leaving her for the
evening to pack up, but wanted her to come out to Centry Park, and
caught eagerly at Marilda's proposal that Felix should come and
spend the evening there. It was as if they were both afraid of their
own dullness in the great uninhabited house; and no doubt they
would have caught at an invitation to share the family meal. Alda
and Wilmet, for different reasons, sat in dread of Felix, in the
reckless hospitality of the male heart, making such an offer; and in
very truth, he was only withheld by certain authoritatively
deprecating glances from those housewifely eyes.
And let it be observed that Wilmet was right. She could not have fed
Mr. Underwood as would have suited him on such short notice,
without a great deal more expense and personal exertion than would
have been becoming; and to his eyes, their ordinary fare would have
seemed ostentation of neediness.
Needy was exactly what the Underwoods had never been. It was not
merely the effect of conscience and of resolution, but of Wilmet's
more than ordinary power of method and adjustment, which had
kept them from ever being behindhand, or in difficulties requiring
external aid; and it was this that had won them already respect that
hardly belonged to their years.
Thomas Underwood really respected Felix, as one who had never
asked assistance from him, yet who had not declined what was
offered in a friendly kinsman-like manner; and besides, had more
than once asserted—modestly indeed, but still asserted—an
independent will and way of his own, and shown that he was
capable of carrying it out. It was five years since Mr. Underwood's
prediction that he would find the attempt keeping house for such a
family an utter failure, and would have to fall back on help he had
not deserved: and here he was, without having made one demand,
a partner in the business, and with so small a fraction of the family
apparent, that there was no air of oppression, no complaint, even
though Thomas himself had returned on his hands both those of
whom he had meant to relieve him.
No wonder, then, that without intending it, his manner to Felix was
not that of patron, but of equal—of kinsman to kinsman, not of rich
man to struggling youth. And Felix, as he sat in the great handsome
dining-room, could not help being amused at all the state that had
followed one man and his daughter for one dinner in their own
house: the courses, and the silver, and the perplexing family of wine-
glasses beside every plate, and all with the Underwood rood and its
motto shining on him—whether on the servant's buttons, on the
panels of the oak-wainscotted hall, and the very china from which he
ate his dinner.
Nothing interested Mr. Underwood more than the account of the visit
to Vale Leston; and warming up under the influence of dinner, he
talked much of the old times there, and with much disparagement of
the two present Fulberts; but Felix was startled to find that he
regarded himself as next in the succession.
'If you could only have gone into the Church, Felix, I could have
given you the Vicarage. Or is not one of your brothers to be a
parson?'
'Yes, Sir—Clement,' said Felix, smiling, but feeling a sense of injury
that revealed to him how much more he must be reckoning on the
chances than he had supposed himself to be doing. As Alda said,
wealth flowed to wealth; and a little attention from Thomas to his
cousins would easily turn the scale.
At any rate, poverty did not suit Alda. She was a different creature
now that her exile was coming to an end.
'It had been like Portsmouth to Fanny Price,' said Geraldine, not
greatly flattered by the overflow of benevolence, which Wilmet
accepted as the token of real affection.
What would she do about Ferdinand? Wilmet ventured to ask.
'He certainly must not call,' said Alda; 'that would never do; but with
Edgar's help it will be manageable enough. It will do the gentleman
no harm to have a few difficulties in his way. I don't want him to feel
his coming such a favour.'
So Alda went; and must it be owned, if there was more peace in the
house, there was also a certain flatness after the incessant
excitements of the former part of the year. At least so Geraldine felt,
and hated herself for feeling, when the numbers had come down to
'the peace establishment,' and she had no companions but Stella
and Theodore through the greater part of the day. She had been
recommended to walk, when the weather permitted, for half an hour
every day; and whenever it was possible, Felix contrived that he or
Lance should be her companion; but as the days shortened, and it
became less easy to contrive this, the constitutional turns up and
down the narrow garden were more dispiriting than sitting occupied
upstairs, especially when she viewed this distaste as frightful
unthankfulness; and even when one of the brothers took her out in
the street, or to the 'People's Park,' though she was happy with
them, the wearisome sameness and dull ugliness of the town
oppressed and wearied her; and to be taken out by Wilmet on a
Saturday was more wearing still. Each brother was her devoted
cavalier; but Wilmet, though kind and considerate, made airing
Cherry a secondary object; and to be set upon a high chair in a
shop, to see Wilmet bargain, was what she did not love. She might
have admired to see Wilmet's perfect knowledge of articles and their
value, and the manifest esteem in which that experience was held
by the respectable tradesmen, who did not scruple to tell her that
they had thought 'this will just suit Miss Underwood;' while her scorn
and indignation at an encounter with a Cheap Jack were something
rich. But though Cherry could describe such an expedition with
humour that threw Felix and Lance into a convulsion of merriment, it
was very wearisome to her; and the more she knew it ought to be
instructive, the more it depressed her, and made her feel, as never
before, the straitness of the family means. She longed wearily at
times for the sight of something beautiful. Edgar's descriptions came
back on her with an almost sick longing. She had made much
progress in drawing, but the want of criticism, instruction, or models,
made her feel baffled; and when her brothers and sisters admired
most, she was most dissatisfied. Edgar's criticism alone was worth
anything to her æsthetic sense, and gave her real assistance; and
his not coming home was a great loss to her art, as well as to her
affection and intellect. Those windows that he opened to her of all
lovely scenes and forms in nature or art, his brilliant stories of artist
society and foreign manners, could not but be greatly missed as she
lived her monotonous life, not without intellectual interest, for that
came to her through the help she was able to render to Felix in his
newspaper work, and the books she reviewed or discussed with him;
but it was not the living interest of actual communication at
secondhand with that outer world, which looked so full of beauty,
and of all that was bright and charming; and then poor little Cherry
applied to herself all the warnings about not loving the world.
Her aspiring compositions and her studies in drawing she almost laid
aside in a fit of hopeless disgust, and she applied herself to what
was less improving, but more immediately profitable. She and Lance
took to the manufacture of Christmas cards, she taking the
sentiment and he the comedy; and what they produced by their joint
efforts were pretty and clever enough to bring in an amount of
pocket-money that was very agreeable to those who otherwise
would have had no claim to any.
The chief outer interest was, as usual, parish affairs. Mr. Bevan was
too ill to come home; but Mr. Mowbray Smith's resignation was
accepted, and he was to go at the beginning of the new year, while
his successor was reported to be elderly and wise.
Another interest, that was not at all bad for Cherry, was stirred up by
her brothers. There was an interminable family belonging to one of
the printers, who died, leaving them in circumstances that somewhat
parodied those of the Underwoods themselves; and in which the
example as well as the counsel of the young master was no doubt a
great incentive and assistance to the pillars of the still humbler
house. There was a perennial supply of 'little Lightfoots,' to fill the
office elegantly termed printer's devil; and the existing imp being
taken young from school, Felix had his education on his conscience,
and asked Cherry to give him lessons after hours. She was at first
desperately afraid of the boy, and only accepted the work when she
found that if she did not, Felix would impose it on himself; but by-
and-by she became enough interested, and enjoyed enough
devotion from her pupil, to make the time she daily expended upon
him not far from one of the pleasures of her life.
So came on a winter of unusual bitterness; and the holidays filled
the house, bringing Bernard back under an entirely new phase. At
Stoneborough he had discovered that it was some distinction to be
an Underwood of Vale Leston, and his accession of dignity was
enormous. He regarded the Nareses from a monstrous elevation;
and thus infinitely scandalized Angela, who had a great hatred of
pretension, and whose laughter threatened to dissolve their mutual
alliance, offensive and defensive. Their janglings were a novelty, and
not a pleasant one; and one bitter afternoon, when a sore throat
had made Felix come up early from the shop, Cherry quite rejoiced
that Bernard was reported to be reading downstairs.
And there sat Felix by the fire, with Theodore at his feet, humming
in rivalry of the big kettle, which had just been brought in, and was
soon followed by Lance, whistling as he came upstairs.
'Look here!' and Angela, who, for her bane at Brompton, had her full
share of the family talent for caricature, showed him a likeness of
Bernard strutting down the High Street, turning his back on certain
figures in the distance; and beneath was written—
'There was a young Bear of Stoneborough,
Who thought his gentility thorough;
To his townsfolk he said,
"Snobs! I'll cut them all dead,"
This high-bred young Bear of Stoneborough.'
'Capital, Angel!' said Lance; 'but don't show it to him; he's a horrid
Bear to poke fun at.'
'Oh, but he does get into such jolly rages!'
'It is beyond being jolly,' said Lance. 'I did this once too often last
holidays; and I don't think he has got over it yet, though I promised
never to do it again.'
'The more reason I should,' said Angela, laughing saucily in his face,
though both spoke under their breath.
'No,' said Lance. 'Consider! He is absurdly stuck up; but anything to
disgust him with the Nareses is good.'
'I see no harm in Jem Nares,' said democratic Angela. 'I'll not have
him cut! give me my picture.'
'No, I promised he should not be done again.'
'Promise for yourself another time.'
She snatched, and there was a sparring match. Lance held off with
one hand, and with the other dashed her drawing into the fire,
where it fell on the top of some black coals; and as he relaxed his
grasp, she sprang to rescue it. Felix looked up in time to see the
kettle toppling over. He flung Theodore out of the way of the boiling
stream that rushed from lid and spout as the whole descended on
the hearth, amid cries from Angela and Theodore that brought all
the others together; nor could the little one be pacified, even though
Wilmet ascertained that he had only been touched by one boiling
drop.
'But Felix!' exclaimed Lance; and they all turned.
'Never mind,' he said, but with more of a contraction of the lips than
a smile; 'only my neck and arm. Here, Lance, help me;' presenting
the end of his sleeve, and setting his teeth.
The hasty vigorous pull, made in ignorance on both sides, removed
the coat; but Felix gave something between a gasp and a cry, tried
to totter to a chair, and was caught by Clement as he fainted away;
so much to the terror of Lance, that in three minutes' space he had
broken in on Mr. Rugg's dinner with a peremptory summons. By the
time he crept into the room behind the doctor, he saw Felix on the
sofa, white as a sheet, with closed eyes and drawn brow, Clement
standing ready with a roll of wadding, and Wilmet, having more
gently removed the shirtsleeve, regarding the injury with some
perplexity, increased by the tearful Sibby's voluble counsels.
She welcomed the arrival with the anxious inquiry, 'O Mr. Rugg! I am
so glad! Should the cotton touch where the skin is broken?—Here—
inside his elbow and hand.'
'Broken! You have been tearing off the clothes, instead of cutting
them! I thought you knew better, Miss Underwood.'
'It was my own doing,' murmured Felix, so faintly, that Mr. Rugg,
with his usual roughness, scolded at his not having had some brandy
at once, and then at there being none nearer than the Fortinbras
Arms, whence Clement brought some in about the time that a grand
butler would have taken to produce it. Felix choked at it like a child,
but it brought back his strength; and Wilmet and Clement were
assistants too handy to give much occasion for scolding. The
shoulder and chest had suffered likewise, though partly protected by
the flannel shirt.
On the patient asking how soon he might hope for the use of his
arm, the gruff answer was, 'Not so soon as if you had not begun by
tearing it to pieces. I can't tell. Depends on general health. May be
three weeks, may be six, may be three months, before you get these
places healed, if you trifle with them. Now I'll stay and see you in
bed, with this arm properly settled.'
This was real kindness for a man in the middle of his dinner; and
Felix stood up, finding himself more shaken than he had expected,
and commanded by acclamation to betake himself to Mr. Froggatt's
bedroom. He chose, however, first to go into the next room, where
Cherry had sunk down, trembling and overcome, and so hysterical
that her utmost powers had been taxed to prevent herself from
disturbing those who could be useful.
'Here I am, all alive!' he said in a cheerful tone, that somehow had
no solidity in it, and which she could hardly bear. 'Why, Cherry, you
poor little thing! you have come by the worst of it!'
'Don't, Felix! Isn't it dreadful pain?'
'Not now; I scarcely feel it. Never mind, Cherry; I'm all right now,
only you will have to write those little fingers nearly off.'
'Oh! Felix, if Wilmet had been gone!'
'She wouldn't be looking Gorgons at me now. Where's Angel?'
Angel had been seized by Robina, and forcibly withheld from flying
out after the doctor; and when assured that Lance was gone, she
had dashed upstairs, and hidden herself in bed, so that Felix was
obliged to go to sleep without seeing her. Remonstrate as he would,
he was not allowed to get up the next morning. Mr. Rugg, who came
very early, assured him that the speed of his recovery greatly
depended on perfect stillness at first, and told him that he would feel
the injury if he tried to move; and Wilmet would not do anything but
rejoice that he was compelled to submit to discipline that was so
good for the cold, a much more real subject of anxiety.
'I must not grumble,' he sighed, as the doctor shut the door; 'but I
did not reckon on such a stupid disaster when I got two boys to look
after everything.'
'People will not mind for a few days.'
'I hope not. Tell Lance to send Lamb up to me as soon as he comes
in. And would Clem walk over to Marshlands? or the Froggery will be
in great commotion.'
'Perhaps Robina will go too; and they always like to have her.'
'And Angel? Poor child! I wish she would come.'
'I'll send her. I want you to talk to her. She is such a perplexity.'
'This was no fault of hers!' exclaimed Felix.
'I don't know that. Lance takes it on himself, and says it was just a
squabble; but that is sure to have been her fault.'
'I shall not go into that,' said Felix.
'It does seem a chance of making an impression, if you would try,'
said Wilmet. 'Sibby says she was crying half the night, (you know
she has to sleep in the nursery,) and you might get at her now. I
don't know what to do with her.'
He looked up, astonished at this avowal, from her who had hitherto
queened it so easily.
'Look at this letter,' she proceeded. 'I have been keeping it till you
had time to think about it.'
He sighed, feeling, like many another head of the house, that time
was swept away from home responsibilities, and indeed, that great
girls needed a more experienced guide. The letter was the school
character, speaking most highly of Robina, who had quite
reconquered esteem. If she had not so much of any one talent as
some of the others, she had excellent capacity, and studied in a
business-like way, as one learning a profession; so that she had won
her promotion into the first ranks, among elder girls.
But Angela was one of those who will not or cannot do anything
tolerably except what they like; and she had only two tastes—for
music and fun—except perhaps for churches. She was a puzzle to
every one, by her eagerness for devout observances, and the very
little good they seemed to do her, even by outrageous irreverence
when the spirit of mischief was roused. Teachers detested her, but
she was the idol of half the school. All unclaimed misdeeds were laid
to her share; and in recklessness or generosity, she never troubled
herself to disavow them, even when not her own. She was popularly
believed to learn nothing but music, and even in that to use talent to
save pains; and she had a lead-like affinity to the bottom of her
class, yet in the final examination she had surpassed far more
diligent girls.
Felix read, and puzzled himself, and did not refuse obedience when
Wilmet insisted that he should 'talk to Angela;' though he was only
too well aware that reproof was that paternal duty to which he was
least adequate. First, however, he had time to despatch Robina and
Clement on their mission to his partner, whose winter rheumatics
had set in—to receive young Lamb, laden with a pile of letters and
papers, and lastly, to be cooed over and stroked by Theodore, who
curled himself up at his feet in that perfect serenity that his presence
always infused.
At last Angela came in on tip-toe, looking immensely tall and lank,
with Clement's propensity for longitudinal growth, and the same
infantine smallness of feature, and much less brilliant colouring than
the others; but while his hair was as closely cropped as if he were
just out of a cell, hers was as long and as unmanageable as herself;
and she had moreover the beautiful large-pupilled, darkly-lashed,
mischievous blue eyes that belonged to Edgar, only now their lids
were swollen, and all the colour in her face centred in two great red
patches beneath them—a scarlet garibaldi over a very old brown
skirt, half-way up a long pair of grey legs, seeming to make the
whole object more deplorable.
'You poor Angel!' exclaimed Felix, his heart more than ever melted;
'you look as if you had been crying all night. Why don't you come
and give me a kiss?'
'I'll—I'll do anything you please, Felix, but I had rather not.'
'But I do please! I want you,' said he, holding out his hand; so that
she was forced to come, touch his cheek with her lips, and submit to
a far heartier kiss. 'You are as cold as ice,' he added, trying to
capture the blue, chilly, long, sausage-like fingers, and warm them in
his grasp.
'No, don't! it will only make my chilblains rage. Let me go, now
you've forgiven me for your own comfort.'
'Forgiven you for my own comfort! I don't want to forgive you—'
'Oh—h!' and the eyes disappeared, and the face puckered in
unutterable woe.
'I haven't anything to forgive you, Angel.'
'Oh, that's worse! when I've hurt you so terribly!'
'You didn't; you never meant it. Of course I never blamed you.'
'Then,' said Angel, trying to get away her other hand, 'why did you
send for me to row me, for I don't call that forgiving.'
'I heard you were unhappy.'
'And did you think it would make me any happier to see you lying
there frowning with pain?' broke out Angela, with an angry sob.
'If I frowned, it was not with pain, but because I don't know what to
make of you.'
'I don't want to be made anything of!' she said pettishly. 'Wilmet told
me you wanted to talk to me. I suppose that meant she ordered
you! So now you've done it, let me go.'
'My dear Angel, don't you see that I am just as anxious about you as
Wilmet can be? and when there is plainly something amiss—'
'Oh, it's old Ful and Fen's character of me, then?'
'It is, Angela. Perhaps it does seem taking an unfair advantage of
you to catch you now; but you see I so seldom get a chance of a
talk with any one; and I must do the best I can for you, you poor
little ones, who, I'm afraid, haven't even the faintest recollection of
our father and mother to help you.'
'I remember mamma, but after she was ill,' said Angela, probably
trying not to be softened. 'But I don't think that has much to do with
it. You and Wilmet mind us as much, or more, than most people's
born parents. Yes, Wilmet worrits twice as much as any rational
mother does.'
'That's the very thing, Angel; parents can do the thing without
worrying.'
'No, I didn't say you did,' said Angela; 'you never did till this minute,
and now you are druv to it;' and she regarded him with a certain
fellow-feeling so comical, that she nearly made him laugh, though he
felt sad enough.
'Have I neglected you then, Angel?'
'Oh no; I think you do just as well as most fathers. You keep us all
going,' said Angela, considering; 'and you look after us and set us a
good example, as people say; and isn't that all that fathers have to
do?'
'My poor little sister! you just show that I cannot be really like a
father to you.'
'Would a father do all the scolding?' asked Angela in an odd voice.
'If we still had our own, you would be coming to him to help you,
and telling him freely what it is that makes things go wrong with
you.'
'I'm sure,' answered the girl, 'I'd just as soon tell you, Felix, if I only
knew; but there's only one thing that would do me any good, I
believe.'
'And that?'
'If I could only be a Trappist.'
'A what?'
'A Trappist, or one of those Sepolte nuns, that never see anybody,
and can't talk to their relations. Oh! I wish I was old enough to turn
Roman Catholic! and then wouldn't I go and cut off this horrible hair,
that is the plague and torment of my life, and never be naughty
again!'
'Which do you want to be rid of most—your hair or your relations?'
asked Felix, half diverted, half dismayed and wholly at a loss.
But Angela had passed the boundary of earnest now, and went on
more from the heart. 'If I could but be in a real strict nunnery, it
would be so nice! It would always be church. Oh! if church could but
last always!'
He was more puzzled than ever at the intent yearning look that had
changed the face. 'You could not keep up. It would lose effect,' he
said.
'I don't know. Lots of girls much better than I—Bobbie herself—don't
like long services, and get tired, but I don't. I'm safe then; I'm
happy altogether. I seem to get wings inside—I could go on singing
for ever. I don't want to be bad; but the instant I go out, I can't live
without fun; and so they think me a horrid false hypocrite—but I'm
not! Only unless I get shut up somewhere, I don't know what will
become of me.'
'You must try to make your life out of church suit your life in church,'
said Felix, much puzzled how to answer.
'I would, only I can't be half-and-half, and wishy-washy.'
'I don't understand.'
'Don't you? Why, if I have fun, I like to have it real fun. I can't be
always drawing it mild! It is no real fun if one is to be always
thinking about who will be vexed, and what's lady-like, and all that
stuff!'
'But that's what life in this world is made of.'
'I know it is; so I hate life in this world, unless one could just have
no conscience at all;' then, as she caught his anxious eye, she went
on, trying to rattle, but with tears in her voice, and submitting to let
him warm her hands all the time, 'Felix, you'd better let me go into a
Sisterhood. It is the only chance for me! Thinking about being a
horrid governess makes me wicked. When I'm good I do long for a
Sisterhood; and when I'm bad I want to get some great rich duke to
marry me, and let me have no end of horses, and go to the races
and the opera—and I don't suppose he will ever come. And I
suppose you are all too dull and tiresome to let me get to be a public
singer! No, don't tell me to put it out of my head, for it is what I
should like best—best of all!'
'Better than the duke?'
'Oh yes! for I think he would be in the way—Felix! do let me be a
Sister! You see it is the only chance.'
'I can't, Angel; they would not accept a Sister at your age.'
'Then let me think about it really, Felix. Promise that I may be when
I am old enough.'
'It is impossible to promise that; but I do not think I am likely to
hinder you, if you then wish it, and it seems right.'
'I wish you would promise me. Look here, Felix,' and the eyes
assumed a deep yearning expression; 'I always did think that if I had
a dedication, like Clement, I could be as good as he is. But I don't
think anything else would put the duke or the opera out of my head.'
'My dear Angel,' and Felix's eyes grew soft too, 'I could not wish
anything better for you than to be such another as Sister Constance,
but I do not know how you could be dedicated. Even Clement is not;
he could change his mind before he is three-and-twenty. It all
depends on how he goes on.'
'And if I go on well, will you let me look to it?'
'As far as may be right.'
'Only then what is the use of my going to this school, if I am not to
turn governess? It only makes me worse.'
'No, Angela. It would not be right to stop your education. You must
have the means of maintaining yourself. It would be against my duty
to hinder that. And remember—some Sisterhoods require an
endowment. You would not wish to be a burthen. You may have to
work to raise means for admission; and if you are set to teach, you
will need all you are learning now.'
'May I think I am preparing?'
'Yes.'
'I will, I will—I mean, I will try,' said Angela. 'O Felix! I do like you
now I find you don't want me to be respectable. No, don't say
something grave and prosy, for I do like you now; and never mind
about not being one's father, for I don't believe anybody could be
better to me.' And she put her face down to his and kissed him as
she used when she was a baby girl; then ran away on thinking she
heard some one coming.
'So,' thought Felix, as he raised himself on his sound elbow, 'the
upshot of it is that I don't want her to be respectable! I hope to
goodness she won't take to being like Tina—though I don't know
why I should either! Poor child! I'll write to Audley about her when I
can. And here comes the dear little Cherry for her hard day's work.'
With his dictation and superintendence, Geraldine was quite equal to
the Pursuivant's Friday requirements; and altogether this day of rest
and leisure was welcome. The sisters were much less anxious about
the sore throat than if it had been in the shop! and indeed it was
nearly well, and no obstacle to his being talked to and amused, to
the general enjoyment, in the rare pleasure of having him at their
mercy. In the afternoon came a message—'The Miss Pearsons' love,
and if she could leave Mr. Underwood, would Miss Underwood step
up?' Such messages were not infrequent, and this was supposed to
spring from a desire to know the particulars of the accident; so that
on her return Wilmet was greeted with the inquiry whether she was
considered responsible for the tea-kettle's misbehaviour, since she
had been kept in so long.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like