Mastering UNIX Shell Scripting

Similar documents
Linux Command Line and Shell Scripting Bible

7 Windows Tweaks. A Comprehensive Guide to Customizing, Increasing Performance, and Securing Microsoft Windows 7. Steve Sinchak

Beginning Web Programming with HTML, XHTML, and CSS. Second Edition. Jon Duckett

Beginning Transact-SQL with SQL Server 2000 and Paul Turley with Dan Wood

Join the p2p.wrox.com. Wrox Programmer to Programmer. Beginning PHP 5.3. Matt Doyle

Linux Command Line and Shell Scripting Bible. Third Edtion

Linux. The book you need to succeed! Boot up to Ubuntu, Fedora, KNOPPIX, Debian, opensuse, and 13 Other Distributions Edition.

Professional ASP.NET 2.0 Databases. Thiru Thangarathinam

Implementing Security and Tokens: Current Standards, Tools, and Practices

Study Guide. Robert Schmidt Dane Charlton

Securing SCADA Systems. Ronald L. Krutz

MCITP Windows Server 2008 Server Administrator Study Guide

XSLT 2.0 and XPath 2.0

Agile Database Techniques Effective Strategies for the Agile Software Developer. Scott W. Ambler

OpenSolaris. The book you need to succeed! Nicholas A. Solter, Gerald Jelinek, and David Miner. Explore the OpenSolaris operating environment

Real-Time Optimization by Extremum-Seeking Control

Oracle PL/SQL. DUMmIES. by Michael Rosenblum and Dr. Paul Dorsey FOR

iwork DUMmIES 2ND EDITION FOR

Linux Command Line and Shell Scripting Bible

Hands-On Oracle Application Express Security

Ruby on Rails. Bible

Cloud Phone Systems. Andrew Moore. Making Everything Easier! Nextiva Special Edition. Learn:

MacBook Air PORTABLE GENIUS

PHP & MySQL. Learn to: Janet Valade. Making Everything Easier! 4th Edition. Create well-formed PHP code that s compliant with PHP 4, 5, and 6

FileMaker. Pro 10. The book you need to succeed! Companion Web Site. Ray Cologon. Go from basics to full-scale development

Windows. 7 Desktop Support and Administration. Real World Skills for MCITP Certification and Beyond. Darril Gibson

Blade Servers and Virtualization. Barb Goldworm Anne Skamarock. Transforming Enterprise Computing While Cutting Costs. Wiley Publishing, Inc.

Flash Lite. Mobile Development. Professional. Build Flash Applications for Mobile Devices. Jermaine G. Anderson. Join the p2p.wrox.

Creating Web Pages. Learn to: Bud E. Smith. Making Everything Easier! 9th Edition. Design, build, and post a Web page

MCTS. Microsoft Windows 7 Configuration STUDY GUIDE. William Panek. Covers All Objectives for Exam Exam

LEGITIMATE APPLICATIONS OF PEER-TO-PEER NETWORKS DINESH C. VERMA IBM T. J. Watson Research Center A JOHN WILEY & SONS, INC., PUBLICATION

Professional Windows PowerShell Programming

COSO Enterprise Risk Management

HASHING IN COMPUTER SCIENCE FIFTY YEARS OF SLICING AND DICING

LEGITIMATE APPLICATIONS OF PEER-TO-PEER NETWORKS

Practical Database Programming with Visual Basic.NET

Google Voice. Learn to: Bud E. Smith Chris Dannen. Making Everything Easier! Set up and use Google Voice

Microprocessor Theory

TASK SCHEDULING FOR PARALLEL SYSTEMS

Microsoft Office Simply the Easiest Way to Learn. Kate Shoup

Hacking Gmail. Ben Hammersley

Microsoft SQL Server 2008 Integration Services

DIFFERENTIAL EQUATION ANALYSIS IN BIOMEDICAL SCIENCE AND ENGINEERING

COMPONENT-ORIENTED PROGRAMMING

SQL Server Administration. Beginning Microsoft. Chris Leiter, Dan Wood, Michael Cierkowski, Albert Boettger

Join the p2p.wrox.com. Wrox Programmer to Programmer. Professional ASP.NET 4. in C# and VB. Bill Evjen, Scott Hanselman, Devin Rader

Modern Experimental Design

Richard Wentk. Cocoa. Developer Reference.

Beginning Visual Basic 2015

Relational Database Index Design and the Optimizers


Shell Programming for System Administrators Student Guide

J2EE TM Best Practices Java TM Design Patterns, Automation, and Performance

WINDOWS 10. by Paul McFedries

Algorithms and Parallel Computing

Mastering BEA WebLogic Server Best Practices for Building and Deploying J2EE Applications

Professional Java Native Interfaces with SWT/JFace. Jackwind Li Guojie

