Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Mastering Linux Shell Scripting Second

Edition Mokhtar Ebrahim Andrew


Mallett
Visit to download the full and correct content document:
https://ebookmeta.com/product/mastering-linux-shell-scripting-second-edition-mokhta
r-ebrahim-andrew-mallett-2/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Mastering Linux Shell Scripting Second Edition Mokhtar


Ebrahim Andrew Mallett

https://ebookmeta.com/product/mastering-linux-shell-scripting-
second-edition-mokhtar-ebrahim-andrew-mallett/

Linux Shell Scripting Bootcamp 1st Edition James Kent


Lewis

https://ebookmeta.com/product/linux-shell-scripting-bootcamp-1st-
edition-james-kent-lewis/

Linux Shell Scripting Cookbook 2nd Edition Shantanu


Tushar Sarath Lakshman

https://ebookmeta.com/product/linux-shell-scripting-cookbook-2nd-
edition-shantanu-tushar-sarath-lakshman/

Linux Shell Scripting Cookbook Quick Answers to Common


Problems Shantanu Tushar

https://ebookmeta.com/product/linux-shell-scripting-cookbook-
quick-answers-to-common-problems-shantanu-tushar/
Linux introduce to beginners guide UNIX operating
system Linux shell scripting and command line Linux
System 1st Edition Erickson Karnel & Coding Hood

https://ebookmeta.com/product/linux-introduce-to-beginners-guide-
unix-operating-system-linux-shell-scripting-and-command-line-
linux-system-1st-edition-erickson-karnel-coding-hood/

Salt Open: Automating Your Enterprise and Your Network


1st Edition Andrew Mallett

https://ebookmeta.com/product/salt-open-automating-your-
enterprise-and-your-network-1st-edition-andrew-mallett/

Salt Open: Automating Your Enterprise and Your Network


1st Edition Andrew Mallett

https://ebookmeta.com/product/salt-open-automating-your-
enterprise-and-your-network-1st-edition-andrew-mallett-2/

Pro Bash: Learn to Script and Program the GNU/Linux


Shell 3rd Edition Jayant Varma

https://ebookmeta.com/product/pro-bash-learn-to-script-and-
program-the-gnu-linux-shell-3rd-edition-jayant-varma/

Linux Fundamentals Second Edition Richard Blum

https://ebookmeta.com/product/linux-fundamentals-second-edition-
richard-blum/
Mastering Linux Shell Scripting
Second Edition

A practical guide to Linux command-line, Bash scripting, and Shell


programming

Mokhtar Ebrahim
Andrew Mallett
BIRMINGHAM - MUMBAI
Mastering Linux Shell
Scripting Second Edition
Copyright © 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

www.packtpub.com
mapt.io

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 www.PacktPub.com and as a print book customer, you are
entitled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.

At www.PacktPub.com, 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 autho
rs.packtpub.com 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
Title Page

Copyright and Credits

Mastering Linux Shell Scripting Second Edition

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the authors

About the reviewer

Packt is searching for authors like you


Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

1. The What and Why of Scripting with Bash

Technical requirements

Types of Linux shells

What is bash scripting?

The bash command hierarchy


Command type

Command PATH

Preparing text editors for scripting

Configuring vim

Configuring nano

Configuring gedit

Creating and executing scripts


Hello World!

Executing the script

Checking the exit status

Ensuring a unique name

Hello Dolly!

Running the script with arguments

The importance of correct quotes

Printing the script name

Declaring variables

User-defined variables

Environment variables

Variable scope

Command substitution

Debugging your scripts

Summary

Questions

Further reading

2. Creating Interactive Scripts

Technical requirements

Using echo with options

Basic script using read

Script comments

Enhancing scripts with read prompts


Limiting the number of entered characters

Controlling the visibility of the entered text


Passing options

Passing parameters with options


Read options values

Try to be standard
Enhancing learning with simple scripts

Backing-up with scripts


Connecting to a server

Version 1 – ping


Version 2 – SSH

Version 3 – MySQL/MariaDB


Reading files
Summary
Questions

Further reading
3. Conditions Attached

Technical requirements
Simple decision paths using command-line lists

Verifying user input with lists


Using the test shell built-in

Testing strings
Testing integers

Testing file types


Creating conditional statements using if

Extending if with else


Test command with the if command

Checking strings
Checking files and directories

Checking numbers
Combining tests

More conditions with elif


Creating the backup2.sh using elif

Using case statements


Recipe – building a frontend with grep

Summary
Questions

Further reading
4. Creating Code Snippets

Technical requirements
Abbreviations

Using code snippets


Bringing color to the Terminal

Creating snippets using VS Code


Summary

Questions
Further reading

5. Alternative Syntax
Technical requirement
Recapping the test command
Testing files

Adding logic
Square brackets as not seen before

Providing parameter defaults


Variables
Special parameters

Setting defaults
When in doubt – quote!
Advanced tests using [[
White space

Other advanced features


Pattern matching
Regular expressions
Regular expression script

Arithmetic operations using ((


Simple math
Parameter manipulation
Standard arithmetic tests

Summary
Questions
Further reading
6. Iterating with Loops

Technical requirement
for loops
Advanced for loops
The IFS

Counting directories and files


C-style for loops 
Nested loops
Redirecting loop output

Controlling the loop


while loops and until loops
Reading input from files
Creating operator menus

Summary
Questions
Further reading
7. Creating Building Blocks with Functions

Technical requirements
Introducing functions
Passing parameters to functions

Passing arrays
Variable scope
Returning values from functions
Recursive functions

Using functions in menus


Summary
Questions
Further reading

8. Introducing the Stream Editor


Technical requirements
Using grep to display text
Displaying received data on an interface

Displaying user account data


Listing the number of CPUs in a system
Parsing CSV files
The CSV file

Isolating catalog entries


Understanding the basics of sed
The substitute command
Global replacement

Limiting substitution
Editing the file
Other sed commands
The delete command

The insert and append commands


The change command
The transform command
Multiple sed commands

Summary
Questions
Further reading
9. Automating Apache Virtual Hosts

Technical requirements
Apache name-based Virtual Hosts
Creating the virtual host template
First steps

Isolating lines
sed script files
Automating virtual host creation
Prompting for data during site creation

Summary
Questions
Further reading
10. AWK Fundamentals

Technical requirements
The history behind AWK
Displaying and filtering content from files
AWK variables

User-defined variables
Conditional statements
The if command
while loops

for loops
Formatting output
Further filtering to display users by UID
AWK control files

Built-in functions
Summary
Questions
Further reading

11. Regular Expressions


Technical requirements
Regular expression engines
Defining BRE patterns

Anchor characters
The dot character
The character class
Ranges of characters

Special character classes


The asterisk
Defining ERE patterns
The question mark

The plus sign


Curly braces
The pipe character
Expression grouping

Using grep
Summary

Questions

Further reading
12. Summarizing Logs with AWK

Technical requirements

The HTTPD log file format


Displaying data from web logs

Selecting entries by date


Summarizing 404 errors

Summarizing HTTP access codes

Resources hits
Identify image hotlinking

Displaying the highest ranking IP address

Displaying the browser data


Working with email logs

Summary
Questions

Further reading

13. A Better lastlog with AWK


Technical requirements

Using AWK ranges to exclude data

The lastlog command


Horizontally filtering rows with AWK

Counting matched rows


Conditions based on the number of fields
Manipulating the AWK record separator to report on XML data

Apache Virtual Hosts


XML catalog

Summary

Questions
Further reading

14. Using Python as a Bash Scripting Alternative


Technical requirements

What is Python?

Saying Hello World the Python way


Pythonic arguments

Supplying arguments

Counting arguments
Significant whitespace

Reading user input


Using Python to write to files

String manipulation

Summary
Questions

Further reading

Assessments
Chapter 1

Chapter 2
Chapter 3

Chapter 4

Chapter 5
Chapter 6

Chapter 7

Chapter 8
Chapter 9

Chapter 10

Chapter 11
Chapter 12

Chapter 13
Chapter 14

Other Books You May Enjoy


Leave a review - let other readers know what you think
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.
What this book covers
, The What and Why of Scripting with Bash, will introduce
Chapter 1

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.

, Creating Interactive Scripts, covers how to read input from


Chapter 2

the user using read 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.

, Conditions Attached, will introduce the


Chapter 3 if statement, the case

statement, and other testing command such as else and elif.

, Creating Code Snippets, covers creating and using code


Chapter 4

snippets using editors, such as vim and Visual Studio Code.

, Alternative Syntax, will discuss advanced testing using


Chapter 5 [[

and how to perform arithmetic operations.

Chapter 6, Iterating with Loops, will teach you how to use for loops,
while loops, and until loops to iterate over simple values and complex

values.

, Creating Building Blocks with Functions, will introduce


Chapter 7

functions and explains how to create a function, list builtin functions,


pass parameters to functions, and writing recursive functions.

, Introducing the Stream Editor, will introduce the basics of


Chapter 8

sed tool to manipulate files, such as adding, replacing deleting, and


transforming text.
, Automating Apache Virtual Hosts, contains a practical
Chapter 9

example of sed and explains how to create virtual hosts


automatically using sed.

, AWK Fundamentals, will discuss AWK and how to filter file


Chapter 10

content using it. Also, we will discuss some AWK programming


basics.

, Regular Expressions, covers regular expressions, their


Chapter 11

engines, and how to use them with sed and AWK to empower your
script.

Chapter 12, Summarizing Logs with AWK, will show how to process the
httpd.conf Apache log file using AWK and extract useful well-formatted

data.

, A Better lastlog with AWK, will show you how to use AWK
Chapter 13

to output beautiful reports using the lastlog command by filtering


and processing the lastlog output.

, Using Python as a Bash Scripting Alternative, will discuss


Chapter 14

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 ls, cd, and which.
Download the example code
files
You can download the example code files for this book from your
account at www.packtpub.com. If you purchased this book elsewhere, you
can visit www.packtpub.com/support 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 www.packtpub.com.


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 https://githu
b.com/PacktPublishing/Mastering-Linux-Shell-Scripting-Second-Edition. 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 https://github.com/PacktPublishing/. Check them out!
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 ht

tps://www.packtpub.com/sites/default/files/downloads/MasteringLinuxShellScriptingSec

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

CodeInText: 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 $HOME/bin/hello2.sh"

A block of code is set as follows:


if [ $file_compression = "L" ] ; then
tar_opt=$tar_l
elif [ $file_compression = "M" ]; then
tar_opt=$tar_m
else
tar_opt=$tar_h
fi

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.


Get in touch
Feedback from our readers is always welcome.

General feedback: Email feedback@packtpub.com 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 questions@packtpub.com.

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 www.packtpub.com/submit-errata, 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
copyright@packtpub.com 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 authors.packtpub.com.
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 packtpub.com .


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
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: https://code.visualstudio.com/.

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 bashdb, 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 https://marketpl
ace.visualstudio.com/items?itemName=rogalmic.bash-debug. This plugin will be

used to debug bash scripts.

The source code for this chapter can be downloaded here:

https://github.com/PacktPublishing/Mastering-Linux-Shell-Scripting-Second-Edition/tr

ee/master/Chapter01
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.

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 if statement, or else or while loops. All are Linux
executables.

You can say that the shell is the glue that binds these commands
together.
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 ls 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 type command can
come to our aid here. The type 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 ls.

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

If we need to just type in the output, we can use the -t 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 type can also be used to identify shell keywords such as
if, and case. The following command shows type 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 type.
Command PATH
Linux will check for executables in the PATH 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 PATH. It is possible
to include our current directory within the PATH by adding the
directory to the PATH variable. This is shown in the following
command example:
$ export PATH=$PATH:.

This appends the current directory to the value of the PATH variable;
each item in the PATH is separated using a colon. Now your PATH 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 bin
within your home directory and add the scripts into that folder.
Adding $HOME/bin to your PATH 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 bin directory or not. The
use of the $HOME 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 $HOME/bin
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.
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, $HOME/.vimrc.

The options we set are detailed in the following list:

set showmode: Ensures we see when we are in insert mode


set nohlsearch: Does not highlight the words that we have

searched for
set autoindent: 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
set tabstop=4: Sets a tab to be four spaces

set expandtab: Converts tabs to spaces, which is useful when the

file moves to other systems


syntax on: Note that this does not use the set command and is

used to turn on syntax highlighting

When these options are set, the $HOME/.vimrc file should look similar to
this:
set showmode
set nohlsearch
set autoindent
set tabstop=4
set expandtab
syntax on
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 $HOME/.nanorc file. Your
edited file should look something like the following:
set autoindent
set tabsize 4
include /usr/share/nano/sh.nanorc

The last line enables syntax highlighting for shell scripts.


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 http://www.packtpub.com for all
the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can
visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

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:
Another random document with
no related content on Scribd:
trace of a digestive tract at any stage of the life-history of Cestodes. For
nourishment they absorb, through the skin, the previously-digested food (of the
host) that bathes them. In a few Cestodes the body is simple and not divided into
"proglottides" or generative segments, but in most cases it is jointed in such a way
that the last segment is the oldest, and each contains a set of reproductive organs.
The life-histories of Cestodes are most remarkable. The proglottides containing the
eggs pass out of the final host along with the faeces and enter the intermediate
host with the food. The larvae hatch, and boring their way into the blood-vessels,
are carried by the circulation to various internal organs. Here they usually become
"bladder-worms," and develop the "head" of the future sexual form. Then, if, as is
usually the case, the intermediate host is preyed upon by the final host, the larval
Cestodes enter the alimentary canal of the latter. The head of the larva alone
survives digestion, and from it the mature worm is formed.

Of these three branches of the phylum Platyhelminthes, the Turbellaria possess


features of special interest and importance. Not only do they furnish the
explanation of the structure of the two parasitic groups (which have probably arisen
from Turbellarian-like ancestors), but they occupy the lowest position in the whole
group of worms. There are reasons for thinking that this is the simplest group of
bilateral animals which adopt the habit of creeping. The Turbellaria are most
closely allied to that great extinct group from which they, the Nemertinea, Rotifera,
and even the Annelids, offer increasingly convincing evidence of having been
derived. Many questions relating to the affinities of, or the origin of organs in, the
Annelids, resolve themselves into similar questions about the Turbellaria. For these
reasons, this group is here dealt with at greater length than the others, the interest
of which is of a more special nature.

The history of our knowledge of the Cestodes dates back to ancient times, as the
presence and effects of tape-worms early attracted the attention of physicians.
Trematodes are first distinctly referred to in the sixteenth century, while Turbellaria
first figure in Trembley's memoir on Hydra (1744).[3] The whole subject of the
increase in our knowledge of parasitic Platyhelminthes is dealt with in the standard
work, The Parasites of Man, by Leuckart,[4] and a complete list of references in
zoological literature to Cestodes and Trematodes is to be found in Bronn's
Thierreich.[5] O. F. Müller[6] and Ehrenberg founded our knowledge of the
Turbellaria, but for a long time the group remained in a most neglected condition. In
this country Montagu, G. Johnston, and in Ireland, William Thompson, discovered
several marine species, one of which, Planocera folium (from Berwick), has not
again been met with on British shores. Dalyell[7] conducted classical researches on
the habits of Planarians, and Faraday[8] made interesting experiments on their
power of regenerating lost parts. The credit of assigning the correct interpretation
to most of the various organs of fresh-water Planarians belongs to von Baer[9] and
Dugès,[10] while Mertens[11] effected a similar service for the marine forms, or
Polyclads. The minute Rhabdocoels were first successfully investigated and
classified by Oscar Schmidt.[12] The great work on this group is, however, the
monograph by von Graff.[13] A similarly comprehensive and indispensable treatise
by Lang, on the Polycladida,[14] contains references to all previous publications on
the group, among which the papers by Quatrefages, Johannes Müller, Keferstein,
Minot, and Hallez stand out conspicuously. Moseley's work[15] on the Land
Planarians of Ceylon is undoubtedly the most revolutionary paper referring to this
group, and the best contribution towards elucidating the structure of the Tricladida
at a time when the subject was very obscure. A monograph on Land Planarians is
being prepared by von Graff.

The Turbellaria are divided into: (1) Polycladida, marine forms with multiple
intestinal branches; (2) Tricladida, marine, fresh-water, and terrestrial Planarians
with three main intestinal branches; (3) the Rhabdocoelida, as varied in habit as
the Triclads, but possessing a straight and simple or slightly lobed, intestine. A
detailed description of an example of the Polyclads, and then a comparative
account of each division, will now be given.

Fig. 1.—Leptoplana tremellaris O. F. M. Seen from the dorsal surface. The


alimentary canal runs down the middle line and sends branches to the margin
of the body. × 6.

Turbellaria. I. Polycladida.

Description of Leptoplana tremellaris.

Appearance and Habits.—An account of the Polyclad Turbellaria may be fitly


prefaced by a description of a very common representative, Leptoplana tremellaris,
so called on account of the thin, flat body which executes when disturbed,
quivering or tremulous swimming movements.

Like all Polyclads, Leptoplana is marine. It is probably found on all European


shores, northwards to Greenland and southwards to the Red Sea, while vertically it
ranges from the littoral zone down to fifty fathoms. There is, however, an
apparently well-marked difference between the littoral specimens, which vary from
three-quarters to one inch in length, are brownish in colour and firm in consistency,
and the more delicate examples half an inch long, white with a brown tinge, which
occur in deeper water.

Fig. 2.—Leptoplana tremellaris. Three-quarters view from the ventral surface. The
pharynx (ph) is widely protruded through the month (mo) as in the act of
attacking prey. br, Brain with nerves, close to which are the four groups of eyes;
mg, stomach; mgc, "marginal groove"; pe, penis; sc, sucker; ut, uterus; vd, vasa
deferentia; ♀ , female genital aperture surrounded by the shell-gland; ♂ , male
aperture. (Semi-diagrammatic, and × 6.)

At low water Leptoplana may be found buried in mud or on the under surface of
stones, in pools where darkness and dampness may be ensured till the return of
the tide. It is, however, by no means easy to detect and remove it from the
encrusting Polyzoa, Ascidians, or Sponges with which it is usually associated. The
flat, soft, unsegmented body is so closely appressed to the substratum that its
presence is usually only betrayed by its movement, an even gliding motion of the
mobile body, which suggested the apt name "la pellicule animée" to Dicquemare.
The creeping surface is called ventral, the upper one dorsal, and as the broader
end of the body always goes first, it is anterior as opposed to the more pointed
posterior extremity. With a lens the characters shown in Figs. 1 and 2 may be
observed. The eyes are seen as black dots near the anterior end, and are placed
at the sides of a clear oval space, the brain. Along the transparent margin of the
body, the ends of the intestinal branches may be seen. These ramify from a lobed
stomach or main-gut, and should the specimen be mature, the "uterus" loaded with
eggs forms a dark margin round the latter (Figs. 1 and 2, ut). The ventral surface is
whitish, and through it the "pharynx," a frilled protrusible structure, may be dimly
observed. The "mouth,"[16] through which the pharynx at the time of feeding is
thrust out (Fig. 2, mo), is almost in the centre of the ventral surface. Behind this, a
white, V-shaped mark (vd) indicates the ducts of the male reproductive organs, and
still further back is the irregular opaque mark of the "shell-gland," by which the egg-
shells are formed (Fig. 2, ♀).
Fig. 3.—Leptoplana tremellaris in the act of swimming. A, Seen from the right side
during the downward stroke (the resemblance to a skate is striking); B, from
above, showing the upward stroke and longitudinal undulations of the swimming
lobes; C, side view during the upward stroke; D, transverse sections of the body
during the strokes. × 5.

Leptoplana employs two kinds of movement, creeping and swimming. Creeping is


a uniform gliding movement, caused by the cilia of the ventral surface, aided
perhaps by the longitudinal muscular layers of this surface, and is effected on the
under side of the "surface-film" of water almost as well as on a solid substratum.
Swimming is a more rapid and elegant movement, employed when alarmed or in
pursuit of prey. The expanded fore-parts of the body act as lobes, which are
flapped rapidly up over the body and then down beneath it, undulations running
rapidly down them from before backwards. The action in fact is somewhat similar
to that by which a skate swims, a resemblance pointed out long ago by Dugès[17]
(Fig. 3).

We have few direct observations on the nature of the food of Leptoplana, or the
exact mode by which it is obtained. Dalyell,[18] who observed this species very
carefully, noticed that it was nocturnal and fed upon a Nereis, becoming greatly
distended and of a green colour after the meal, but pale after a long fast.
Keferstein[19] noticed a specimen in the act of devouring a Lumbriconereis longer
than itself, and also found the radulae of Chiton and Taenioglossate Molluscs in the
intestine. That such an apparently weak and defenceless animal does overpower
large and healthy Annelids and Mollusca, has not hitherto been definitely proved.
Weak or diseased examples may be chiefly selected. The flexible Leptoplana
adheres firmly to its prey, and the rapid action of the salivary glands of its mobile
pharynx quickly softens and disintegrates the internal parts of the victim. The food
passes into the stomach (Fig. 2, mg), and is there digested. It is then transferred to
the lateral branches of the intestine, and, after all the nutritious matters have been
absorbed, the faeces are ejected with a sudden contraction of the whole body
through the pharynx into the water.

Leptoplana probably does not live more than a year. In the spring or summer,
batches of eggs are laid and fixed to algae or stones by one individual, after having
been fertilised by another. Young Leptoplana hatch out in two to three weeks, and
lead a pelagic existence till they are three or four millimetres in length. In late
summer, numbers of such immature examples may be found among sea-weeds
and Corallina in tide pools. In the succeeding spring they develop first the male and
then the female reproductive organs.

Fig. 4.—Portion of a transverse section of Leptoplana tremellaris in the hinder part of


the body. × 100. bm, Basement (skeletal) membrane; cil, cilia; d.m, diagonal
muscles; d.v.m, dorso-ventral muscles; ep, epidermis; f.p, food particles; l.g,
lateral intestinal branches cut across; l.m ext, external, and l.m int, internal
longitudinal muscle layers; m.c, glandular (mucous) cells; md, their ducts; N,
longitudinal nerve; Nu, nuclei of the intestinal epithelium; ov, ovary; ovd,
oviduct; par, cells of the parenchyma; r.d, vasa deferentia, with spermatozoa;
rm, circular musculature; rh, rhabdites; sh, cells of the shell-gland; te, testes; ve,
vasa efferentia; y.c, "yellow cells." (After Lang.)

Anatomy of Leptoplana tremellaris.—Leptoplana may be divided into


corresponding halves only by a median vertical longitudinal plane. The body and all
the systems of organs are strictly bilaterally symmetrical. Excepting the cavities of
the organs themselves, the body is solid. A connective "parenchyma" (Fig. 4, par)
knits the various internal organs together, while it allows free play of one part on
another. These organs are enclosed in a muscular body-wall, clothed externally by
the ciliated epidermis, which is separated from the underlying musculature by a
strong membrane (Fig. 4, bm), the only skeletal element in the body.

Body-Wall.—The epidermis (Fig. 4, ep) is composed of a single layer of ciliated


cells, containing small, highly refractive, pointed rods or "rhabdites" (rh), and gives
rise to deeply-placed mucous cells (m.c), which are glandular and pour out on the
surface of the body a fluid in which the cilia vibrate. The tenacious hold on a stone
which Leptoplana exerts if suddenly disturbed, or when grasping its prey, is
probably due to the increased glutinous secretion of these glands, aided perhaps
by rhabdites, which on such occasions are shot out in great numbers. The
basement membrane is an elastic skeletal membrane composed of stellate cells
embedded in a firm matrix. It serves chiefly for the origin and insertion of the dorso-
ventral muscles (d.v.m). Under the basement membrane lies a very thin layer of
transverse muscular fibres (Fig. 4, rm), which are, however, apparently absent on
the ventral surface. Then follows a stout layer of longitudinal fibres (l.m ext), and
beneath this a diagonal layer (d.m), the fibres of which intersect along the median
line in such a way that the inner fibres of one side become the outer diagonal fibres
of the other. Lastly, within this again, on the ventral surface, is a second stout
longitudinal layer (l.m int). The sucker (sc, Figs. 2 and 5) is a modification of the
body-wall at that point. In addition to the dorso-ventral muscles, there exists a
complex visceral musculature regulating the movements of the pharynx, intestine,
and copulatory organs.

Parenchyma.—The spaces between the main organs of the body are filled by a
tissue containing various kinds of cells, salivary glands, shell-glands, and prostate
glands. Besides these, however, we find a vacuolated, nucleated, thick-walled
network, and to this the word parenchyma is properly applied. Besides its
connective function, the parenchyma confers that elasticity on the body which
Leptoplana possesses in such a high degree. Pigment cells are found in the
parenchyma in many Polyclads.

Digestive System.—The general arrangement of this system may be seen in Figs.


2, 5, and 7; and may be compared, especially when the pharynx is protruded, as in
Fig. 2, with the gastral system of a Medusa. The "mouth" (there is no anus) is
placed almost in the centre of the ventral surface. It leads (Fig. 7, B, phs) into a
chamber (the peripharyngeal space) divided into an upper and a lower division by
the insertion of a muscular collar-fold (the pharynx, ph), which may be protruded,
its free lips advancing, through the mouth (Fig. 2), and is then capable of enclosing
by its mobile frilled margin, prey as large as Leptoplana itself. The upper division of
the chamber communicates by a hole in its roof[20] (the true mouth, Figs. 5 and 7,
g.m) with the cavity of the main-gut or stomach (m.g), which runs almost the length
of the body in the middle line, forwards over the brain (Fig. 5, up). Seven pairs of
lateral gut-branches convey the digested food to the various organs, not directly
however, but only after the food mixed with sea-water has been repeatedly driven
by peristalsis first towards the blind end of the gut-branches and then back towards
the stomach. Respiration is probably largely effected by this means. The epithelium
of the intestine (Fig. 4, l.g) of a starving specimen is composed of separate
flagellated cells frequently containing "yellow cells."[21] After a meal, however, the
cell outlines are invisible. Gregarines, encysted Cercariae, and Orthonectida[22]
occur parasitically in the gut-branches.
An excretory system of "flame-cells" and fine vessels has hitherto been seen only
by Schultze[23] in this species, which will not, however, resist intact the
compression necessary to enable the details to be determined. They are probably
similar to those of Thysanozoon described on p. 25.

Nervous System.—The brain, which is enclosed in a tough capsule (Fig. 5, br), is


placed in front of the pharynx, but some distance behind the anterior margin of the
body. It is of an oval shape, subdivided superficially into right and left halves by a
shallow depression, and is provided in front with a pair of granular-looking
appendages, composed of ganglion-cells from which numerous sensory nerves
arise, supplying the eyes and anterior region. Posteriorly the brain gives rise to a
chiefly motor, nervous sheath (Fig. 5, nn), which invests the body just within the
musculature. This sheath is thickened along two ventral lines (Fig. 5, ln) and two
lateral lines (n.s), but is very slightly developed on the dorsal surface. Ganglion-
cells occur on the course of the nerves, and are particularly large at the point of
origin of the great motor nerves.
Fig. 5.—Diagrammatic view of the structure of Leptoplana tremellaris
as a type of the Polycladida. The body is cut across the middle to
show the relative position of organs in transverse section. In the
posterior half the alimentary canal has been bisected and
removed from the left side, to exhibit the deeply placed nervous
sheath (nn) and the male reproductive organs. br, Brain; dp,
"diaphragm"; e, cerebral group of eyes; et, tentacular eye-group;
gr, marginal groove; gm, true mouth; lg, lateral gut-branch; ln,
longitudinal nerve stem; m, external mouth; mg, mg', main-gut,
whole, and bisected; n, sensory nerve supplying the eyes; nn,
nervous network lying on the ventral musculature; n.s, lateral
nerve; od, oviduct; ov, ovary; pe, penis (in section); ph, pharynx;
pr, prostate or "granule gland"; sc, sucker; sg, shell-gland; te,
testes; up, anterior unpaired gut-branch; ut, uterus; va, vagina (in
section); vd, vas deferens; ve, vasa efferentia; ♂ , male genital
pore; ♀, female pore.

Sense Organs.—Leptoplana possesses eyes, stiff tactile, marginal


cilia, and possibly a sense organ in the "marginal groove." The eyes,
which are easily seen as collections of black dots lying at the sides
of the brain, may be divided into two paired groups: (1) cerebral eyes
(Fig. 5, e), and (2) tentacle eyes (et), which indicate the position of a
pair of tentacles in allied forms (Fig. 8, A, t and B). Each ocellus
consists of a capsule placed at right angles to the surface of the
body in the parenchyma, below the dorsal muscles, and with its
convex face outwards. It is a single cell in which pigment granules
have accumulated. The light, however, can only reach the refractive
rods, which lie within it, obliquely at their outer ends. These rods are
in connexion with the retinal cells, and thus communicate by the
optic nerve with the brain. The cerebral eyes are really paired, and
are directed some upwards, some sideways, some downwards.

The "marginal groove" is a shallow depression of the epidermis (Fig.


5, gr) lined by cilia, and containing the ducts of very numerous gland-
cells. It runs almost parallel to the anterior margin of the body, a
short distance from it, but we have no observations on its functions.

Fig. 6.—Diagram of an eye of Leptoplana from the tentacle group. ×


600. (After Lang.)

Reproductive Organs.—Leptoplana is hermaphrodite, and, as in


most hermaphrodites, the reproductive organs are complicated. The
male organs are the first to ripen, but this does not appear to prevent
an overlapping of the periods of maturity of the male and female
products, so that when the eggs are being laid, the male organs are,
apparently, still in a functional state. The principal parts are seen in
Fig. 5. The very numerous testes (te) are placed ventrally, and are
connected with fine vasa efferentia (ve), which form a delicate
network opening at various points into the two vasa deferentia (vd).
These tubes, especially when distended with spermatozoa, may
easily be seen (Fig. 2, vd) converging at the base of the penis, and
connected posteriorly by a loop that runs behind the female genital
pore (Fig. 5). The penis (pe) is pyriform and muscular, and is divided
into two chambers, a large upper one for the spermatozoa, and a
smaller lower one for the secretion of a special "prostate" gland. The
apex of the penis is eversible and not merely protrusible, being
turned inside out when evaginated. The ovaries (Fig. 5, ov) are
numerous and somewhat spherical. They are dorsally placed, but
when fully developed extend deeply wherever they can find room to
do so, and they not only furnish the ova, but elaborate food-yolk in
the ova, as there are no special yolk-glands. The slender oviducts
(od) open at several points into the "uterus" (ut) (a misnomer, as no
development takes place within it), which encircles the pharynx, and
opens by a single duct into the vagina (va). Here the ova are
probably fertilised, and one by one invested by the shell-gland (sg)
with a secretion which hardens and forms a resistant shell. They are
then laid in plate-like masses which are attached to stones or shells.
The development is a direct one, and the young Leptoplana, which
hatches in about three weeks, has the outline of a spherical triangle,
and possesses most of the organs of the adult. After leading a
floating life for a few weeks it probably attains maturity in about nine
months.

Classification, Habits, and Structure of the Polycladida.

The Polyclads were so called by Lang on account of the numerous


primary branches of their intestine. They are free-living, purely
marine Platyhelminthes, possessing multiple ovaries, distinct male
and female genital pores (Digonopora), but no yolk-glands. The eggs
are small, and in many cases give rise to a distinct larval form,
known as "Müller's larva" (Fig. 12). The Polyclads, with one
exception,[24] fall into two sub-groups, Acotylea and Cotylea:—

Character. Acotylea. Cotylea.


Sucker A sucker absent.[25] A sucker always present
(Figs. 8, D, s; 7, A, sc).
Mouth In the middle, or In the middle, or in front
behind the middle, of of the middle, of the
the ventral surface. ventral surface.
Pharynx More or less intricately Rarely folded. Usually
folded. cylindrical or trumpet-
shaped.
Tentacles A pair of dorsal A pair of marginal
tentacles usually tentacles (except in
present. Anonymus).
Development Usually direct. Larva Müller's larva present.
when present, not a Metamorphosis,
typical Müller's larva. however, extremely
slight.

Fig. 8 shows that, starting with a member (A, D) of each division, in


which the mouth is almost in the middle of the ventral surface, and
the brain and sense organs somewhat remote from the anterior end,
we find in the Acotylea a series leading to an elongated form
(Cestoplanidae), in which the mouth, pharynx, and genital pores are
far back near the hinder end of the body; while in the Cotylea the
series leads similarly to the elongated Prosthiostomatidae, in which,
however, the pharynx and external apertures are in the front part of
the body. This view of the morphology of the Polyclads is due to
Lang, and is based on the assumption that the more radially-
constructed forms (Fig. 8, A, D) are the primitive ones.

Fig. 7.—Diagrammatic vertical longitudinal sections: A, Of


Prosthiostomum (type of Cotylea); B, of Leptoplana; C, of
Cestoplana (types of Acotylea). (After Lang.) These figures
illustrate the changes which follow the shifting of the mouth from a
central position (B) to either end of the body. br, Brain; dphm,
"diaphragm"; gm, true mouth; lg, openings of lateral gut-branches;
m, mouth; mg, main-gut or stomach; mgbr, median gut-branch;
ph, pharynx; ph.m, aperture in pharyngeal fold; phs,
peripharyngeal sheath; sc, sucker; ♂, male, and ♀, female, genital
aperture.

Fig. 8.—Chief forms of Polycladida: A-C, Acotylea; D-F, Cotylea. A,


Planocera graffii Lang, nat. size; B, Stylochoplana maculata
Stimps, × 7; C, Cestoplana rubrocincta Lang, × 4⁄3; D, Anonymus
virilis Lang, × 3, ventral surface; E, Thysanozoon brocchii Grube,
nat. size; the head is thrown back and the pharynx (ph) is
protruded. F, Prosthiostomum siphunculus Lang, × 3. Br, Brain;
CG, cerebral eye group; DM, true mouth; Ey, marginal eyes; m,
mouth; MG, main-gut or stomach; P, dorsal papillae; Ph, pharynx;
s, sucker (ventral); T, tentacles; UP, dorsal median gut-branch. ♂,
male, and ♀, female, genital aperture, except in D, where ♂ refers
to the multiple penes. (After Lang and Schmidt.)

Classification of Polycladida.

ACOTYLEA.
Family. Genus. British
Representatives.
Planocera (Fig. 8,
Planocera folium
A).
Grube. Berwick-
Imogine.
on-Tweed.
Planoceridae. Conoceros.
Stylochoplana
With dorsal tentacles. Stylochus.
maculata Quatref.
Mouth sub-central. Stylochoplana
Among brown
(Fig. 8, B).
weeds in
Diplonchus.
Laminarian zone.
Planctoplana.
Leptoplana
tremellaris O. F.
Müll.
Discocelis.
L. fallax Quatref.
Leptoplanidae. Cryptocelis.
Plymouth.
Without dorsal Leptoplana.
L. droebachensis
tentacles. Penis Trigonoporus.
Oe. Plymouth
directed backwards. ?Polypostia (see
Sound.
p. 27).
L. atomata O. F.
Müll. Doubtful
species.
Cestoplana (Fig. 8,
Cestoplanidae. C).
No tentacles. Body In Mediterranean
elongated. Penis and on French
directed forwards. side of the
Channel.
Enantiidae.
No sucker. No
tentacles. Main-gut Enantia.
very short. External Adriatic Sea.
apertures as in
Euryleptidae.

COTYLEA.
Anonymidae. Anonymus (Fig. 8,
Mouth central. No D).
tentacles. With two Naples (two
rows of penes. specimens).
Pseudoceridae. Thysanozoon (Fig.
Marginal tentacles 8, E).
folded. Mouth in Pseudoceros.
anterior half. Yungia.
Prostheceraeus
vittatus Mont. On
west coast.
P. argus Quatref.
Guernsey.
Cycloporus
Euryleptidae. papillosus Lang.
Tentacles usually Prostheceraeus. On Ascidians in
present and pointed, Cycloporus. 2-30 fms.
or represented by Eurylepta. Eurylepta cornuta
two groups of eyes. Oligocladus. O.F. Müll. On
Mouth close to Stylostomum. sponges and
anterior end. Aceros. shells, 2-10 fms.
Pharynx cylindrical. Oligocladus
sanguinolentus
Quatref.
O. auritus Clap.
Doubtful.
Stylostomum
variabile Lang.
Prosthiostomatidae.
Tentacles absent.
Body elongated.
Prosthiostomum
Pharynx long,
(Fig. 8, F).
cylindrical. Penis
with accessory
muscular vesicles.
Appearance and Size of Polyclad Turbellaria.—Polyclads are
almost unique amongst animals in possessing a broad and thin,
delicate body that glides like a living pellicle over stones and weeds,
moulding itself on to any inequalities of the surface over which it is
travelling, yet so fragile that a touch of the finger will rend its tissues
and often cause its speedy dissolution. The dorsal surface in a few
forms is raised into fine processes (Planocera villosa), or into hollow
papillae (Thysanozoon brocchii), and in very rare cases may be
armed with spines (Acanthozoon armatum,[26] Enantia spinifera); in
others, again, nettle-cells (nematocysts) are found (Stylochoplana
tarda, Anonymus virilis). Some Polyclads, especially the pelagic
forms, are almost transparent; in others, the colour may be an
intense orange or velvety black, and is then due to peculiar deposits
in the epidermal cells. Between these two extremes the colour is
dependent upon the blending of two sources, the pigment of the
body itself and the tint of the food. Thus a starved Leptoplana is
almost or quite white, a specimen fed on vascular tissue reddish.
Many forms are coloured in such a way as to make their detection
exceedingly difficult, but this is probably not merely due, as Dalyell
supposed, to the substratum furnishing them with food and thus
colouring them sympathetically, but is probably a result of natural
selection.

The largest Polyclad, the bulkiest Turbellarian, is Leptoplana gigas


(6 inches long and 4 in breadth), taken by Schmarda, free-
swimming, off the coast of Ceylon. The largest European form is
Pseudoceros maximus, 3½ inches in length and stoutly built. A
British species, Prostheceraeus vittatus, attains a length of from 2 to
3 inches. These large forms, especially the Pseudoceridae (pre-
eminently the family of big Polyclads), are brightly coloured, and
usually possess good swimming powers, since, being broad and flat,
they are certainly not well adapted for creeping rapidly, and this is
well shown by the way these Polyclads take to swimming when in
pursuit of prey at night. The size of any individual is determined,
amongst other factors, by the period at which maturity sets in, after
which probably no increase takes place. Polyclads apparently live
about twelve months, and mature specimens of the same species
vary from ½ inch to 2½ inches in length (Thysanozoon brocchii),
showing that growth is, under favourable conditions, very rapid.

Habits of Polyclad Turbellaria.—Polyclads are exclusively marine,


and for the most part littoral, animals. Moreover, there is no evidence
of their occurrence in those inland seas where certain marine
animals (including one or two species of otherwise characteristically
marine Rhabdocoelida, p. 46) have persisted under changed
conditions. From half-tide mark down to 50 fathoms, some Polyclads
probably occur on all coasts, but as to their relative abundance in
different seas we have very little accurate information. The southern
seas of Europe possess more individuals and species than the
northern, and probably the maximum development of the group
takes place on the coasts and coral islands of the tropics.[27] No
Polyclads have been taken below 60 fathoms; but their delicacy and
inconspicuousness render this negative evidence of little value. Six
truly pelagic forms, however, are known,[28] and these are interesting
on account of their wide distribution (three occurring in the Atlantic,
Pacific, and Indian oceans), and also from the distinct modifications
they have undergone in relation to their pelagic existence.

Whatever may be the interpretations of the fact, Polyclads are


notoriously difficult to detect, and this fact doubtless explains the
scanty references to them by the older naturalists who collected
even in tropical seas. Lang, who worked seven years at Naples,
added to the Mediterranean fauna as many Polyclads as were
previously known for all Europe, in spite of the assiduous labours of
his predecessors, Delle Chiaje and Quatrefages. Again Hallez,
collecting at Wimereux at low-water, obtained some twenty
specimens of Leptoplana tremellaris in an hour, while some other
collectors working by his side could only find two or three. Yet, even
making allowance for the difficulty of finding Polyclads, few of them
appear to be abundant.

Leptoplana tremellaris is frequently associated with colonies of


Botryllus, and if separated soon perishes, whereas the free-living
individuals are distinctly hardy (Hallez). A closely allied but possibly
distinct form lives upon the surface of the Polyzoon Schizoporella, on
the French side of the Channel, and cannot long endure separation
from its natural habitat, to which it is adaptively coloured. A striking
case of protective mimicry is exhibited by Cycloporus papillosus, on
the British coasts. This species, eminently variable in colour and in
the presence or absence of dorsal papillae, is usually a quarter of an
inch in length and of a firm consistency. Fixed by its sucker to
Polyclinid and other Ascidians, Cycloporus appears part and parcel
of the substratum, an interesting parallel to Lamellaria perspicua,[29]
though we are not justified in calling the Polyclad parasitic. Indeed,
though a few cases of association between Polyclads and large
Gasteropods, Holothurians, and Echinids are known,[30] there is only
one case, that of Planocera inquilina,[31] in the branchial chamber of
the Gasteropod Sycotypus canaliculatus, which would seem to bear
the interpretation of parasitism. The jet-black Pseudoceros velutinus
and the orange Yungia aurantiaca of the Mediterranean, are large
conspicuous forms with no attempt at concealment, but their taste,
which is not known, may protect them. Other habits, curiously
analogous with devices employed by Nudibranch Mollusca (compare
Thysanozoon brocchii with Aeolis papillosa), emphasise the
conclusion that the struggle for existence in the littoral zone has
adapted almost each Polyclad to its particular habitat.

As regards the vertical distribution of this group on the British coasts,


Leptoplana tremellaris has an extensive range, and appears to come
from deeper to shallower water to breed.[32] In the upper part of the
Laminarian zone, Cycloporus papillosus, and, among brown weeds,
Stylochoplana maculata are found. At and below lowest water-mark
Prostheceraeus vittatus, P. argus, and Eurylepta cornuta occur.
Stylostomum variabile and Oligocladus sanguinolentus, though
occasionally found between tide-marks, especially in the Channel
Islands, are characteristic, along with Leptoplana droebachensis and
L. fallax, of dredge material from 10 to 20 fathoms.
Locomotion.—Locomotion is generally performed by Polyclads at
night when in search of food, and two methods, creeping and
swimming, are usually employed—creeping by the cilia, aided
possibly, as in the case of some Gasteropod Mollusca, by the
longitudinal muscles of the ventral surface; and swimming, by
undulations of the expanded margins of the body. In the former case
the cilia work in a glandular secretion which bathes the body, and
enables them to effect their purpose equally well on different
substrata. The anterior region is generally lifted up, exploring the
surroundings by the aid of the tentacles, which are here usually
present. The rest of the body is closely appressed to the ground.

Swimming is particularly well performed by the Pseudoceridae,


certain species of Prostheceraeus, the large Planoceridae, some
Stylochoplana, Discocelis, and Leptoplana, and in the same manner
as in Leptoplana tremellaris (p. 9). In Cryptocelis, Leptoplana alcinoi,
and L. pallida, however, the whole body executes serpentine
movements like an active leech (e.g. Nephelis); a cross section of
the body would thus present the same appearance during the whole
movement. Many Polyclads, notably Anonymus (Lang), if irritated,
spread out in all directions, becoming exceeding thin and
transparent.

Fig. 9.—Discocelis lichenoides Mert. (after Mertens), creeping on the


inner side of a glass vessel by means of the lobes of the extended
and exceedingly mobile pharynx (ph). These lobes also serve to
enclose Crustacea (a), and one lobe may then be withdrawn
independently of the rest, back into the body (b). The brain (br)
and shell-gland (sg) are shown by transparency.
Discocelis lichenoides, Planocera graffii, and Anonymus virilis have
peculiar modes of progression. The first, according to Mertens, will
climb up the sides of a vessel by means of the expanded lobes of
the pharynx (Fig. 9, ph), a habit of considerable interest, since we
know that certain Ctenophores—Lampetia, for instance—progress
when not swimming on the expanded lobes of their "stomach."[33]
Planocera and Anonymus creep by extending parts of the anterior
margin and dragging the rest of the body behind. In consequence,
the brain and dorsal tentacles may come to lie actually behind the
middle of the body, and thus no definite anterior end or "head"
advances first. Along with this curious habit it may be noticed (Lang)
that the radial symmetry of the body is well marked; but even without
accepting this author's suggestion of the concurrent development of
a "head" with locomotion in a definite direction, the facts, whether
these two forms are primitive or not, are highly interesting.

Food.—Though we are probably right in calling Polyclads a


carnivorous group, the food of very few forms has been ascertained.
Those which possess a large frilled pharynx (most Acotylea)
probably enclose and digest large, and, it may be, powerful prey, as
appears to be the case in Leptoplana tremellaris. Cryptocelis alba
has been seen by Lang with the pharynx so distended, owing to a
large Drepanophorus (Nemertine) which it contained, as to resemble
a yolk-sac projecting from the under surface of an embryo. The
Cotylea such as Thysanozoon, with a bell- or trumpet-shaped
pharynx, are fond of fixing this to the side of the aquarium, but
whether they thus obtain minute organisms is not clear.
Prosthiostomum shoots out its long pharynx with great vehemence
(Fig. 8, F) and snaps up small Annelids by its aid (Lang). Those
Polyclads which, as Cycloporus and others, are definitely associated
with other organisms are not certainly known to feed upon the latter,
though "Planaria velellae" has been seen by Lesson[34] devouring
the fleshy parts of its host. The salivary glands which open on the
lips and the inner surface of the pharynx powerfully disintegrate the
flesh of the prey. Digestion takes place in the main-gut, and the
circulation of the food is accomplished by the sphinctral musculature
of the intestinal branches (conf. Leptoplana, p. 13).

Fig. 10.—Diagram of the musculature, causing peristaltic movements


of the intestinal branches of Polyclads. (After Lang.)

A distinct vent or anus is always absent. After a meal the faecal


matter collects in the main-gut, and is discharged violently by the
pharynx into the water. In a few species, however, the intestinal
branches open to the exterior (Lang). Yungia aurantiaca, a large and
abundant Neapolitan form, possesses such openings over the
greater part of the dorsal surface; Cycloporus papillosus has
marginal pores; Oligocladus sanguinolentus apparently possesses
an opening at the posterior end of the main-gut; and Thysanozoon
brocchii frequently rends at this point, in consequence of the
accumulation of food.

Respiration.—The oxygen of the atmosphere dissolved in the sea-


water is, in default of a special circulatory fluid, brought to the tissues
of Polyclads in two ways. The ciliated epidermis provides a constant
change of the surrounding water, by which the superficial organs
may obtain their supply; and the peristaltic movements of the
digestive system, aided by the cilia of the endoderm cells, ensure a
rough circulation of the sea-water, which enters along with the food,
to the internal organs. The papillae of Thysanozoon brocchii,
containing outgrowths of the intestinal branches, are possibly so
much additional respiratory surface, although still larger forms (other
Pseudoceridae) are devoid of such outgrowths.

Excretion.—The excretory system of only one Polyclad


(Thysanozoon brocchii) is accurately known. Lang, by compressing
light-coloured specimens, found the three parts of the system known

You might also like