Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (8 votes)
18 views

Instant download (Ebook) Mastering Linux shell scripting a practical guide to Linux command- line, Bash scripting, and Shell programming by Mokhtar Ebrahim; Andrew Mallett ISBN 9781788990158, 1788990153 pdf all chapter

The document provides information about the ebook 'Mastering Linux Shell Scripting' by Mokhtar Ebrahim and Andrew Mallett, detailing its content, authors, and various editions available for download. It covers topics related to Linux command-line, Bash scripting, and shell programming, along with technical requirements and practical applications. Additionally, it includes acknowledgments, a table of contents, and promotional information about related ebooks and resources.

Uploaded by

papasinobreb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (8 votes)
18 views

Instant download (Ebook) Mastering Linux shell scripting a practical guide to Linux command- line, Bash scripting, and Shell programming by Mokhtar Ebrahim; Andrew Mallett ISBN 9781788990158, 1788990153 pdf all chapter

The document provides information about the ebook 'Mastering Linux Shell Scripting' by Mokhtar Ebrahim and Andrew Mallett, detailing its content, authors, and various editions available for download. It covers topics related to Linux command-line, Bash scripting, and shell programming, along with technical requirements and practical applications. Additionally, it includes acknowledgments, a table of contents, and promotional information about related ebooks and resources.

Uploaded by

papasinobreb
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Mastering Linux shell scripting a


practical guide to Linux command- line, Bash
scripting, and Shell programming by Mokhtar
Ebrahim; Andrew Mallett ISBN 9781788990158,
1788990153
https://ebooknice.com/product/mastering-linux-shell-
scripting-a-practical-guide-to-linux-command-line-bash-
scripting-and-shell-programming-11145962

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Mastering Linux Shell Scripting: a practical guide


to Linux command-line, Bash scripting, and Shell
programming by Ebrahim, Mokhtar;Mallett, Andrew ISBN
9781788990158, 9781788990554, 1788990153, 1788990552
https://ebooknice.com/product/mastering-linux-shell-scripting-a-
practical-guide-to-linux-command-line-bash-scripting-and-shell-
programming-11381866
ebooknice.com

(Ebook) Mastering Linux Shell Scripting Second Edition by


Mokhtar Ebrahim, Andrew Mallett ISBN 9781788990554,
1788990552
https://ebooknice.com/product/mastering-linux-shell-scripting-second-
edition-38624096

ebooknice.com

(Ebook) Mastering Linux Shell Scripting, Second Edition by


Mokhtar Ebrahim, Andrew Mallett ISBN 9781788990554,
1788990552
https://ebooknice.com/product/mastering-linux-shell-scripting-second-
edition-42970140

ebooknice.com

(Ebook) Mastering Linux Shell Scripting, Second Edition by


Mokhtar Ebrahim, Andrew Mallett ISBN 9781788990554,
1788990552
https://ebooknice.com/product/mastering-linux-shell-scripting-second-
edition-42970142

ebooknice.com
(Ebook) Linux : introduce to beginners guide + UNIX
operating system + Linux shell scripting and command line
+ Linux System by Erickson Karnel & CODING HOOD ISBN
B0B2HP36XR
https://ebooknice.com/product/linux-introduce-to-beginners-guide-unix-
operating-system-linux-shell-scripting-and-command-line-linux-
system-43317364
ebooknice.com

(Ebook) Linux Command Line and Shell Scripting Bible by


Richard Blum, Christine Bresnahan ISBN 9781118983843,
111898384X
https://ebooknice.com/product/linux-command-line-and-shell-scripting-
bible-9995626

ebooknice.com

(Ebook) Pro Bash Programming: Scripting the GNU/Linux


Shell by Chris Johnson ISBN 9781430219972, 1430219971

https://ebooknice.com/product/pro-bash-programming-scripting-the-gnu-
linux-shell-1365422

ebooknice.com

(Ebook) Linux Command Line and Shell Scripting Bible, 2nd


Edition by Richard Blum, Christine Bresnahan ISBN
9781118004425, 1118004426
https://ebooknice.com/product/linux-command-line-and-shell-scripting-
bible-2nd-edition-5474284

ebooknice.com

(Ebook) Pro bash programming: scripting the GNU/Linux