MODERN MULTITHREADING

Microsoft. Access by Paul McFedries

IP MULTICAST WITH APPLICATIONS TO IPTV AND MOBILE DVB-H

Fedora 8 and Red Hat Enterprise Linux Bible


Windows 10 Anniversary Update. Paul McFedries

Dreamweaver CS4. A Complete Training Package! Adobe. Full-color, step-by-step instructional book Video training from Adobe Certified Experts

Office 2010 For Seniors

PROFESSIONAL SCALA. INTRODUCTION... xv


ASP.NET 3.5 SP1. In C# and VB. Professional. Covers. Service Pack 1. Bill Evjen, Scott Hanselman, Devin Rader

Making Everything Easier! Windows 7. Pick the task, Find it fast, Get it DONE! Nancy Muir

Exploiting Distributed Resources in Wireless, Mobile and Social Networks Frank H. P. Fitzek and Marcos D. Katz

Multi-Core Programming

Microsoft. Excel. Paul McFedries

Implementing 802.1X Security Solutions for Wired and Wireless Networks. Jim Geier

Microsoft Virtualization SECRETS

ASP.NET MVC 1.0. Website Programming. Nick Berardi, Al Katawazi, Marco Bellinaso. Wrox Programmer to Programmer TM


IC Internet and Computing Core Certification Living Online. Study Guide

Acrobat PDF. Adobe. The book you need to succeed! Standard, Pro, and Pro Extended Version. CD-ROM Included! Ted Padova

Join the p2p.wrox.com. Wrox Programmer to Programmer. Beginning. Python. Using Python 2.6 and Python 3.1. James Payne

Networking. 11th Edition. by Doug Lowe

Beginning Visual Basic 2005 Databases. Thearon Willis

Wrox Programmer to Programmer TM. Professional. Design Patterns. Aaron Saray PHP. Updates, source code, and Wrox technical support at

THE ARCHITECTURE OF COMPUTER HARDWARE, SYSTEM SOFTWARE, AND NETWORKING

FUZZY LOGIC WITH ENGINEERING APPLICATIONS

COMPUTATIONAL DYNAMICS

PowerShell, VBScript, JScript

CliffsStudySolver Geometry. By David Alan Herzog

CISSP. DUMmIES 4TH EDITION FOR

OS X El CapitanTM. Paul McFedries

ASUS Eee PC. DUMmIES. by Joel McNamara FOR

Network Performance Open Source Toolkit Using Netperf, tcptrace, NIST Net, and SSFNet

Multi-Core Programming

Backlink To. Fast track your traffic with Simple Strategies

IC Internet and Computing Core Certification Computing Fundamentals. Study Guide

OVER 750 QUESTIONS AND 55 TASK-BASED SIMULATIONS! CPA EXAM REVIEW. Auditing and Attestation. O. Ray Whittington, CPA, PhD Patrick R.

macos Sierra Paul McFedries

BEGINNING CSS PART I THE BASICS PART II PROPERTIES PART III ADVANCED CSS AND ALTERNATIVE MEDIA

MacBook Pro. PORTABLE GENIUS 5th EDITION

UNIX System Administration

Excel 2016 Formulas. Michael Alexander Dick Kusleika

Transcription:

Mastering UNIX Shell Scripting Bash, Bourne, and Korn Shell Scripting for Programmers, System Administrators, and UNIX Gurus Second Edition Randal K. Michael Wiley Publishing, Inc.

Mastering UNIX Shell Scripting Second Edition

Mastering UNIX Shell Scripting Bash, Bourne, and Korn Shell Scripting for Programmers, System Administrators, and UNIX Gurus Second Edition Randal K. Michael Wiley Publishing, Inc.

Mastering UNIX Shell Scripting: Bash, Bourne, and Korn Shell Scripting for Programmers, System Administrators, and UNIX Gurus, Second Edition Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright 2008 by Randal K. Michael Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-18301-4 Manufactured in the United States of America 10987654321 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002. Library of Congress Cataloging-in-Publication Data is available from publisher. Trademarks: Wiley, the Wiley logo, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. UNIX is a registered trademark of The Open Group. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

This book is dedicated to my wife Robin, the girls, Andrea and Ana, and the grandchildren, Gavin, Jocelyn, and Julia my true inspiration.

About the Author Randal K. Michael is a UNIX Systems Administrator working as a contract consultant. He teaches UNIX shell scripting in corporate settings, where he writes shell scripts to address a variety of complex problems and tasks, ranging from monitoring systems to replicating large databases. He has more than 30 years of experience in the industry and 15 years of experience as a UNIX Systems Administrator, working on AIX, HP-UX, Linux, OpenBSD, and Solaris. vii

