0% found this document useful (0 votes)
21 views76 pages

Mastering Linux Shell Scripting Second Edition 2nd Edition Mokhtar Ebrahim PDF Download

The document is about the book 'Mastering Linux Shell Scripting, Second Edition' by Mokhtar Ebrahim and Andrew Mallett, which covers various aspects of Bash scripting and shell programming. It includes detailed content on creating interactive scripts, using conditions, functions, and regular expressions, among other topics. The book is published by Packt Publishing and aims to help readers master Linux shell scripting for practical applications.

Uploaded by

jeroobryton
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
0% found this document useful (0 votes)
21 views76 pages

Mastering Linux Shell Scripting Second Edition 2nd Edition Mokhtar Ebrahim PDF Download

The document is about the book 'Mastering Linux Shell Scripting, Second Edition' by Mokhtar Ebrahim and Andrew Mallett, which covers various aspects of Bash scripting and shell programming. It includes detailed content on creating interactive scripts, using conditions, functions, and regular expressions, among other topics. The book is published by Packt Publishing and aims to help readers master Linux shell scripting for practical applications.

Uploaded by

jeroobryton
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

Mastering Linux Shell Scripting Second Edition

2nd Edition Mokhtar Ebrahim download

[Link]
second-edition-2nd-edition-mokhtar-ebrahim-38624096

Explore and download more ebooks at [Link]


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

Mastering Linux Shell Scripting A Practical Guide To Linux Command


Line Bash Scripting And Shell Programming Second Edition Mokhtar
Ebrahim Andrew Mallett

[Link]
practical-guide-to-linux-command-line-bash-scripting-and-shell-
programming-second-edition-mokhtar-ebrahim-andrew-mallett-11145962

Mastering Linux Shell Scripting Master The Complexities Of Bash Shell


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

[Link]
the-complexities-of-bash-shell-scripting-and-unlock-the-power-of-
shell-for-your-enterprise-andrew-mallett-5470908

Mastering Linux Shell Scripting Andrew Mallett

[Link]
mallett-96341792

Mastering Linux Shell Scripting Andrew Mallett Mokhtar Ebrahim

[Link]
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

[Link]
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

[Link]
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

[Link]
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

[Link]
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

[Link]
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

[Link]
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 [Link] 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/[Link]

[ 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/[Link]

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:
$ [Link]
$ 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 [Link] #To determine the type and path
$ type -a [Link] #To print all commands found if the name is NOT unique
$ type -t [Link] ~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:
$ [Link] 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/[Link] $HOME/bin/[Link]
$ chmod +x $HOME/bin/[Link]

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:
$ [Link] 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:


$ [Link] 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/[Link] 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/[Link] 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/[Link] $HOME/bin/[Link]
$ chmod +x $HOME/bin/[Link]

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 ]
Another Random Scribd Document
with Unrelated Content
The Project Gutenberg eBook of L'Illustration,
No. 0054, 9 Mars 1844
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 [Link]. 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: L'Illustration, No. 0054, 9 Mars 1844

Author: Various

Release date: September 28, 2013 [eBook #43839]


Most recently updated: October 23, 2024

Language: French

Credits: Produced by Rénald Lévesque

*** START OF THE PROJECT GUTENBERG EBOOK L'ILLUSTRATION, NO.


0054, 9 MARS 1844 ***
Ab. pour Paris.--3 mois, 8 fr.--6 mois, 16 fr.--Un an, 30
fr.
Prix de chaque No. 75 c.--La collection mensuelle br., 2
fr. 75.

Ab. pour les Dép.--3 mois, 9 fr.--6 mois, 17 fr.--Un an,


32 fr.
pour l'Étranger. -- 10 -- 20 --
40

Nº 54. Vol. III.--SAMEDI 9 MARS 1844.


Bureaux, rue de Seine, 33.
Sommaire.
Courrier de Paris. Vue du Pont de Beaucaire, emporté par un coup de
vent; Perte du navire l'Elberfeldt.--Fragments d'un Voyage en
Afrique. (Suite et fin.)--Paris souterrain. (2e art.) Plan indicatif de
l'Entrée des Catacombes et des Carrières de Paris; Éboulement de la
galerie du Port-Mahon; Coupe géologique du sol sous Paris; Trois vues
intérieures des Catacombes.--Histoire de la Semaine.--Intérieur de
la Chambre des Députés. Tribunes des deux Chambres; Tribune des
Orateurs de la Chambre des Pairs; Tribune des Journalistes à la Chambre
des députés; Sonnette du Président; La Tribune des Orateurs et le banc
des Ministres à la Chambre des Députés; Pupitre du banc des Ministres.--
Académie des Sciences. (Suite.)--Don Graviel l'Alferez. Fantaisie
maritime par M. G. de la Landelle. (Suite et fin.) Une Gravure. Théâtres.
Une Scène de Carla et Carlin.--Chinoiseries. Deux Gravures.--Bulletin
bibliographique.--Bronze. Une Gravure.--Amusements des
Sciences. Deux Gravures.--Rébus.
Courrier de Paris.
Mais où sommes-nous, bon Dieu? tout est sombre et sinistre: les bruits
de la ville, les nouvelles du dehors n'apportent à la curiosité publique que
des faits déplorables ou sanglants!--Vous sortez de votre lit le matin,
enveloppé de votre robe de chambre ouatée, les pieds dans vos
pantoufles, le teint frais, la bouche souriante, l'œil calme et doux, comme
un honnête homme qui a dormi la grasse matinée, avec un cœur léger et
une conscience en repos; vous voici dans votre fauteuil à bras, au coin
d'un feu joyeux, remuant dans votre cerveau les idées les plus aimables
et les plus sereines, et aimant toute la nature, comme dit la chanson de
Lantara.--Cependant vous prenez votre journal du matin, vous en brisez
l'enveloppe légère, et d'un œil curieux vous y cherchez les nouvelles
récentes de ce monde charmant, de ce délicieux univers dont vous êtes
amoureux; tout à coup votre regard s'attriste, votre visage s'assombrit,
vous pâlissez, vous rougissez tout à la fois; une invincible tristesse
s'empare de toute votre personne, et au lieu d'un air de fête, comme
tout à l'heure, vous avez un air d'enterrement.
Vue du Pont de Beaucaire, emporté par un coup de vent.
Perte du navire l'Elberfeldt.

C'est qu'en effet, depuis quelque temps, tout journal est une véritable
nécropole, un champ de meurtres et de ruines, une forêt de Bondi, où il
n'est pas sain de passer seul et sans armes. Le lecteur qui s'aventure
imprudemment dans la contrée des Nouvelles diverses, tressaille à
chaque pas et court risque de la vie; ici un bandit s'introduit dans la
maison d'un millionnaire, et laisse après lui un coffre-fort brisé et un
cadavre étendu sur les dalles; là deux pauvres vieilles femmes tombent
sous les coups d'un assassin; tous les jours du sang, tous les jours des
crimes hideux, tous les jours des crânes fendus, et le vol se glissant dans
les demeures et y introduisant le meurtre à l'œil hagard.--Hier c'était la
veuve Sénepart, aujourd'hui le banquier Donon-Cadet, demain l'Anglais
Ward; chaque semaine a son forfait, son bourreau, sa victime; et les
journaux ne manquent pas de vous donner, avec une exactitude qui fait
dresser les cheveux sur la tête, les plus minutieux et les plus horribles
détails de ces effroyables aventures.--En vérité, en lisant les feuilles du
matin, on se tâte pour s'assurer si on n'a pas reçu quelque coup de
couteau ou de poignard, et peu s'en faut qu'on ne crie: «A la garde!» La
main de la justice saisissant le crime, la loi le frappant de son glaive, ne
semblent plus même inquiéter le criminel. L'infortuné sculpteur P... a été
frappé de dix coups de stylet par son apprenti, qui venait d'assister au
supplice de Poulmann: et peut-être quelque assassin en expectative se
prépare à suivre assidûment les débats de l'affaire Ducros, le meurtrier
de madame Sénepart, qui commenceront la semaine prochaine. Ne sont-
ce pas là des faits épouvantables et qui attestent malheureusement qu'il
y a, à côté de notre monde de mœurs si faciles et si douces, je ne sais
quelle race féroce de damnés toujours armée et toujours menaçante?
Quel est le moyen d'apporter la lumière à ces âmes ténébreuses et
perdues? N'y en a-t-il aucun, et la société aura-t-elle toujours ses tigres,
ses hyènes et ses chacals?

C'est peu des hommes; les choses se mettent de la partie et jouent, à


leur tour, des jeux effrayants et terribles; tantôt--et nous en avons eu
tout récemment de douloureux exemples--c'est l'incendie qui allume ses
flammes dévorantes et détruit de riches manufactures; le pâle ouvrier,
sans travail et sans pain, erre sur les décombres fumants; tantôt c'est
l'inondation,--les récits publics l'attestent,--qui promène sur les
campagnes et sur les villes ses irrésistibles fureurs; les hameaux
disparaissent, la campagne est dévastée; des cadavres d'hommes et de
maisons flottent à la surface des vagues déchaînées; l'inondation, fléau
cent fois plus avide et plus insatiable que le dévorant incendie! En vain la
prévoyance humaine s'efforce d'opposer un obstacle à cet ennemi sans
frein; il rugit, il s'agite avec rage, et brisant, comme une paille fragile, la
digue la plus solide, répand la peur, la mort, le désastre de tous côtés.--
Plus loin, c'est l'ouragan qui gronde; l'ouragan, à qui rien ne résiste;
l'ouragan, monstre aux effroyables tourbillons, qui déracine les arbres
dans sa course haletante, abat les hautes tours et les hauts clochers,
emporte les toits et les murailles, fait crouler les arches des ponts et les
engloutit, dans les fleuves.--Qui n'a tressailli d'épouvante en entendant la
récente nouvelle de la ruine du pont de Beaucaire, qu'une trombe
furieuse a fait voler dans les airs et dispersé par débris, laissant des
cadavres sur la rive.

Voilà les faits sinistres qui occupent la ville depuis quinze jours, et se
mêlent au bruit de ses fêtes; l'élégant Paris ne s'en amuse pas moins et
continue de courir le bal.--Des pauvres gens inondés, noyés, ruinés,
assassinés, incendiés, mais savez-vous une c'est affreux, ma chère!--A
propos, dansez-vous la polka?

Rien n'est plus intéressant, en effet, que la polka; rien ne cause en ce


moment des émotions plus profondes, rien, pas même l'aventure du
navire hollandais l'Elberfeldt.--Le navire était en route pour l'Angleterre,
sous le commandement du capitaine Stranach; il avait à son bord M.
Busch. En approchant des côtes, M. Busch fit observer au capitaine
Stranach que, depuis quelques instants, le navire tressaillait en
marchant. Pour M. Busch, navigateur habile, ce tressaillement était le
signal d'une prochaine catastrophe; M. Burch prévoyait que le bâtiment,
construit en fer, ne tarderait pas à s'entr'ouvrir: «Alerte! capitaine; faites
préparer les embarcations! alerte! alerte!»

A peine l'alarme était-elle donnée qu'on entendit un craquement


épouvantable; M. Busch avait dit vrai: l'Elberfeldt venait de se rompre par
le milieu, en deux parts égales. «Nous sommes perdus! s'écria
l'équipage.--Arrêtez les machines! hors les embarcations!» répliqua M.
Busch; et en même temps il se jeta dans le canot avec deux hommes et
le fit amener. Le vent soufflait avec violence; cependant M. Busch, avec
un rare sang-froid et une grande habileté, maintint le canot le plus près
possible de l'arrière du navire; en même temps il criait au capitaine
Stranach de se jeter à la mer avec un aviron, afin d'éviter d'être écrasé
entre l'arrière et l'avant, qui se rejoignaient en s'abîmant.

Ce fut alors un moment suprême et terrible; le navire sombra; les


chaudières, écrasées par le choc des deux parties du bâtiment,
lancèrent, dans les airs d'immenses nuages de vapeur et des jets d'eau
bouillante; enfin, au milieu de ce vaste tourbillon de flamme et de fumée,
l'Elberfeldt disparut dans l'abîme béant, après une horrible explosion;
spectacle effrayant et grandiose!

Aussitôt M. Busch s'avança sur le champ du désastre, pour sauver les


victimes; la première qu'il recueillit fut le capitaine Stranach, qui se tenait
sur l'eau, soutenu sur un débris flottant de l'Elberfeldt; après le capitaine,
M. Busch sauva les matelots: l'équipage se composait, de treize hommes,
trois seulement périrent dans cette fatale journée. Pendant quatre
heures, le canot portant M. Busch, le capitaine Stranach et leurs
compagnons, flotta au caprice des vents sur une mer agitée et sombre;
la Providence envoya enfin à leur rencontre le navire, la Charlotte, qui les
prit à son bord et les mit à l'abri de tout danger.

J'ai entendu raconter cette catastrophe de l'Elberfeldt, beaucoup mieux


que je ne le fais, dans un bal charmant, par une femme fine et blanche,
au doux regard, aux lèvres roses, aux dents d'ivoire, à la taille de guêpe,
à la jambe de biche, au petit pied de fée, qui se leva en souriant, après
le récit terrible qu'elle venait de faire, pour se livrer aux bras d'un valseur
acharné; je pensais, en la voyant si ardente au plaisir, que toutes ces
frêles et intrépides petites Parisiennes valseraient encore, valseraient
toujours, alors même qu'une voix leur crierait, comme M. Busch au
capitaine Stranach: «Prenez garde, la mort est sous vos pieds; le sol
tressaille, et la salle de bal va s'entr'ouvrir, s'écrouler et vous engloutir!»

Il y a aujourd'hui à Paris un homme dont on parle certainement


beaucoup plus que de tous les hommes de génie ou de talent de notre
époque; cet homme a un crédit immense, une réputation prodigieuse;
son nom est dans toutes les bouches; il n'est question que de lui du
matin au soir: «Eh bien! l'avez-vous vu? Vous êtes-vous entendu avec ce
personnage merveilleux? Veut-il, ou ne veut-il? irez-vous le trouver, ou
daignera-t-il venir chez vous?» Telles sont les questions qu'on échange
de tous côtés; ni Mirabeau ni Napoléon n'ont excité une pareille rumeur
et obtenu un tel crédit.--Le nom de ce prodige, s'il vous plaît?--Ce
prodige se nomme Cellarius. Vous me regardez d'un air ébahi; quoi! vous
ne connaissez pas Cellarius? Mais qui êtes-vous? mais que faites vous?
mais d'où sortez-vous? Quand on vous parle de Cellarius, faire cette mine
d'ignorant et de débarqué de Pontoise! en vérité, c'est à ne plus oser dire
qu'on est de vos amis! c'est à vous tourner le dos! c'est à vous mettre à
la porte! c'est à vous fuir d'une lieue à la ronde!

Apprenez donc, et ne l'oubliez pas, que Cellarius est un homme... ah!...


un homme dont... un homme que... un homme... c'est un homme
enfin... qui donne des leçons de polka! Il n'y a guère qu'un mois que la
polka fait tourner la tête ou plutôt la jambe à nos lionnes, depuis la jeune
lionne aux crins noirs et blonds, aux reins souples et cambrés, jusqu'à la
lionne émérite pourvue d'une fausse crinière, jusqu'à la lionne efflanquée
et édentée. Ce mois a suffi pour élever Cellarius au-dessus de la colonne;
Musard n'est plus qu'un drôle; Cellarius va mettre l'empereur Musard à
bas de son piédestal! Cellarius n'était rien hier, il est tout aujourd'hui.

Vous jugez de l'air de Cellarius et des allures qu'il se donne; mais, après
tout, comme le grand Cellarius n'a pas le don d'ubiquité, et qu'il ne
saurait être en même temps partout où on le demande, il se partage le
plus qu'il peut, et se loue, au quart d'heure, à la demi-heure, à l'heure, je
ne dirai pas à la course, un personnage de l'importance de Cellarius ne
prend pas la peine de se déranger; on vient chez le grand homme.
Baronnes, duchesses, comtesses, marquises, femmes de banquier,
femmes de notaire, femmes d'agents de change y abondent, et
heureuses celles qu'il veut bien recevoir! Cellarius a répondu hier au valet
de chambre d'une comtesse! «Dites-lui que je n'ai pas le temps, et
qu'elle me laisse tranquille!» au groom d'une marquise: «Peut-être;» au
chasseur d'une princesse: «J'y songerai;» au premier gentilhomme d'une
impératrice: «Qu'elle attende.»

Quant au prix de ses leçons, le grand homme est modeste; il y a six


semaines, il demandait vingt francs par heure; c'était le commencement
de sa célébrité, le tarif s'est accru depuis, en proportion de sa
renommée; et avant un mois, si la mode du Cellarius ne se ralentit pas,
nous vous apprendrons probablement qu'un quart d'heure de polka du
danseur Cellarius est une denrée hors de prix que l'on n'obtient plus
qu'en déposant un cautionnement de 100,000 francs chez le concierge.

Je demande pardon à Jeanne d'Arc de la faire intervenir dans ces passe-


temps mondains; la chaste, simple et pieuse Jeanne va se trouver bien
déplacée au milieu de ces têtes légères et folles de polka; mais elle
m'absoudra en faveur de ma bonne intention, qui est de rendre justice
au talent d'un poète et à une œuvre distinguée: le poète s'appelle
Porchat, et il est de Lausanne; l'œuvre, qui a pour titre: la Mission de
Jeanne d'Arc, vient de paraître à la librairie Dubochet, rue de Seine. Sous
ce litre, la Mission de Jeanne d'Arc, on pourrait soupçonner quelque
épopée en vingt-quatre chants; il n'en est rien, et nous ne prenons pas
notre lecteur en traître; c'est d'une tragédie qu'il s'agit, d'une tragédie en
cinq actes, tragédie accueillie avec honneur au comité du Second-
Théâtre-Français, et qui devait tenter les chances de la représentation
publique. M. Porchat a préféré céder à des considérations qui font l'éloge
de sa modestie et de sa délicatesse, et retirer sa tragédie pour ne pas
faire concurrence à des œuvres présentées sous le même nom et le
même sujet, et ne pas nuire à des droits antérieurs. Après quoi, M.
Porchat s'est heureusement décidé à livrer sa Jeanne d'Arc à l'impression.

Nous venons de lire cet ouvrage intéressant et consciencieux, et c'est en


toute sincérité que nous regrettons que la Jeanne de M. Porchat n'ait pas
jusqu'au bout poussé l'aventure et récité sa poésie en face de la rampe,
au lieu de la faire brocher ou relier pour toute fortune; sans nul doute,
Jeanne aurait réussi. Des caractères bien étudiés, un style clair et
élégant, de nobles idées, des sentiments vraiment français, un drame
émouvant et varié, n'est-ce donc rien? Nos auteurs, même ceux en
crédit, nous font-ils souvent de tels présents? et sommes-nous si fort
gâtés par eux qu'il faille ne pas tenir compte à M. Porchat des honorables
qualités de sa tragédie? Eh bien! si on ne peut pas entendre cette Jeanne
au théâtre, du moins peut-on la lire au coin de son feu. Qu'on lise donc
la Jeanne de M. Porchat, on verra que certains de nos poètes, qui
donnent aussi dans le tragique, feraient sagement d'entreprendre un
petit voyage à Lausanne.

Nous avons entre les mains une lettre de madame Cinti-Damoreau datée
de La Havane; elle annonce son retour à Paris pour les premiers temps
de 1845. Pour revenir, il faudra que madame Damoreau s'arrache aux
ovations que l'Amérique multiplie sous ses pas. Il ne s'est rien vu de tel
depuis le passage de Fanny Ellsler. La voie de madame Damoreau produit
là-bas le même enthousiasme que le pied de l'adorable Fanny avait
partout soulevé. De Philadelphie à Baltimore, de Washington à
Richmond, de Richmond à Charlestown, la voix mélodieuse a séduit les
plus rebelles. Artot, comme on sait, accompagne madame Damoreau et
partage sa course triomphale. Les villes envoient des députations; les
sociétés offrent des fêtes. A Charlestown, après le concert, la foule,
s'échappant bruyamment par toutes les issues du théâtre, reconduisit les
artistes jusqu'à leur hôtel, au milieu des vivat, et à la lueur de mille
flambeaux.--A La Havane, où ils arrivèrent le 13 janvier, après une
traversée périlleuse, ils étaient attendus avec une telle impatience, que le
port se trouva tout à coup couvert d'une immense multitude pour les
recevoir. Le 17 janvier eut lieu leur premier concert. On se battait aux
portes; on se ruait dans la salle par flots précipités. Le journal havanais,
voulant peindre le succès obtenu par la cantatrice à cette première
soirée, dit: «Ce n'était pas un torrent, mais un Niagara
d'applaudissements.» Un feuilleton de Paris transporté à la Havane
n'aurait pas trouvé mieux.

--Du reste, après les bruits d'inondations, d'incendies, de meurtres et de


polka, il n'a été question ici, depuis huit jours, que de fortifications, de
patentes et de Pomaré. Décidément la semaine a été mauvaise.

--Le Théâtre-Italien de Saint-Pétersbourg a fait sa clôture le dimanche


(6) 18 février dernier, le dernier jour du carnaval des Russes. Jamais plus
magnifique représentation n'avait eu lieu à Paris ou à Londres durant les
plus belles années des directions Severini ou Laporte. On jouait quelques
scènes des Puritani pour Tamburini, et la Sonnanbula pour Rubini et
madame Viardot-Garcia... «La salle était plus que pleine, nous écrit notre
correspondant, on s'y était amoncelé; quant à vous raconter tout ce qui
s'est fait à cette représentation vraiment étonnante, et mémorable, je ne
sais comment m'y prendre. Il y avait, entre le public et les artistes, cet
échange du besoin d'être regretté qui fait que chacun se surpasse;
jamais madame Viardot et Rubini n'avaient chanté et joué avec autant de
verve et de pathétique; on pleurait dans la salle et sur le théâtre. Pour
vous donner une idée de l'enthousiasme général, et de la manière dont
on cherchait à le témoigner, il me suffira de vous dire qu'ici, et dans cette
saison, la scène a été littéralement couverte, à plusieurs reprises, de
bouquets et de couronnes. Un seul fleuriste en a vendu pour 1,400
roubles. Il y a eu au moins 50 rappels. A la fin du spectacle toute la salle
se tenait debout, les femmes agitant leurs mouchoirs, les hommes leurs
chapeaux, c'étaient non des bravi et des battements de mains, mais des
hurras et des trépignements universels. Cette scène étrange n'a fini que
lorsqu'on a pris le parti de relever le lustre et d'éteindre la rampe; il n'y a
que l'obscurité qui a fait partir enfin le public. Une demi-heure après,
quand les artistes sont sortis, ils ont trouvé une foule immense qui les
attendait à la porte pour les applaudir une dernière fois... et cependant il
faisait un froid dont on n'avait pas eu d'exemple depuis dix ans (30
degrés Réaumur). Pendant cette nuit même, vingt-deux personnes sont
mortes gelées dans les rues, n'ayant pas été relevées à temps par les
rondes de police, qui en ont sauvé bien d'autres.» La saison prochaine
promet d'être encore plus brillante que celle de cette année. Rubini.
Tamburini et madame Viardot ont renouvelé leurs engagement. Madame
Viardot, qui a obtenu de si éclatants succès, et qui a joué quarante fois
en trois mois et demi, aura, nous assure-t-on, près de 30,000 fr. par
mois.--On espère que Lablache se décidera A signer à Londres le brillant
engagement qui lui a été proposé.
Fragments d'un Voyage en Afrique (l).
(Suite et fin.--Voir t. II, p. 358, 374, 390 et 410; t. III, p. 6.)

Note 1: La reproduction de ces fragments est interdite.

Nous ne suivrons pas l'auteur de ces fragments dans le récit des causes
qui avaient amené la sanglante catastrophe de son malheureux ami. Le
lecteur est pressé sans doute de savoir de quelle manière l'auteur a pu
lui-même échapper aux périls que sa téméraire entreprise attirait sur sa
tête au moment où les hostilités venaient de recommencer contre l'émir.
..............................................................

A tout prix je voulus quitter Tazza, où je me sentais mourir peu à peu.


Tandis que je rêvais aux moyens de m'éloigner, le ciel, touché de mes
peines, fit passer dans la ville une caravane qui s'en retournait au Maroc.
Ni les dangers que j'allais courir en m'enfuyant du pays sans y être
autorisé par l'émir, ni les fatigues du voyage ne purent m'arrêter! Pour
moi il n'y avait que deux partis à prendre: mourir ou reconquérir ma
liberté. Le moment propice, le camp en désordre, la population effrayée,
secondèrent mon dessein. Je me procurai deux chameaux, et je me fis
associer, avec Ben-Oulil, à la caravane.

Je ne puis dire ici ce que je ressentis dès que nous eûmes dépassé les
portes de Tazza; il est des impressions qu'aucune langue ne rend bien.
La souffrance et la sombre atonie de mon âme s'effacèrent peu à peu
pour la laisser s'ouvrir à l'espérance. J'étais presque heureux, et je ne
songeais plus guère au meurtre commis sous mes yeux (tant l'homme
est égoïste!), lorsqu'un nouvel accident faillit me replonger dans toutes
mes terreurs. On sait qu'il faut traverser sept fois la Mina (la Blonde)
avant d'atteindre Mascara. Les eaux de cette rivière sont très-basses en
été, mais l'hiver les rend dangereuses; son sein, gonflé de tous les
torrents qui se précipitent des montagnes, s'élève et franchit souvent les
limites que lui imposa la nature. La Mina rappelle assez exactement notre
Rhône, dont les flots couvrirent tant de fois les belles plaines du Midi.
Quoique nous fussions alors au mois de juin, le passage de la rivière
présentait de graves difficultés; il avait plu beaucoup les jours
précédents, et la Mina mêlait ses eaux débordées aux mille petits
ruisseaux qui sillonnent le bassin du Chélif. Au troisième bras la caravane
s'élancait au galop des chameaux, lorsque Ben-Oulil perdit l'équilibre et
disparut dans le gouffre. Nous ne nous aperçûmes de l'accident qu'en
voyant son chameau débarquer seul sur le bord opposé.

J'appris en passant à quelques lieues de Tekedempt, qu'une cinquantaine


de prisonniers français étaient détenus dans la forteresse; on les
employait, dit-on, aux travaux les plus rudes et les plus abjects; aucun
outrage ne leur était épargné. Quelques-uns travaillaient à la
manufacture d'armes. Il y avait, en outre, en ville deux femmes et quatre
enfants qui partageaient le logement de la famille d'Abd-el-Kader, ainsi
que deux Alsaciennes qui avaient été laissées par un Européen en
garantie de quelques fonds qu'il devait à l'émir. Ces otages n'ont pas été
réclamés depuis.

Sur la ligne qui conduit à Mascara, on trouve plusieurs villes, entre autres
Mysouna, Tyliouan et Callah. La première est perchée sur la crête d'une
montagne; elle compte un millier d'habitants, presque tous hommes
lettrés, c'est-à-dire lecteurs du Koran (on est lettré chez les Arabes
lorsqu'on explique le livre du Prophète). Les Mysouniens ne s'inquiètent
point de ce qui se passe autour d'eux. Tyliouan, petite cité en ruines,
occupe le fond d'un vallon. Des monts élevés la couronnent; elle a de six
à sept cents habitants lettrés et fanatiques qui abhorrent, non-seulement
les Français, mais tous les Européens en général. Callah n'est qu'un petit
douair auquel on a généreusement donné le nom de ville; quelques
cabanes couvertes de chaume éparpillées sans ordre dans une plaine
resserrée entre deux chaînes de montagne, quelques jardins, une
forteresse ou, pour être plus exact, une tour délabrée, tel est Callah. Il
est à remarquer cependant que les quatre cents Arabes qui l'habitent
sont assez industrieux. Il s'y fabrique de beaux tapis de pied, dont les
Marocains et les citoyens de Fez font le principal objet de leurs
spéculations. On obtient ces objets à vil prix sur les lieux, tant la misère y
est grande! Les populations de Mysouna. Tyliouan et Callah sont
administrées par Hadji-Mustapha. Elles ne fournissent que des cavaliers à
la guerre sainte. On peut recruter dans ces villes environ huit mille
combattants qui suivent la bannière de Mouloud-ben-Aratch. On conçoit
aisément les motifs de la haine qu'elles nous portent, car elles
appartiennent à la tribu d'Abd-el-Kader. L'égoïsme, l'amour-propre et
l'intérêt lui ont fait parmi elles des serviteurs dévoués.

Juillet dardait sur nous ses rayons dévorants lorsque nous traversâmes
Mascara. Cette ville n'avait alors que fort peu d'habitants; on désertait
ses marchés; c'est à peine si on y rencontrait quelques citoyens venus de
Fez pour vendre des objets dont le pays était privé depuis que l'émir
avait, par un édit, prononcé la peine capitale contre quiconque achèterait
ces objets dans nos ports. Les habitants de Mascara, réduits à la misère,
s'étaient jetés dans les montagnes ou retirés à Tekedempt. Ceux qui
étaient restés les derniers expédiaient déjà leur bagage et n'attendaient
qu'un ordre du sultan pour abandonner leurs foyers: on s'attendait à voir
paraître d'un instant à l'autre les colonnes françaises. Le kalifat était sorti
de la ville il avait posé son camp sur la rive droite de la Mina, à une
journée de marche vers l'est. Tout ce qui, dans la ville, appartenait au
gouvernement venait d'être dirigé sur Tekedempt. La contrée était en un
mot sur un qui vive continuel; de toutes parts on voyait surgir des
cohortes arabes. D'après nos calculs, nous avons vu défiler devant nous
plus de quatre mille cavaliers marchant au secours de l'émir. La
canonnade retentissait du côté de Milianah, et les vieux échos de l'Atlas
apportaient jusqu'à nous ces bruits formidables. Nous marchions
épouvantés par des détonations pareilles au bruit du tonnerre. Nous
apprîmes ensuite que les Français s'étaient emparés de Milianah sans
avoir été inquiétés par les Arabes. Ceux-ci perdirent encore beaucoup de
monde dans l'affaire de la vallée du Chélif, qui eut lieu immédiatement
après.

De Mascara à Tlemcen, la route est pittoresque et très-accidentée; on


parcourt de longues chaussées formées par les pentes des chaînes, puis
on traverse l'Hamman et le Sigg, fleuves qui se jettent dans la mer, au
golfe d'Arzew, après avoir réuni leurs eaux à celles de l'Habra. Le Sigg
coule aux pieds des Dj. Karkar, monts boisés que le voyageur traverse et
d'où il découvre Tlemcen et toute la province. A notre droite, dans la
direction du désert d'Angad, est Saïda, fort bâti par Bou-Hamidy, d'après
l'ordre d'Abd-el-Kader. On met deux jours pour se rendre du Tlemcen à
Saïda. Ce dernier point est, au dire des indigènes, l'un des plus
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!

[Link]

You might also like