shell by Johnson, Chris;Varma, Jayant ISBN 9781484201213,
9781484201220, 1484201213, 1484201221
https://ebooknice.com/product/pro-bash-programming-scripting-the-gnu-
linux-shell-11730824

ebooknice.com
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 ]
Exploring the Variety of Random
Documents with Different Content
carried back a long way to Boston, New York, Philadelphia, and
other parts of the East.
Glass mills form an important part of the city’s industries and
have been in operation for a long time. Bottle glass is manufactured
here, besides three fourths of all the plate glass of the United States.
Perhaps it is because bottles are made in Pittsburg that we find here
also the largest cork factory in the world.
Pittsburg is proud of the fact that she handles more tons of
freight in a year than any other city in the world. Indeed, the tonnage
is greater than that of New York and Chicago taken together.
The old “point” between the rivers is filled with tall buildings.
Inclined railways run up the steep bluffs on the further side of each
river and lead to the beautiful streets and the homes where many of
the people live. For Pittsburg is not all coal and furnaces and smoke,
but has fine churches, the great Carnegie Library and Museum, and
many schools. But it is mostly because of the coal and the rivers that
we find here a splendid city.
Sixty-three miles down the Ohio river, on its left bank, is
Wheeling, the largest city in West Virginia. The business streets lie
close to the Ohio, and the houses extend up the steep slope to the
east, while over a high ridge comes the old National Road from the
valley of Wheeling creek. Wheeling was the goal of many heavily
laden wagons in the days of the pike, and because of the river and
many railroads has a large trade to-day. It was settled in 1770 and is
one of the oldest towns on the river.
On the north bank of the great stream, in the southwest corner of
Ohio, is the largest city on the river. As late as 1900 Cincinnati had a
few thousand more people than Pittsburg, but a “greater Cincinnati”
would not be so large as a “greater Pittsburg.”
In Cincinnati, as in Pittsburg, men do business on the low
grounds by the river, where offices and mills and shops crowd one
another, and the smoke of soft coal hangs as a cloud above.
Business hours over, the well-to-do merchants climb out of the grimy
town to the top of the bluffs, and there find, in a clearer air and along
open and beautiful avenues, their comfortable homes. Down town
the turbulent river sometimes comes up forty or fifty feet beyond its
usual level and makes trouble in the busy city, but Mt. Auburn and
Walnut Hills are disturbed neither by smoke nor by floods.
Rivers do not often flow in straight lines, and it is very common
for them to change their courses along their flood plains. This habit
of shifting belongs alike to great and small streams, whether the
Mississippi or the brook in the meadow. The Ohio, like other rivers,
often writes the letter S, and in so doing at this point has swung off
from its old north bank, leaving a low plain with room enough for a
hundred thousand people to carry on their business. There is always
some good reason which has led to the settlement and growth of a
town, and the history of Cincinnati shows no exception.
It was in early winter, 1788, when cakes of ice were already
floating on the river, that a number of men sailing downstream
stopped here and began a settlement. The place was not readily
named. It is said that the matter was left to a frontier schoolmaster,
and he did not lose the chance to show how much he knew. He saw
that the Licking river comes into the Ohio on the Kentucky side just
opposite. So he set down an L. He next remembered an ancient
word os, meaning “mouth,” and he put that down. Then he
considered that anti means “opposite” and that ville means “town.”
So he wrote the whole name,—L-os-anti-ville,—Losantiville,—“the
town opposite the mouth of Licking.”
We might wonder whether a town with a name like that would
ever grow into a great city. It did not have to try, for it was not long
before General St. Clair, who had come there, made fun of the name
and insisted upon a new one. He and other officers of the American
army had formed a society commemorating their experience in the
Revolution, and in honor of the Roman patriot Cincinnatus had called
themselves the Order of Cincinnati. St. Clair thought this a good
name for the town, and Cincinnati it has been since that time.
The place has its nickname also, and its people like to call it the
Queen City, which seems to go very well with Beautiful River.
Another name, rarely used and not very pleasing, perhaps, to those
who live there, is “Porkopolis,” which came from the fact that for forty
years before the American Civil War more pork packing was done in
Cincinnati than anywhere else in the country.

Fig. 49. River Front, Cincinnati