Credits Executive Editor Carol Long Development Editor John Sleeva Technical Editor John Kennedy Production Editor Dassi Zeidel Copy Editor Kim Cofer Editorial Manager Mary Beth Wakefield Production Manager Tim Tate Vice President and Executive Group Publisher Richard Swadley Vice President and Executive Publisher Joseph B. Wikert Project Coordinator, Cover Lynsey Stanford Proofreader Candace English Indexer Robert Swanson ix

Contents Acknowledgments Introduction xxv xxvii Part One The Basics of Shell Scripting Chapter 1 Scripting Quick Start and Review 3 Case Sensitivity 3 UNIX Special Characters 3 Shells 4 Shell Scripts 4 Functions 4 Running a Shell Script 5 Declare the Shell in the Shell Script 6 Comments and Style in Shell Scripts 6 Control Structures 8 if... then statement 8 if... then... else statement 8 if... then... elif... (else) statement 9 for... in statement 9 while statement 9 until statement 9 case statement 10 Using break, continue, exit, and return 10 Here Document 11 Shell Script Commands 12 Symbol Commands 14 Variables 15 Command-Line Arguments 15 shift Command 16 Special Parameters $* and $@ 17 Special Parameter Definitions 17 Double Quotes, Forward Tics, and Back Tics 18 xi

xii Contents Using awk on Solaris 19 Using the echo Command Correctly 19 Math in a Shell Script 20 Operators 20 Built-In Mathematical Functions 21 File Permissions, suid and sgid Programs 21 chmod Command Syntax for Each Purpose 22 To Make a Script Executable 22 To Set a Program to Always Execute as the Owner 23 To Set a Program to Always Execute as a Member of the File Owner s Group 23 To Set a Program to Always Execute as Both the File Owner and the File Owner s Group 23 Running Commands on a Remote Host 23 Setting Traps 25 User-Information Commands 25 who Command 26 w Command 26 last Command 26 ps Command 27 Communicating with Users 27 Uppercase or Lowercase Text for Easy Testing 28 Check the Return Code 29 Time-Based Script Execution 30 Cron Tables 30 Cron Table Entry Syntax 31 at Command 31 Output Control 32 Silent Running 32 Using getopts to Parse Command-Line Arguments 33 Making a Co-Process with Background Function 34 Catching a Delayed Command Output 36 Fastest Ways to Process a File Line-by-Line 37 Using Command Output in a Loop 40 Mail Notification Techniques 41 Using the mail and mailx Commands 41 Using the sendmail Command to Send Outbound Mail 41 Creating a Progress Indicator 43 ASeriesofDots 43 A Rotating Line 43 Elapsed Time 44 Working with Record Files 45 Working with Strings 46 Creating a Pseudo-Random Number 47 Using /dev/random and /dev/urandom 48 Checking for Stale Disk Partitions in AIX 48

Contents xiii Automated Host Pinging 49 Highlighting Specific Text in a File 49 Keeping the Printers Printing 50 AIX Classic Printer Subsystem 50 System V and CUPS Printing 50 Automated FTP File Transfer 51 Using rsync to Replicate Data 51 Simple Generic rsync Shell Script 52 Capturing a List of Files Larger than $MEG 53 Capturing a User s Keystrokes 53 Using the bc Utility for Floating-Point Math 54 Number Base Conversions 55 Using the typeset Command 55 Using the printf Command 55 Create a Menu with the select Command 56 Removing Repeated Lines in a File 58 Removing Blank Lines from a File 58 Testing for a Null Variable 58 Directly Access the Value of the Last Positional Parameter, $# 59 Remove the Column Headings in a Command Output 59 Arrays 60 Loading an Array 60 Testing a String 61 Summary 65 Chapter 2 24 Ways to Process a File Line-by-Line 67 Command Syntax 67 Using File Descriptors 68 Creating a Large File to Use in the Timing Test 68 24 Methods to Parse a File Line-by-Line 73 Method 1: cat while read LINE 74 Method 2: while read LINE bottom 75 Method 3: cat while LINE line 76 Method 4: while LINE line bottom 77 Method 5: cat while LINE line cmdsub2 78 Method 6: while LINE line bottom cmdsub2 79 Method 7: for LINE cat FILE 79 Method 8: for LINE cat FILE cmdsub2 80 Method 9: while line outfile 81 Method 10: while read LINE FD IN 81 Method 11: cat while read LINE FD OUT 83 Method 12: while read LINE bottom FD OUT 85 Method 13: while LINE line bottom FD OUT 86 Method 14: while LINE line bottom cmdsub2 FD OUT 87 Method 15: for LINE cat FILE FD OUT 87 Method 16: for LINE cat FILE cmdsub2 FD OUT 88 Method 17: while line outfile FD IN 89