Contents
Introduction 12
Organization of This Document 12
Before You Begin 14
Obtaining a Shell Prompt 14 In Mac OS X 14 In Other UNIX Variants or Linux Variants 15 In Windows 15 Familiarize Yourself With the Command Line 15 Tips for Shell Users 15 The alias Builtin 15 Entering Special Characters 17 Creating Text Files in Your Home Directory 17 In TextEdit 17 In pico or nano 18
Shell Script Basics 19
Shell Script Dialects 19 She Sells C Shells 21 Shell Variables and Printing 21 Using Arguments And Variables That Contain Spaces 23 Handling Quotation Marks in Strings 25 Exporting Shell Variables 26 Using the export Builtin (Bourne Shell) 27 Overriding Environment Variables for Child Processes (Bourne Shell) 28 Using the setenv Builtin (C shell) 29 Overriding Environment Variables for Child Processes (C Shell) 31 Deleting Shell Variables 32
Shell Input and Output 33
Shell Script Input and Output Using printf and read 33 Bulk I/O Using the cat Command 35 Pipes and Redirection 38 Basic File Redirection 38
2011-07-27 | © 2003, 2011 Apple Inc. All Rights Reserved.
2
Contents
Pipes and File Descriptor Redirection (Bourne Shell) 40 Pipes and File Descriptor Redirection (C Shell) 42
Flow Control, Expansion, and Parsing 44
Basic Control Statements 44 The if Statement 44 The test Command and Bracket Notation 46 The while Statement 48 The for Statement 50 The case statement 53 The expr Command 56 Parsing, Variable Expansion, and Quoting 59 Variable Expansion and Field Separators 60 Special Characters Explained 61 Quoting Special Characters 64 Inline Execution 66
Result Codes, Chaining, and Flags 68
Working with Result Codes 68 Chaining Execution 69 Handling Flags and Arguments 72 Special Multi-argument Variables 72 The shift Builtin 74 The getopts builtin and the getopt command 75
Subroutines, Scoping, and Sourcing 81
Subroutine Basics 81 Anonymous Subroutines 82 Variable Scoping 84 Declaring a Local Variable