Sir Charles Lyell, an Englishman who saw Cincinnati in 1842,
speaks of the “pork aristocracy,” explaining that he means the men
that had grown rich by packing pork, and not the pigs that he saw
running in the streets. This shows how new some of our large
business centers are, though it would be a great mistake to suppose
that pigs and cows now run loose in western cities. In those days
such places were teaching the country how to “pack fifteen bushels
of corn into a pig,” and how to send the produce of the farms to
distant cities or other lands in such a way as to get the most money
for the least freight.
When Charles Dickens visited this country many years ago he
went to Cincinnati, and spoke well of the place. This was a great
compliment, for the famous English story-teller was hard to suit when
he was looking at anything American. If he could come back to
Cincinnati now, he might find even more to please and surprise him.
Cincinnati has always made much use of the river. There were
little boats in which the owners carried notions and such things as a
country store sells, peddling them from one settlement to another
along the banks. There were barges and flatboats bearing families
and farm produce. Then came steamboats, which carried everything,
—passengers, grain, coal, merchandise, and even circuses and
menageries. We can imagine the excitement among the small boys
of a river town when the circus boat told of its arrival by the fierce
blast of a loud steam whistle. There are steamboats yet and a busy
river front, but great railroads center here, and trains run to Pittsburg
and Philadelphia, Cleveland and New York, Chicago and St. Louis,
Nashville and New Orleans. A vast business is done. There are
many schools, and to-day Cincinnati can boast of her music, of her
pictures and museums, and of the fine pottery that she makes. She
has thrown off the schoolmaster’s clumsy name, she has many
better things than pork, and she is widely known as one of America’s
great cities.
An early writer says that the Ohio is “by far the noblest river in
the universe.” He writes this in the beginning of a history of
Louisville, a book which was printed in 1819. This in itself shows that
Louisville is one of the old cities of the Ohio valley. It is not so large
as Cincinnati or Pittsburg, but it is the chief city of the great state of
Kentucky.
The old boatmen, finding that the current was rapid at a certain
point, called it the “falls of the Ohio.” A ledge of hard rocks in the bed
of the river caused the rapids and made it no easy task to navigate
boats. Finally a canal was dug by which the rapids might be avoided
at low water.
It was this ledge in the river that started the town and finally
made a city out of Louisville, for boats going in either direction
naturally stopped at the falls. There was another reason, too, as we
shall see when we learn something of the “Wilderness Road,” which
crossed Kentucky from the eastern mountains and came out on the
river at Louisville. Back from the river also lay the rich and fertile
Blue Grass country for which Kentucky is famous.
The canal was ready to take steamboats around the ledge in
1831. Some of these boats had interesting names, such as the
Enterprise, the Vesuvius, the Comet, the Volcano, the New Orleans,
the Cincinnati, the Experiment, the Rifleman, and the Rising States.
It was a wonderful life on the river, and Louisville got her share of
the gain of it, as she now shares the traffic of the railroads. To-day
she is a rich and beautiful city of two hundred thousand people.
CHAPTER XI
THE GREAT VALLEY

Alexander Spotswood was a famous governor of the colony of


