Pro Bash: Learn to Script and Program the GNU/Linux Shell, 3rd Edition / Профессиональный Bash: Учимся писать сценарии и программировать оболочку GNU/Linux, 3-е издание Год издания: 2023 Автор: Varma J., Johnson C. F. A. / Варма Дж., Джонсон К. Ф. А. Издательство: Apress Media ISBN: 978-1-4842-9588-5 Язык: Английский Формат: PDF Качество: Отсканированные страницы + слой распознанного текста Количество страниц: 328 Описание: Learn how to effectively utilize the Bash shell in your programming. This refreshed and expanded third edition has been updated to Bash 5.2, and many scripts have been rewritten to make them more idiomatically Bash, taking better advantage of features specific to Bash. It is easy to read, understand, and will teach you how to get to grips with Bash programming without drowning you in pages and pages of syntax. Using this book you will be able to use the shell efficiently, make scripts run faster using expansion and external commands, and understand how to overcome many common mistakes that cause scripts to fail. This book is perfect for all beginning Linux and Unix system administrators who want to be in full control of their systems, and really get to grips with Bash programming. The Bash shell is a complete programming language, not merely a glue to combine external Linux commands. By taking full advantage of Shell internals, Shell programs can perform as snappily as utilities written in C or other compiled languages. And you will see how, without assuming UNIX lore, you can write professional Bash programs through standard programming techniques. What You'll Learn: Use the Bash shell to write utilities and accomplish most programming tasks Replace many external commands with shell parameter expansion making scripts very fast Avoid many common mistakes that cause scripts to fail See how Bash’s read line and history libraries can save typing when getting user input Build shell scripts that get information from the Web Who This Book Is For: Developers, programmers, and open source enthusiasts who want to write scripts using Bash on multiple platforms. Узнайте, как эффективно использовать оболочку Bash в вашем программировании. Это обновленное и расширенное третье издание было обновлено до версии Bash 5.2, и многие скрипты были переписаны, чтобы сделать их более идиоматичными для Bash, лучше используя возможности, характерные для Bash. Ее легко читать, понимать, и она научит вас, как освоить программирование на Bash, не погружая вас в бесконечные страницы синтаксиса. Используя эту книгу, вы сможете эффективно использовать оболочку, ускорить выполнение сценариев с помощью расширения и внешних команд и поймете, как преодолеть многие распространенные ошибки, приводящие к сбою сценариев. Эта книга идеально подходит для всех начинающих системных администраторов Linux и Unix, которые хотят полностью контролировать свои системы и по-настоящему освоить программирование на Bash. Оболочка Bash - это полноценный язык программирования, а не просто средство для объединения внешних команд Linux. Используя все преимущества внутренней оболочки, программы оболочки могут работать так же быстро, как утилиты, написанные на C или других компилируемых языках. И вы увидите, как, не прибегая к знаниям UNIX, вы можете писать профессиональные программы на Bash с помощью стандартных методов программирования. Чему вы научитесь: Использовать оболочку Bash для написания утилит и выполнения большинства задач программирования Замените многие внешние команды расширением параметров оболочки, что сделает скрипты очень быстрыми Избегать многих распространенных ошибок, которые приводят к сбою скриптов Посмотрите, как библиотеки чтения строк и истории в Bash могут экономить ввод текста при получении пользовательского ввода Создавать сценарии оболочки, которые получают информацию из Интернета Для кого предназначена Эта книга: Разработчики, программисты и энтузиасты с открытым исходным кодом, которые хотят писать сценарии с использованием Bash на нескольких платформах.
Примеры страниц
Оглавление
About the Authors ....................................................................................................................... xvii About the Technical Reviewer ........................................................................................................ xix Acknowledgments ........................................................................................................................ xxi Chapter 1: Hello, World: Your First Shell Program ............................................................................. 1 What Is a Shell Script? .................................................................................................................. 1 The Hello World Code .................................................................................................................... 2 The Hello World Program File ........................................................................................................ 3 Naming the Script File .................................................................................................................. 3 Selecting a Directory for the Script. .............................................................................................. 4 Creating the File and Running the Script ...................................................................................... 5 Choosing and Using a Text Editor .................................................................................................. 6 Building a Better "Hello, World!" ................................................................................................... 7 Summary ....................................................................................................................................... 7 Commands .................................................................................................................................... 8 Concepts ....................................................................................................................................... 8 Variables ....................................................................................................................................... 9 Exercises ....................................................................................................................................... 9 Chapter 2: Input, Output, and Throughput ..................................................................................... 11 Parameters and Variables ........................................................................................................... 11 Positional Parameters ................................................................................................................. 12 Special *@#0$? !- Parameters .................................................................................................. 13 Variables ..................................................................................................................................... 13 Arguments and Options .............................................................................................................. 13 Why You Should Avoid echo ........................................................................................................ 14 TABLE OF CONTENTS printf: Formatting and Printing Data ........................................................................................... 15 Escape Sequences ...................................................................................................................... 16 Format Specifiers ........................................................................................................................ 16 Width Specification ..................................................................................................................... 18 Printing to a Variable ................................................................................................................... 20 Line Continuation ........................................................................................................................ 20 Standard Input/Output Streams and Redirection ............................................................................. 20 Redirection: >,>>, and < ........................................................................................................... 21 Reading Input .............................................................................................................................. 23 Pipelines ..................................................................................................................................... 24 Command Substitution ................................................................................................................ 24 Summary ..................................................................................................................................... 25 Commands .................................................................................................................................. 25 Concepts ..................................................................................................................................... 25 Exercises ..................................................................................................................................... 26 Chapter 3: Looping and Branching .................................................................................................. 27 Exit Status ................................................................................................................................... 27 Testing an Expression ................................................................................................................... 28 test, a.k.a. [ ... ] .......................................................................................................................... 28 File Tests ..................................................................................................................................... 28 Integer Tests ................................................................................................................................ 29 String Tests ................................................................................................................................. 29 [[ ... ]): Evaluate an Expression .................................................................................................. 31 Enhancements over Test ............................................................................................................. 31 (( ... )): Evaluate an Arithmetic Expression ................................................................................... 31 Conditional Execution ................................................................................................................. 32 if .................................................................................................................................................. 32 Conditional Operators: && and 11 ................................................................................................... 34 case ............................................................................................................................................ 35 Looping ....................................................................................................................................... 36 while ........................................................................................................................................... 36 until ............................................................................................................................................. 37 for ................................................................................................................................................ 38 break ........................................................................................................................................... 38 continue ...................................................................................................................................... 39 Summary ..................................................................................................................................... 39 Commands .................................................................................................................................. 40 Concepts ..................................................................................................................................... 40 Exercises ..................................................................................................................................... 40 Chapter 4: Command-Line Parsing and Expansion ............................................................................. 41 Quoting ........................................................................................................................................ 42 Brace Expansion ......................................................................................................................... 44 Tilde Expansion ........................................................................................................................... 46 Parameter and Variable Expansion ................................................................................................ 47 Arithmetic Expansion .................................................................................................................. 48 Command Substitution ................................................................................................................ 51 Word Splitting ............................................................................................................................. 51 Pathname Expansion .................................................................................................................. 53 Process Substitution ................................................................................................................... 54 Parsing Options ........................................................................................................................... 55 Summary ..................................................................................................................................... 58 Commands .................................................................................................................................. 58 Exercises ..................................................................................................................................... 58 Chapter 5: Parameters and Variables .............................................................................................. 61 The Naming of Variables ............................................................................................................. 61 The Scope of a Variable: Can You See It from Here? ........................................................................ 62 Shell Variables ............................................................................................................................ 65 Shell Variables ............................................................................................................................ 65 Parameter Expansion .................................................................................................................. 67 Bourne Shell ................................................................................................................................ 67 ${var:-default} and ${var-default}: Use Default Values ................................................................ 67 ${var:+alternate} and ${var+alternate}: Use Alternate Values .................................................... 68 ${var:=default} and ${var=default}: Assign Default Values ......................................................... 70 ${var:?message} and ${var?message}: Display Error Message If Empty or Unset... ........................ 70 POSIX Shell ................................................................................................................................. 71 ${#var}: Length of Variable's Contents ........................................................................................ 71 ${var%PAITTRN}: Remove the Shortest Match from the End ..................................................... 72 ${var%%PATTERN}: Remove the Longest Match from the End ................................................... 73 ${var#PATTERN}: Remove the Shortest Match from the Beginning ............................................. 73 ${var##PATTERN}: Remove the Longest Match from the Beginning ........................................... 73 bash .................................................................................................................................. 74 ${var//PATTERN/STRING}: Replace All Instances of PATTERN with STRING ................................. 74 ${var:OFFSET:LENGTH}: Return a Substring of $var .................................................................... 75 ${!var}: Indirect Reference .......................................................................................................... 76 bash-4.0 ...................................................................................................................................... 76 ${var"PATTERN}: Convert to Uppercase ...................................................................................... 76 ${var,PATTERN}: Convert to Lowercase ....................................................................................... 77 Positional Parameters ................................................................................................................. 77 Arrays .......................................................................................................................................... 78 Integer-Indexed Arrays ................................................................................................................ 79 Displaying Arrays ........................................................................................................................ 79 Assigning Array Elements ........................................................................................................... 80 Associative Arrays ....................................................................................................................... 81 Summary ..................................................................................................................................... 82 Commands .................................................................................................................................. 82 Concepts ..................................................................................................................................... 83 Exercises ..................................................................................................................................... 83 Chapter 6: Shell Functions .............................................................................................................. 85 Definition Syntax ......................................................................................................................... 85 Compound Commands ................................................................................................................ 88 Getting Results ............................................................................................................................ 89 Set Different Exit Codes .............................................................................................................. 89 Print the Result ........................................................................................................................... 90 Place Results in One or More Variables ............................................................................................ 91 Function Libraries ....................................................................................................................... 92 Using Functions from Libraries ...................................................................................................... 92 Sample Script ............................................................................................................................. 93 Summary ..................................................................................................................................... 95 Commands .................................................................................................................................. 95 Exercises ..................................................................................................................................... 96 Chapter 7: String Manipulation ....................................................................................................... 97 Concatenation ............................................................................................................................. 98 Repeat Character to a Given Length ........................................................................................... 99 Processing Character by Character .......................................................................................... 100 Reversal .................................................................................................................................... 101 Case Conversion ....................................................................................................................... 102 Comparing Contents Without Regard to Case ........................................................................... 105 Check for Valid Variable Name .................................................................................................. 106 Insert One String into Another ................................................................................................... 107 Examples ................................................................................................................................... 108 Overlay ...................................................................................................................................... 108 Examples ................................................................................................................................... 109 Trim Unwanted Characters ............................................................................................................ 110 Examples ................................................................................................................................... 111 Index ......................................................................................................................................... 111 Summary ................................................................................................................................... 113 Commands ................................................................................................................................ 113 Functions .................................................................................................................................. 113 Exercises ................................................................................................................................... 114 Chapter 8: File Operations and Commands .................................................................................... 115 Reading a File ........................................................................................................................... 116 External Commands .................................................................................................................. 117 cat ............................................................................................................................................. 118 head .......................................................................................................................................... 119 touch ......................................................................................................................................... 120 Is ............................................................................................................................................... 121 cut ............................................................................................................................................. 122 we ............................................................................................................................................. 123 Regular Expressions ..................................................................................................................... 124 grep ........................................................................................................................................... 124 sed ............................................................................................................................................ 125 awk ........................................................................................................................................... 127 File Name Expansion Options ........................................................................................................ 130 nullglob ..................................................................................................................................... 131 failglob ...................................................................................................................................... 131 dotglob ...................................................................................................................................... 132 extglob ...................................................................................................................................... 132 ?(pattern-list) ............................................................................................................................ 133 *(pattern-list} ............................................................................................................................ 133 @(pattern-list} ........................................................................................................................... 133 +(pattern-list) ........................................................................................................................... 133 !(pattern-list) ............................................................................................................................. 134 nocaseglob ................................................................................................................................ 134 globstar ..................................................................................................................................... 135 Summary ................................................................................................................................... 136 Shell Options ............................................................................................................................. 136 External Commands .................................................................................................................. 136 Exercises ................................................................................................................................... 137 Chapter 9: Reserved Words and Built-In Commands .................................................................... 139 help, Display Information About Built-In Commands ................................................................ 139 time, Print Time Taken for Execution of a Command ................................................................ 141 read, Read a Line from an Input Stream ................................................................................ 142 -r, Read Backslashes Literally ............................................................................................. 142 -e, Get Input with the readline Library ................................................................................. 143 -a, Read Words into an Array ............................................................................................... 144 -d OEL/M, Read Until OELIM Instead of a Newline ............................................................... 144 -n NUM, Read a Maximum of NUM Characters .................................................................... 145 -s, Do Not Echo Input Coming from a Terminal... ................................................................. 145 -p PROMPT:, Output PROMPTWithout a Trailing Newline .................................................... 145 -t TIMEOUT, Only Wait TIMEOUT Seconds for Complete Input ............................................. 145 -u Fli. Read from File Descriptor FO Instead of the Standard Input .................................... 146 -i TEXT, Use TEXT As the Initial Text for Readline ................................................................ 147 eval, Expand Arguments and Execute the Resulting Command .......................................... 148 Poor Man's Arrays ....................................................................................................... 148 Setting Multiple Variables from One Command ................................................................... 151 type, Display Information About Commands ........................................................................ 152 builtin, Execute a Built-In Command ................................................................................... 154 command, Execute a Command or Display Information About Commands ............................... 154 pwd, Print the Current Working Directory ............................................................................ 155 unalias, Remove One or More Aliases ................................................................................. 155 Summary ....................................................................................................................... 157 Commands and Reserved Words ......................................................................................... 157 Deprecated Commands ....................................................................................................... 158 Exercise ........................................................................................................................... 158 Chapter 10: Writing Bug-Free Scripts and Debugging the Rest .................................................... 159 Prevention Is Better Than Cure ................................................................................................. 160 Structure Your Programs ........................................................................................................... 160 Comments ................................................................................................................................. 160 Initialization of Variables ........................................................................................................... 161 Function Definitions .................................................................................................................. 162 Runtime Configuration and Options ............................................................................................ 162 Process Information .................................................................................................................. 163 Document Your Code ................................................................................................................. 164 Format Your Code Consistently ................................................................................................... 164 The K.l.S.S. Principle ................................................................................................................. 165 Grouping Commands ................................................................................................................. 166 Test As You Go ........................................................................................................................... 167 Debugging a Script ................................................................................................................... 169 Summary ................................................................................................................................... 174 Exercises ................................................................................................................................... 174 Chapter 11: Programming for the Command Line ............................................................................ 175 Manipulating the Directory Stack ................................................................................................... 175 cd .............................................................................................................................................. 176 pd .............................................................................................................................................. 177 cdm ........................................................................................................................................... 177 dirs Built-In Command .................................................................................................................. 178 menu ......................................................................................................................................... 179 Filesystem Functions .................................................................................................................... 181 l ................................................................................................................................................ 181 lsr .............................................................................................................................................. 182 cp, mv ....................................................................................................................................... 183 md ............................................................................................................................................. 184 Miscellaneous Functions ................................................................................................................. 184 pr1 ............................................................................................................................................. 184 calc ........................................................................................................................................... 186 Managing Man Pages .................................................................................................................... 186 sman ......................................................................................................................................... 186 sus ............................................................................................................................................ 187 k ................................................................................................................................................ 187 Games ....................................................................................................................................... 188 The fifteen Puzzle ........................................................................................................................ 189 Summary ................................................................................................................................... 195 Exercises ................................................................................................................................... 195 Chapter 12: Runtime Configuration ............................................................................................... 197 Defining Variables ...................................................................................................................... 197 Command-Line Options and Arguments ......................................................................................... 198 Menus ....................................................................................................................................... 198 Q&A Dialogue ............................................................................................................................ 199 Configuration Files .................................................................................................................... 200 Scripts with Several Names ...................................................................................................... 202 Environment Variables .............................................................................................................. 203 All Together Now ....................................................................................................................... 204 Script Information ..................................................................................................................... 205 Default Configuration ................................................................................................................ 205 Screen Variables ....................................................................................................................... 206 Function Definitions .................................................................................................................. 207 Function: die ............................................................................................................................. 207 Function: menu ......................................................................................................................... 207 The Upload Settings Menu ........................................................................................................ 208 Function: qa .............................................................................................................................. 211 Function: print_config ............................................................................................................... 212 Function: readline ..................................................................................................................... 213 Parse Command-Line Options .................................................................................................. 214 Bits and Pieces ......................................................................................................................... 215 Summary ................................................................................................................................... 217 Exercises ................................................................................................................................... 217 Chapter 13: Data Processing ......................................................................................................... 219 Arrays ........................................................................................................................................ 219 Holes in an Indexed Array ......................................................................................................... 219 Using an Array for Sorting ......................................................................................................... 221 Insertion Sort Function .............................................................................................................. 223 Searching an Array .................................................................................................................... 224 Reading an Array into Memory .................................................................................................. 225 Two-Dimensional Grids ............................................................................................................. 228 Working with Single-String Grids .............................................................................................. 229 Function: initgrid ....................................................................................................................... 229 Function: gridindex ................................................................................................................... 230 Function: putgrid ....................................................................................................................... 231 Function: getgrid ....................................................................................................................... 232 Function: showgrid ................................................................................................................... 233 Function: rshowgrid .................................................................................................................. 234 Two-Dimensional Grids Using Arrays ............................................................................................ 235 Function: initagrid ..................................................................................................................... 237 Function: putagrid ..................................................................................................................... 238 Function: getagrid ..................................................................................................................... 238 Function: showagrid .................................................................................................................. 239 Function: rshowagrid ................................................................................................................ 239 Data File Formats ...................................................................................................................... 240 Line-Based Records .................................................................................................................. 240 Delimiter-Separated Values ....................................................................................................... 241 Fixed-Length Fields .................................................................................................................. 244 Block File Formats .................................................................................................................... 245 Summary ................................................................................................................................... 247 Exercises ................................................................................................................................... 247 Chapter 14: Scripting the Screen ................................................................................................ 249 Teletypewriter vs. Canvas ......................................................................................................... 250 Stretching the Canvas ............................................................................................................... 250 Control Sequence Introducer .................................................................................................... 251 Priming the Canvas ................................................................................................................... 251 Moving the Cursor ..................................................................................................................... 252 Changing Rendition Modes and Colors .......................................................................................... 253 Placing a Block of Text on the Screen ............................................................................................ 255 Scrolling Text ............................................................................................................................. 259 Rolling Dice ............................................................................................................................... 260 Summary ................................................................................................................................... 263 Exercises ................................................................................................................................... 263 Chapter 15: Entry-Level Programming ........................................................................................... 265 Single-Key Entry ....................................................................................................................... 265 Function Library, key-tunes ........................................................................................................ 266 History in Scripts ....................................................................................................................... 274 Sanity Checking ........................................................................................................................ 275 Form Entry ................................................................................................................................ 276 Reading the Mouse ..................................................................................................................... 278 Summary ................................................................................................................................... 282 Exercises ................................................................................................................................... 283 Appendix A: Shell Variables .......................................................................................................... 285 Index ........................................................................................................................................ 301
Varma J., Johnson C. F. A. / Варма Дж., Джонсон К. Ф. А. - Pro Bash: Learn to Script and Program the GNU/Linux Shell, 3rd Edition / Профессиональный Bash: Учимся писать сценарии и программировать оболочку GNU/Linux, 3-е издание [2023, PDF, ENG] download torrent for free and without registration
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum