TEAM LinG Linux Shell Scripting with Bash TEAM LinG Linux Shell Scripting with Bash Sams Publishing, 800 East 96th Street, Indianapolis, Indiana 46240 DEVELOPER’S L IBRARY Ken O. Burtch Linux Shell Scripting with Bash Copyright © 2004 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein.Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omis- sions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-32642-6 Library of Congress Catalog Card Number: 2003112582 Printed in the United States of America First Printing: February 2004 07060504 4321 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied.The infor- mation provided is on an “as is” basis.The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book. Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com For sales outside of the U.S., please contact International Sales 1-317-428-3341 international@pearsontechgroup.com Acquisitions Editor Scott Meyers Managing Editor Charlotte Clapp Project Editor Elizabeth Finney Copy Editor Kezia Endsley Indexer Ken Johnson Proofreader Leslie Joseph Technical Editor John Traenkenschuh Publishing Coordinator Vanessa Evans Multimedia Developer Dan Scherf Designer Gary Adair Page Layout Brad Chinn Susan Geiselman ❖ To F. Ray Skilton Professor and Author Who taught me more about computers over tea than I ever learned in a lecture hall. ❖ Contents at a Glance Introduction 1 1 The Linux Environment 7 2 Operating the Shell 13 3 Files, Users, and Shell Customization 27 4 Script Basics 51 5 Variables 67 6 Expressions 87 7 Compound Commands 115 8 Debugging and Version Control 125 9 Parameters and Subshells 145 10 Job Control and Signals 157 11 Text File Basics 169 12 Text File Processing 207 13 Console Scripting 233 14 Functions and Script Execution 249 15 Shell Security 267 16 Network Programming 281 17 Data Structures and Databases 301 18 Final Topics 319 A Complete Example 337 B Summary of Bash Built-In Commands 355 C Bash Options 357 D Error Codes 361 E Signals 365 F ASCII Table 367 Glossary 371 Index 375 Table of Contents 1 The Linux Environment 7 The Origin of Linux 7 Files and File Systems 8 Directories 9 Inodes and Links 10 Pipe and Socket Files 11 Device Files 11 2 Operating the Shell 13 Bash Keywords 13 Command Basics 13 Command-Line Editing 15 Variable Assignments and Displaying Messages 17 Multiple Commands 18 Command History 19 Directory Commands 21 Specialized Navigation and History 23 The Colon Command 24 Reference Section 24 date Command Switches 24 stty Command Switches 24 history Command Switches 25 pwd Command Switches 25 dirs Command Switches 25 3 Files, Users, and Shell Customization 27 Listing Files 27 printf Command 28 Getting Help 31 Fixing the Display 32 Working with Files 32 viii Contents Working with People 35 Shell Aliases 36 The Bash Hash Table 36 Customizing Your Prompt 37 Long Command Lines 39 Customizing Command-Line Editing 39 Your Session Profile 42 Reference Section 45 ls Command Switches 45 printf Formatting Codes 47 printf Backslash Codes 47 rm Command Switches 48 cp Command Switches 48 mv Command Switches 49 4 Script Basics 51 Creating a Script 51 Creating a Well-Behaved Script 52 The Header 53 Global Declarations 54 Sanity Checks 54 The Main Script 55 Cleanup 55 Stopping a Script 57 Reading Keyboard Input 57 Basic Redirection 58 Standard Output, Error, and Input 60 Built-In Versus Linux Commands 62 The Set and Shopt Commands 63 Reference Section 64 command Command Switches 64 enable Command Switches 64 read Command Switches 64 suspend Command Switches 65 ix Contents 5 Variables 67 Variable Basics 67 Predefined Variables 69 The Effect of Quotations 70 Variable Attributes 73 Arrays 74 Exporting Variables and the Linux Environment 76 The eval Command 78 story.bash:A Story Generator 80 Reference Section 82 Declare Command Switches 82 Bash Predefined Variables 82 6 Expressions 87 Expansions 87 The Basic if Command 88 File Expressions 89 Multiple Tests 90 Strings 92 Arithmetic Expressions 93 Logical Expressions 95 Relational Operations 96 Bitwise Operations 96 Self-Referential Operations 97 Other let Features 98 temperature.bash: Converting Fahrenheit to Celsius 99 Arithmetic Tests 100 Pattern Recognition 101 Globbing Options 104 Filename Brace Expansion ( { } ) 104 Dollar Sign Substitutions 105 ANSI C Escape Expansion ($’) 105 Locale Translation ($”) 105 [...]... by the Linux operating system.The shell was called Bash (for the pun “Bourne Introduction Again Shell ).This shell was compatible with the original shell created by Steven R Bourne, but included many enhancements It was also compliant with the POSIX standard for shells Bash is the standard shell provided with most Linux distributions, including Red Hat, SuSE, Mandrake, Slackware, and UnitedLinux When... Use the —prefix option with configure to specify the directory to install Bash in For example, —prefix=$HOME or — prefix=$HOME /bash might be good choices Bash and Other Scripting Tools Ksh, Perl, and Python are similar, but not identical, to Bash The Korn shell (ksh) is an enhanced version of the Bourne shell A public domain version exists called pdksh Korn shell is a popular shell on many commercial... common successors were csh, a shell loosely based on the C language, and the Korn shell (ksh), an improved Bourne shell developed by David G Korn Shell designers incorporated commands into the shell for better speed and portability and to make the shells easier to work with Successful features were freely copied between shells as they matured An enhanced version of the Bourne shell was developed as part... Korn shell s features work under Bash Both shells can do bitwise arithmetic, for example Some features have different names.The Korn shell built-in print command is a rough equivalent to the Bash printf command, and the Korn shell whence command is equivalent to the type command A complete list of differences and porting issues is available in the Bash FAQ at http://www.faqs.org/faqs/unixfaq /shell/ bash/ ... A command that works with one form of quotation can suddenly stop working when different data appears in the quotes Issues like shell word quoting, specialized capabilities, or portability features, when abused, can lead to increased maintenance and long-term development costs Installing Bash Bash is the standard shell on most Linux distributions However, there are other Linux shells available and... compile Bash 2 Run make to build Bash 3 Run make tests.This will run diagnostic tests to ensure Bash was built properly 4 Run make install to install Bash under the /usr/local/ subdirectory Introduction Assuming your PATH variable is set correctly, you can start Bash by typing bash at the shell prompt If you do not have superuser privileges on your computer, you can still compile and install Bash under... Control Shell Debugging Features 125 Debug Traps 128 Version Control (CVS) 129 Creating Transcripts 133 125 Contents Watching Running Scripts 134 Timing Execution with Time 134 Creating Man Pages 136 Source Code Patches 139 Shell Archives 141 Reference Section 141 tee Command Switches 141 Linux Time Command Switches 142 Bash Time Command Format Codes 142 Linux Time Command Format Codes 142 Shell Debugging... bookshelf, there’s good reason for it and a lot of good people behind it In the summer of 1999, I talked with Michael Slaughter at Addison-Wesley publishing about writing a series of Linux books Because Linux begins with Bash, Bash would be the topic of my first book So if you’ve been dying for a good Bash book, thank Michael Lawrence Law, a Unix programmer who’s worked both sides of the Pacific, offered... suggests, a scripting language for generating reports It combines the features of a shell language, the sed command, and the awk command to create a single tool It is not a shell and Perl scripts are not compatible with Bash Python (named after the “Monty Python” comedy troupe) is an interpreted language designed for small projects needing rapid development It is not a shell, but like Bash, it contains... short form of “teletypewriter,” a printer and keyboard connected to a computer by a cable With this overview of the Linux philosophy, you are ready to begin using Linux through the Bash shell 2 Operating the Shell O NE DAY MY FATHER WAS WORKING on the electrical wiring on his pontoon boat He worked for several hours without success No matter what he tried, he couldn’t get his running lights to work Frustrated, . LinG Linux Shell Scripting with Bash TEAM LinG Linux Shell Scripting with Bash Sams Publishing, 800 East 96th Street, Indianapolis, Indiana 46240 DEVELOPER’S L IBRARY Ken O. Burtch Linux Shell Scripting. it. In the summer of 1999, I talked with Michael Slaughter at Addison-Wesley publish- ing about writing a series of Linux books. Because Linux begins with Bash, Bash would be the topic of my first. 301 Associative Arrays Using Bash Arrays 301 Hash Tables Using Bash Arrays 305 Binary Trees Using Bash Arrays 309 Working with PostgreSQL Databases (psql) 313 Working with MySQL Databases 316 Reference