Virginia. He was of Scottish parentage, but he was born in Morocco,
where his father was a surgeon. The lad grew up to serve his
country as a soldier, and was wounded by a cannon ball in a great
war then going on in Europe. In 1710 the king sent him to Virginia to
be governor, an office which he filled for twelve years. The people
liked him, though he made some enemies because he kept his
soldierly ways and did not always speak in gentle phrases. He was a
kind, warm-hearted man, nevertheless, loving his family and friends.
His energy, too, was well known, and he was always ready to further
a new scheme.
Because he started the first iron furnaces in America he was
called the “Tubal Cain of Virginia,” Tubal Cain being known in sacred
history as the first of metal workers. Nothing was more important to
the colonists than iron, for they could not always bring tools and
kettles and nails and gun metal from England. The governor showed
his practical ability in other ways. He brought over Germans who
knew how to raise grapes and make wine. He was interested in
teaching the Indians, and at one time he sent out ships and caught
“Blackbeard,” who, with his fellow-pirates, was prowling about the
coast. When the young Benjamin Franklin, in Boston, heard of the
capture he wrote a poem about it.
In that day nearly all of Virginia was in the “tide-water country,”
but Spotswood had often heard of the valley beyond the Blue Ridge.
He made up his mind to go and see this region, and brought together
a party to make the journey. They took their servants and pack
horses and carried provisions and many bottles of the wine which
the Germans had made. There was good hunting in the unbroken
forest and they had all the venison and other wild meat they could
have wished.
A good map of Virginia will show us Harpers Ferry, where the
Potomac river runs through a deep gap in the Blue Ridge. Looking
along the range to the southwest, we shall find, about eighty miles
away, Swift Run Gap, not so low a pass, but one which made it easy
to cross the mountains and go down into the lowlands along the
Shenandoah river.
Spotswood and his friends climbed one of the peaks of the Blue
Ridge and named it Mt. George, after the king. Another peak was
named Alexander for the governor. Down by the Shenandoah they
buried a bottle (the historian of Virginia thinks that by this time they
must have had several that were empty), and in the bottle was a
paper stating that they took possession in the name of the king. They
called the river the Euphrates, but the name did not cling to it. We
may be glad of that, for the Indian name of Shenandoah is much
more musical.
Fig. 50. Luray, Shenandoah Valley
If Spotswood had crossed the lowlands, he would have found
himself among other mountains running parallel to the Blue Ridge.
Between the two ranges is the valley of the Shenandoah, or, as it is
quite as often called, the valley of Virginia. The land is flat and the
soil deep and rich. The soft shales and limestone of ancient higher
lands have wasted away here, between the higher mountains on
either side, and thus we find a valley and a fertile valley floor.
The place was wild and lonely when this band of explorers
visited it, but to-day it is a country rich in interest and associations. If
we go northeast we shall pass Winchester, which became famous in
the Civil War. In another part of the valley is Luray, where the
limestones have been dissolved under the ground, making a large
cavern with beautiful stalactites. Still going northward, we shall pass
Harpers Ferry on our right and cross the Potomac. On our right also,
after we cross the river, is Antietam, where a severe battle was
fought between Lee and McClellan. A little farther on is Hagerstown,
Colonel Rochester’s old home, in the state of Maryland.
The next move would take us over into Pennsylvania, through
Chambersburg and Carlisle, about which we already know, and
across the Susquehanna to Harrisburg. On our right, as we go up
into Pennsylvania, is the low South mountain, which is the Blue
Ridge continued. All this time we are in the Great Valley. The valley
of Virginia is but a part of the whole, which reaches through several
states and everywhere has the Blue Ridge on the southeast and
other ridges of the Appalachian mountains on the northwest. Every
part of the valley is thickly settled and has fine houses and homes,
because its soil produces good crops and makes the people
prosperous.

Southern Appalachian Region


Spotswood’s journey opened the way for families from the tide-
water region to settle beyond the mountains, but they were not the
only settlers. It was easy for the people of the Great Valley in
Pennsylvania, where the land was earlier taken up, to push to the
southwest along the same valley. They found smoother traveling and
better farms than if they had gone up into the mountains on the west.
So we see that the valley, leading southwest, guided the stream of
emigrants in that direction. The result was that the valley of Virginia
was occupied partly by people entering through Pennsylvania, and
partly by those who, like Spotswood, came through passes in the
Blue Ridge. It was thirty years later, when most of the land was still a
wilderness, that we find George Washington crossing these same
mountains to survey for Lord Fairfax. His path lay between Harpers
Ferry and Swift Run Gap.
In this valley, during the Civil War, “Stonewall” Jackson,
Sheridan, and other well-known generals took their armies up and
down, and fought a number of battles. The rich farms and full barns
of the valley played no small part in the strife by furnishing food for
the soldiers.
The headwaters of the James river are in the Great Valley. One
branch flows southwest and another northeast. These come together
and go out to the southeast by a gap in the Blue Ridge. To-day we
come up the Shenandoah by the Norfolk and Western Railway,
which continues along these branches of the James. Before long we
reach Roanoke, a flourishing city just inside the Blue Ridge. Then
follows the crossing of the New river, which flows northwest across
the valley on its long course to the Ohio.

Fig. 51. James River Gap in the


Blue Ridge, from the West

Now we are looking toward Tennessee, and the Great Valley


soon takes us to several long streams which help to form the
Tennessee river. The heads of these streams we shall find in
Virginia, and their names are the Holston, the Clinch, and Powell’s
river. The Great Valley in this southwestern part of Virginia is really
divided into several valleys by long and rather high ridges that
separate these rivers.
The main line of the Southern Railway, between Washington and
Knoxville, runs along the valley of the Holston river and crosses from
Virginia into Tennessee at Bristol.
After we come into Tennessee the ridges that separate the
streams fall away again, and we find one great valley, about forty
miles wide. On the northwest the Cumberland plateau and the
Cumberland mountains rise above it. On the southeast there loom
up the Great Smoky mountains on the border of North Carolina.
Great Smoky is only another name for the Blue Ridge, for it is the
same range, only higher and wider than it is farther north.
Although this valley is a part of the Great Valley, it is commonly
called the valley of east Tennessee, its people using the home name
as they do in Virginia. The Holston, the Clinch, and Powell’s river are
not the only branches of the Tennessee. Out of the Great Smoky
mountains there flow from the east the French Broad, the Little
Tennessee, and the Hiwassee. Knoxville stands a little below the
place where the Holston and French Broad flow together, and
Chattanooga is a hundred miles farther down, where the Tennessee,
now a lordly stream, leaves the Great Valley and flows westward
through a deep valley in the Cumberland plateau. This lesson in
geography we must learn well, with the help of a map, and we shall
then see what the pioneers did as they followed the rivers between
the mountains.
It is an old road that runs from Pennsylvania to Tennessee by the
valley. It took the pioneer across the Potomac through Winchester
and Staunton in Virginia. Farther on was a fortified place, Fort
Chissel, built in 1758, which was on the way to the Watauga
Settlement and Cumberland Gap. Of Watauga we must now tell, and
of the Cumberland Gap in the next chapter.
Watauga is the name of a small river which flows out of the
mountains on the east, into the Great Valley, and enters the Holston.
In a pleasant spot on the banks of this stream the first settlement of
white men in Tennessee was made. Some of the people had come
along the valley from Pennsylvania and Virginia, and others had
climbed over the mountains from North Carolina because of the
wrongs they had suffered there.
Many of these men and women had come from the north of
Ireland. They were not of Irish but of Scotch blood, their ancestors
having originally come from Scotland to make the north of Ireland
their home. For this reason they are often called Scotch-Irish, but
whatever we name them, we are to remember that they were sturdy
and intelligent people. Conscientious and loyal Presbyterians they
were in faith, and by nature brave and full of endurance. Their
fathers had shed their blood for freedom on Scottish fields, and the
sons were not likely to be frightened by a wilderness full of red
savages.

