Home > Store

Portable Shell Programming: An Extensive Collection of Bourne Shell Examples

Register your product to gain access to bonus material or receive a coupon.

Portable Shell Programming: An Extensive Collection of Bourne Shell Examples

Book

  • Sorry, this book is no longer in print.
Not for Sale

About

Features

  • focuses on shells that are portable, known as Bourne Shells.
  • provides over 250 major shell examples that show most of the common tasks of shell programmers.
  • contains several complete shell scripts, described on a line-by-line basis, that can be used as templates.
  • offers solutions for coding practices that frequently cause problems.

Description

  • Copyright 1996
  • Dimensions: 7" x 9-1/4"
  • Pages: 296
  • Edition: 1st
  • Book
  • ISBN-10: 0-13-451494-7
  • ISBN-13: 978-0-13-451494-9

Traditionally, books on shell programming present the shell as the user interface to UNIX. This complete guide shows how to use the shell to develop shell scripts, using the shell more like a programming language than a command interpreter. KEY TOPICS: Covers shell syntax, portability on different UNIX systems, using shell scripts to catch or ignore signals, executing commands using the remote shell command, and using the shell's redirection syntaxes. MARKET: For software development engineers, system administrators, and QA test engineers who work with UNIX computer systems.

Sample Content

Table of Contents



 1. Shell Syntax.


 2. Shell Variables.


 3. Shell Functions and Built-in Commands.


 4. Using Files.


 5. The Environment.


 6. Parsing Command Line Parameters.


 7. Using Filters.


 8. Shell Utilities.


 9. Examples of Shell Functions.


10. Examples of Shell Scripts.


11. Debugging.


12. Portability.


13. Common Questions and Problems.


Appendix A. Comparison of UNIX Shells.


Appendix B. Syntax Summary.

Preface

The most frequently asked question in shell programming is:

Where can I find examples of shell scripts?

Most engineers find that the easiest way to learn shell programming is to learn from the examples of others. Similarly, the easiest way to write a shell script is to use an existing shell script as a template. This stems from the fact that there are innumerable commands and techniques that can be used to solve any particular problem. Seeing an example helps you sift through the chaff to get to a solution quickly. Oftentimes shell programming is used to solve a short-term problem, and, therefore, it is important to get something working quickly; the task might not be worth doing if it requires a significant amount of learning or trial and error to come up with a solution.

Seeing examples also helps you to remember the peculiarities of the shell syntax and the idiosyncrasies of the UNIX commands. Since writing shell scripts is not an everyday task for most engineers, it is easy to forget those infrequently used details. It is usually easier to modify a shell script that contains many of the ideas that you need than it is to develop a new shell script from scratch.

Shell programming is too useful to avoid simply because you find the syntax difficult to remember or the number of UNIX commands overwhelming. Besides executing simple commands such as echo, date, cp, and so forth, the shell defines a command language e that allows you to combine commands into complex shell scripts. The shell supports variables, control flow statements (such as if, while, and for), functions, parameter passing, and even interrupt handling. Coupling the capabilities of the shell with the wide variety of commands available on UNIX, very powerful shell scripts can be written in just a few lines. In addition, since the shell is an interpretive language, there is no compiling or linking to worry about. You can create simple and powerful shell scripts in just a few minutes.

When I first began to write shell scripts, I found it difficult to find useful examples of shell scripts, and when I did find them, they were often difficult to understand. To this end, I believe it is useful to have a reference of relevant, well-doc umented examples, which is what I have tried to provide in this book. I have also tried to provide enough variety in the examples and their explanations that you will become familiar with many of the common practices used in writing shell scripts, an d, therefore, it will be easier for you to understand the code in other shell scripts that you find. This is not a book on how to use UNIX, as most books on shell programming are. This book is intended for people who are already familiar with UNIX and, for one reason or another, have decided to write a shell script. This book is intended for people who already know what an if statement is, but they do not know or cannot remember how an if statement is implemented in the shell. If they could just see an example, they would be off and programming. The examples in this book cover everything from simple shell statements to complex shell scripts, and unlike most books on shell programming, this book contains examples that you are likely to use.

This book is intended to be useful as a reference book. The style of presentation is straightforward. Each topic is self-contained, which allows you to skip directly to the information that you are interested in. This book provides an extensive collection of examples that are organized and indexed so that you have a ready reference to a wide variety of shell programming tasks. If you choose to read the book from cover to cover, you will be exposed to a variety of techniques and practices that would normally take you years to discover.

All of the examples in the book are written using the standard Bourne shell1 (sh or /bin/sh), which allows these examples to be used on any UNIX system. While there are several shells to choose from on most UNIX systems, and many of them are more suitable table than the Bourne shell for interactive work, the standard Bourne shell is available on all modern UNIX systems, and therefore, is the most common choice for writing shell scripts. In addition, the Korn shell and the POSIX shell contain all of the e syntactic constructs of the Bourne shell, which makes the examples in this book compatible with those shells as well. Some of the examples in this book have dependencies on the flavor of UNIX (e.g., System V or BSD) and some of the examples are dependent upon the particular implementation of a command by the vendor, but these dependencies are explained in the text, and in each case a portable solution is shown. This makes the examples in this book especially useful to those who write shell scripts that must execute on more than one type of UNIX system.

When reading this book, it is important to remember that there are many ways to perform most tasks on UNIX systems. I have chosen implementations for the examples in this book that are easy to understand, but not necessarily the most efficient solution on, or in some other way, the most desirable solution. I will sometimes comment on alternatives, but for the most part, I leave it up to you to determine when an example from this book should be altered for your particular situation.