Fig. 52. Hilly Farm Lands in the Great Valley, near Knoxville
Besides the Scotch-Irish, there were many Germans who had
followed the valley from Pennsylvania, and there were Huguenots
also, besides a few Hollanders and Swedes. A fort was built on the
little river, and around this defense grew up the Watauga Settlement.
There was no Tennessee in those days.
Many of the settlers had followed down the valleys from earlier
homes in Virginia, and it never occurred to them that they were not
still living in Virginia, and able to call on the colony for help. But after
a time a man came to the settlement who was a surveyor, and for
some reason he thought that he would run the boundary line of
Virginia farther west. When he had done it, what was the surprise of
every one to find that they were not in Virginia at all! If they belonged
to any colony, it was to North Carolina. Unfortunately there was a
lack of good government in that colony, and the prospect of
belonging to it was not a pleasant one; indeed, some of the settlers
had run away from North Carolina, and had felt safer because the
great mountains rose between them and their former home.
There seemed nothing to do but to make a government of their
own, so they formed the Watauga Association, about which writers of
American history have said a good deal. It would be interesting to
see a copy of the constitution that was drawn up by these
backwoodsmen, but it has been lost, with little hope that it will ever
be recovered. It is known, however, that there was a committee of
thirteen, really a legislature. This committee chose five of their own
number to form a court, which had a clerk and a sheriff and made
laws for all the settlers. Roosevelt, in his Winning of the West, says
that these pioneers were the first to build a “free and independent
community” in America.
The two most important men of this little state in the wild forest
show us that the settlers came from widely different places. James
Robertson was one, and he came over the mountains from North
Carolina. John Sevier was the other, and he came down the valley
from Virginia. We shall need to know what sort of men these were.
James Robertson belonged to the Scotch-Irish people. He was
not one of the very first settlers at Watauga, but came in the second
year, 1770. He had no early education, and his wife, an intelligent
woman, taught him to read. He went alone over the mountains, with
only his horse and gun, in search of a place for a home. He found
the settlers and admired the place which they had chosen, but on his
way back in the fall he lost his horse and got his powder wet. He
wandered about, almost starved, until he met some hunters, who
helped him home. He told his neighbors of the lands in the valley,
and as soon as the winter was over his own family and sixteen
others started out for Watauga. He built a log house, went to work on
the land, and by his wisdom and energy soon came to be a leader of
the new colony.
John Sevier did not come until 1772. His father had been a
settler in the Shenandoah valley, and John followed the streams, as
we have traced them, to the Great Valley. He was by birth a
gentleman, using that word to mean a man born of cultivated parents
and familiar with the world. He was well educated and was
acquainted with prominent men, such as Franklin and Madison. Both
he and Robertson were good fighters, as we shall see.
It was not long before seven hundred Indian warriors, angry
because the white people had made homes on their hunting
grounds, stole in upon the settlement. An Indian woman, Nancy
Ward by name, who felt kindly toward the whites, secretly warned
them of the attack, so that when the savages came they found all the
men, women, and children in the fort. It was not much of a fort, but it
saved their lives. The Indians kept up the attack for six days, but the
colonists, led by Sevier and Robertson, held out against them and
killed a number of their braves. When nearly a week had passed the
red men, tired of the siege, went off through the forest.
Fig. 53. From the Pinnacle, Cumberland Gap, looking
Northeast along the Cumberland Mountains. The
Great Valley at the Right

At one time, when some lawless whites had killed an Indian


without reason, the members of the tribe were very angry and
threatened to avenge the murder. Robertson, thinking that he could
soften their anger, went alone among the fierce Cherokees. He told
them that the Watauga people were very sorry the man had been
killed, and that they would try to find and punish the murderer. As the
Indians believed Robertson to be an honest man, they did as he
asked them to do and the settlers were not disturbed.
The Watauga colonists had to live in a very rough and simple
way. They built their cabins of logs, with what were called puncheon
floors,—that is, floors made of thick, rude slabs. Frequently a big
slab served for a table, three-legged stools for chairs, and a row of
pegs for a wardrobe. Roosevelt says that the dress of the men was
largely copied from that of the Indians, and included a fur cap,
leggings of buckskin or elk hide, and a fringed hunting shirt. A heavy
rifle was carried, which was usually fired from a rest.
Garments and bed clothing were made of wool, which was spun
at home by the wives and daughters. The women worked hard from
morning till night, and the men had many things to do. There were
lands to be cleared, crops to be raised, and game to be hunted and
dressed. Besides all these occupations it was necessary to keep a
constant lookout for hostile savages and to have all means of
defense ready in case of a sudden attack. The Indians were so crafty
and deceitful that only the closest watchfulness saved the palefaces
from danger and death. Sometimes an unwary hunter, hearing the
gobbling of a turkey or the call of an owl, would come out into an
open place only to be laid low by the red man’s bullet. These
experiences developed a strong and brave people.
The settlers often bartered things because they had no money,
and they were ignorant of many of the ways of civilized life. Some of
the frontiersmen did not know that tea leaves should be steeped and
used for a drink, and tried to eat them with butter or salt.
When a boy was twelve years old he had to begin to take a
man’s part. A gun was given to him, and he was placed at a loophole
in the fort to help keep off the savage foe. Thus the boys grew up to
be real men, knowing little fear, able to take care of themselves, and
helping to build one of the great states of the American Union.
CHAPTER XII
TO KENTUCKY BY THE CUMBERLAND GAP

Dr. Thomas Walker was a man of Virginia. He had attended