There is no warranty of any kind on the examples in this book. I have tested each example on several different UNIX systems, but because of the wide variety of UNIX systems and configurations available, it is possible that some examples will not work exactly as I have indicated. I welcome any comments that you might have about the content of this book, including problems with examples and suggestions for improvements.

How This Book Is Organized

The first four chapters in this book describe the syntax of the Bourne shell.

Chapter 1, "Shell Syntax," begins by introducing you to the basic syntax of the Bourne shell. This chapter describes simple commands, quotes and quoting, file name expansion n, and control flow statements.

Chapter 2, Shell Variables, continues the presentation of shell syntax. It describes how to assign values to variables, how to retrieve those values, variable initialization techniques, and variables that are built into the shell.

Chapter 3, Shell Functions and Built-in Commands, presents the syntax for shell functions and discusses techniques for using them. This chapter also lists the commands that are built into the shell and gives a brief description of each one.

Chapter 4, Using Files, presents the shell syntax for input-output redirect. It shows a variety of examples that use the shell redirection syntax to redirect the standard input and the standard output of commands, and it also discusses how to use the shell redirection syntax to read and write other files.

Chapter 5, The Environment, describes the process environment and how it affects shell scripts. This chapter discusses how parent and child processes can affect each other, how signals can be used in shell scripts, and it presents a variety of examples on how to execute commands on remote systems.

Chapter 6, Parsing Command Line Parameters, explains the conventions used to pass parameters to shell scripts and presents examples of common techniques that are used to parse the command line parameters.

Chapter 7, Using Filters, explains what a filter is, how to write one, and how they are used. This chapter contains many examples of filters that can be used to process text files.

Chapter 8, Shell Utilities, has examples of how to perform many common tasks that are frequently used in larger shell scripts. This chapter covers such things as doing arithmetic, manipulating strings, manipulating files and directories, asking questions, presenting output, and much more.

Chapter 9, Examples of Shell Functions, has examples of complete shell functions. These functions demonstrate a variety of reasons to use shell functions, and each function in this chapter contains a line-by- line explanation describing exactly how the function works.

Chapter 10, Examples of Shell Scripts, has examples of complete shell scripts. Each example is complete with comments and demonstrates good shell programming practices. Each shell script in this chapter contains a line-by-line explanation describing exactly how the shell script works

Chapter 11, Debugging, describes the debugging options in the shell and other techniques that are useful for debugging shell scripts. This chapter also describes a variety of common problems and unusual coding styles that can lead to errors.

Chapter 12, Portability, explains the most common issues surrounding the portability of shell scripts and how to avoid portability problems. This chapter also discusses some of the portability issues that arise with specific UNIX commands.

Chapter 13, Common Questions and Problems, is structured as a question and answer discussion. It explains many of the problems that inexperienced users are likely to encounter, and it answers many of the questions they are likely to ask.

Appendix A, Comparison of UNIX Shells, provides a brief description of each of the major shells available on UNIX systems

Appendix B, Syntax Summary, is a complete but brief summary of the syntax of the Bourne shell.

Conventions Used in this Book

To differentiate the text of the explanations in this book from the examples of shell code, typewriter font is used to represent the examples of shell code. Typewriter font is also used to indicate command names, file names, or anything else that must t be entered literally as it is shown in the text.

echo Hello world.

Text in italics is used to indicate text that should be replaced with an appropriate value rather than entering the text literally as it is shown.

rm file
When expressing command syntax, square brackets () indicate an optional entry, a vertical bar (|) separates multiple selections, and ellipses (...) indicate that the previous entry may be repeated.

cp file1 file2 ... target
Nonprinting characters are represented by the name of the character in italics and surrounded by angle brackets. This notation is only used where the additional clarity is necessary.


Even though this book does not cover using the shell instructively, it is frequently useful to use the shell interactively to test new ideas. Some of the examples in this book are presented this way. These examples will use the dollar sign ($) as the shell prompt and the greater than sign (>) as the prompt for continuation lines.

$ if command
> ...
> fi
$

Software Included with this Book

Many of the examples in this book are complete, ready-to-use shell scripts. These examples (which include all of the examples in Chapter 9, Examples of Shell Functions, and Chapter 10, Examples of Shell Scripts) are contained on the floppy diskette attached to this book and they are also available electronically from the Prentice Hall FTP server.

The files on the floppy diskette are stored as a tar archive. To extract the files from the floppy diskette, enter the following command:

tar -xvf device

Where device is the name of the floppy diskette device on your system (for example, /dev/fd0). This command will create a subdirectory named shbook that contains the examples from this book. To obtain the examples electronically from the Prentice Hall FTP server, you can use the ftp command to connect to ftp.prenhall.com. The files are contained in the compressed, tar archive file /pub/blinn/shbook.tar.Z. The following example shows a sample dialog to obtain this file from the Prentice Hall FTP server. The underlined text is the portion of the dialog that you enter, the remainder of the text is the information displayed by the ftp command.

$ ftp ftp.prenhall.com
Connected to ... 220 ... FTP server (...) ready.
Name (ftp.prenhall.com:username): anonymous 331 Guest login ok, send ident as password.
Password: username@xxx.xxx.xxx (Your user name and full host name; it will not echo) 230 Guest login ok, access restrictions apply.
ftp> cd /pub/blinn 250 CWD command successful.
ftp> binary 200 Type set to I.
ftp> get shbook.tar.Z 200 PORT command successful.
150 Binary data connection for shbook.tar.Z (n.n.n.n,n) (n bytes).
226 Transfer complete.
n bytes received in n.n seconds (n.n Kbytes/s)
ftp> quit
221 Goodbye
$

After executing this command, the file shbook.tar.Z should be in the current directory. To unpack this file, enter the following commands: uncompress shbook.tar.Z tar -xvf shbook.tar

This will create a subdirectory named shbook that contains the examples from this book.

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020