William and Mary College, and was well educated for his times. As
the agent of a land company which had a grant of new lands in
Kentucky, he, with several companions, made a hard journey of six
months into the wilderness. They started at Charlottesville in
Virginia, went through the Blue Ridge into the Great Valley, and then
followed the valley southwest. One of Walker’s companions bore the
name of Ambrose Powell, and as they followed one of the long
streams that flow to the southwest to form the Tennessee, they
named it Powell’s river. His son afterwards was an officer in the
Revolution, and it is said that A. P. Hill, a well-known Confederate
general in the Civil War, was his great-grandson.
These were, in fact, no common men who, in the year 1750,
ventured out into the forest, over the roughest trails we can imagine,
among wild animals and savage men. Following down Powell’s river,
the travelers saw rugged mountains on their right, the Cumberland
range. As they wished to explore the forests of Kentucky, they were
looking for a chance to pass the mountains, and by and by they
came in sight of a deep notch, cut at least a thousand feet below the
top of the mountain ridge (Fig. 54).
Fig. 54. Cumberland Gap from the East
They turned aside to this and followed it out of the Great Valley.
They had to climb up about five hundred feet through a wooded
ravine in order to reach the top of the pass, and there was a similar
slope on the other side. This brought them to an open valley and to a
river, which they followed through a gap in another mountain range,
the Pineville mountains.
Dr. Walker called the first pass the Cumberland Gap, in honor of
a well-known Englishman, and the name has survived even to the
present day. In like manner we have the Cumberland mountains.
Walker did not go far enough west to find the beautiful Kentucky
lands on the Ohio river. After wandering about in the high, rough
country of eastern Kentucky, he finally reached his Virginia home
without having accomplished much in the service of his company.
But he had found and named what has become one of the most
famous historical places in America, the Cumberland Gap. He was
not the first man to go through it, for the Indians had long been
familiar with it. Their trail had traversed it for no one knows how
many generations. Not only did it lead directly to the open, fertile
country west of the mountains, but beyond it the warrior’s trail
stretched northward through the woods to the Ohio river.
The Watauga Settlement was about fifty miles eastward from the
Cumberland Gap. As the hardy pioneers did not make much of
following a forest trail for fifty miles, the Watauga colony was next
door to Kentucky, and the great gap in the Cumberland mountains
was only a step farther on, either for them or for travelers to the West
who might choose this route.
We must now follow the fortunes of the most famous of Kentucky
hunters and pioneers, who, while he did not find or name the
Cumberland Gap, often went through it, and is remembered by most
people in connection with it. This man was Daniel Boone.
We could not find a better example of the movement along the
Great Valley to the southwest than the life of Boone; for his
childhood was spent on what was then the frontier, and his
experience was like that of hundreds of others similarly reared.

Fig. 55. Daniel Boone


Boone was born near the Schuylkill river in Pennsylvania in
1734, two years after the birth of Washington. This part of
Pennsylvania was still on the edge of the wilderness, and from his
early boyhood Boone knew all about the Indians. His family were
Quakers, and he himself was quiet and thoughtful, learning to read
from the Quaker wife of his eldest brother, but getting most of his
education in the fields and woods. Though he could read, he spelled
almost as badly as did Nicholas Herkimer. Boone had some
experience as a blacksmith, which, his biographer says, taught him
how to mend his traps and guns. He used to hunt in the woods in
winter, helping thus to feed the family, and with the skins which he
took to Philadelphia he bought powder, lead, and hunting knives.
When Boone was about sixteen years old his family decided to
move. They went along the Great Valley, as many were doing in
those days, crossed the Potomac, and traveled far through the valley
of Virginia. Then they turned east, crossed the Blue Ridge, and
made a home in the valley of the Yadkin river in North Carolina. They
were thus east of the mountains, and across, to the west, was the
Watauga Settlement.
While his home was in North Carolina Boone had an experience
which helped him to be a rugged pioneer, for he went up to Virginia
and across the mountains with General Braddock, serving as
wagoner and blacksmith. He found himself in dangerous quarters in
the battle, where many of the teamsters were shot, but he managed
to cut his horses loose, mounted one of them, and escaped.
On this expedition he made friends with John Finley, and
together they planned to go at some future time to Kentucky by the
Cumberland Gap and enjoy the fine hunting in the forests of the
West. Finley had already made a journey down to the falls of the
Ohio river.
At home Boone lived, like all others in those valleys, in a small
log cabin chinked with clay and warmed by a large fireplace, in
which, says his biographer, “the young wife (for Boone was now
married) cooked simple meals of corn mush, pumpkins, squashes,
beans, potatoes, and pork, or wild meat of many kinds.”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like