Transcription of Advanced Bash-Scripting Guide - …
1 Advanced bash scripting GuideAn in depth exploration of the art of shell scriptingMendel June 2003 Revision HistoryRevision June 2000 Revised by: mcInitial October 2000 Revised by: mcBugs fixed, plus much additional material and more example February 2001 Revised by: mcAnother major July 2001 Revised by: mcMore bugfixes, much more material, more scripts a complete revision and expansion of the September 2001 Revised by: mcMajor update. Bugfixes, material added, chapters and sections October 2001 Revised by: mcBugfixes, reorganization, material added. Stable January 2002 Revised by: mcBugfixes, material and scripts March 2002 Revised by: mcBugfixes, material and scripts June 2002 Revised by: mc'TANGERINE' release: A few bugfixes, much more material and scripts June 2002 Revised by: mc'MANGO' release: Quite a number of typos fixed, more material and scripts July 2002 Revised by: mc'PAPAYA' release: A few bugfixes, much more material and scripts September 2002 Revised by: mc'POMEGRANATE' release: some bugfixes, more material, one more script January 2003 Revised by: mc'COCONUT' release: a couple of bugfixes, more material, one more May 2003 Revised by: mc'BREADFRUIT' release: a number of bugfixes, more scripts and June 2003 Revised by: mc'PERSIMMON' release.
2 Bugfixes and more tutorial assumes no previous knowledge of scripting or programming, but progresses rapidly toward anintermediate/ Advanced level of instruction .. all the while sneaking in little snippets of UNIX wisdom andlore. It serves as a textbook, a manual for self study, and a reference and source of knowledge on shellscripting techniques. The exercises and heavily commented examples invite active reader participation, underthe premise that the only way to really learn scripting is to write latest update of this document, as an archived, bzip2 ed "tarball" including both the SGML source andrendered HTML, may be downloaded from the author's home site. See the change log for a revision Anita, the source of all the magicTable of ContentsChapter 1. Why Shell Programming?..1 Chapter 2. Starting Off With a Sha Invoking the Preliminary 2. 3. Special 4.
3 Introduction to Variables and Variable Variable bash Variables Are Special Variable 5. 6. Exit and Exit 7. Test File test Comparison operators (binary).. Nested if/then Condition Testing Your Knowledge of 8. Operations and Related Numerical 3. Beyond the 9. Variables Internal Manipulating Manipulating strings using Further Parameter Typing variables: declare or Indirect References to $RANDOM: generate random The Double Parentheses 10. Loops and Nested Loop bash scripting GuideiTable of ContentsChapter 10. Loops and Testing and 11. Internal Commands and Job Control 12. External Filters, Programs and Basic Complex Time / Date Text Processing File and Archiving Communications Terminal Control Math Miscellaneous 13. System and Administrative 14. Command 15. Arithmetic 16.
4 I/O Using Redirecting Code 17. Here 18. Recess 4. Advanced 19. Regular A Brief Introduction to Regular 20. 21. Restricted 22. Process 23. Complex Functions and Function Local Local variables make recursion bash scripting GuideiiTable of ContentsChapter 24. 25. List 26. 27. 28. /dev and 29. Of Zeros and 30. 31. 32. 33. scripting With Unofficial Shell scripting 34. Interactive and non interactive shells and Shell Tests and Comparisons: "Colorizing" Assorted Security Portability Shell scripting Under 35. bash , version 36. Author's About the Tools Used to Produce This Software and bash scripting GuideiiiTable of ContentsAppendix A. Contributed B. A Sed and Awk Micro C. Exit Codes With Special D. A Detailed Introduction to I/O and I/O E. F. History G. A H.
5 Converting DOS Batch Files to Shell I. Analyzing Writing J. bash scripting GuideivChapter 1. Why Shell Programming?A working knowledge of shell scripting is essential to anyone wishing to become reasonably proficient atsystem administration, even if they do not anticipate ever having to actually write a script. Consider that as aLinux machine boots up, it executes the shell scripts in / to restore the system configuration andset up services. A detailed understanding of these startup scripts is important for analyzing the behavior of asystem, and possibly modifying shell scripts is not hard to learn, since the scripts can be built in bite sized sections and there is only afairly small set of shell specific operators and options [1] to learn. The syntax is simple and straightforward,similar to that of invoking and chaining together utilities at the command line, and there are only a few "rules"to learn.
6 Most short scripts work right the first time, and debugging even the longer ones is shell script is a "quick and dirty" method of prototyping a complex application. Getting even a limitedsubset of the functionality to work in a shell script, even if slowly, is often a useful first stage in projectdevelopment. This way, the structure of the application can be tested and played with, and the major pitfallsfound before proceeding to the final coding in C, C++, Java, or scripting hearkens back to the classical UNIX philosophy of breaking complex projects into simplersubtasks, of chaining together components and utilities. Many consider this a better, or at least moreesthetically pleasing approach to problem solving than using one of the new generation of high poweredall in one languages, such as Perl, which attempt to be all things to all people, but at the cost of forcing youto alter your thinking processes to fit the not to use shell scriptsresource intensive tasks, especially where speed is a factor (sorting, hashing, etc.)
7 Procedures involving heavy duty math operations, especially floating point arithmetic, arbitraryprecision calculations, or complex numbers (use C++ or FORTRAN instead) cross platform portability required (use C instead) complex applications, where structured programming is a necessity (need type checking of variables,function prototypes, etc.) mission critical applications upon which you are betting the ranch, or the future of the company situations where security is important, where you need to guarantee the integrity of your system andprotect against intrusion, cracking, and vandalism project consists of subcomponents with interlocking dependencies extensive file operations required ( bash is limited to serial file access, and that only in a particularlyclumsy and inefficient line by line fashion) need multi dimensional arrays need data structures, such as linked lists or trees need to generate or manipulate graphics or GUIs need direct access to system hardware need port or socket I/O need to use libraries or interface with legacy code proprietary, closed source applications (shell scripts put the source code right out in the open for allthe world to see)
8 If any of the above applies, consider a more powerful scripting language, perhaps Perl, Tcl, Python, Ruby, orpossibly a high level compiled language such as C, C++, or Java. Even then, prototyping the application as ashell script might still be a useful development 1. Why Shell Programming?1We will be using bash , an acronym for "Bourne Again Shell" and a pun on Stephen Bourne's now classicBourne Shell. bash has become a de facto standard for shell scripting on all flavors of UNIX. Most of theprinciples dealt with in this book apply equally well to scripting with other shells, such as the Korn Shell,from which bash derives some of its features, [2] and the C Shell and its variants. (Note that C Shellprogramming is not recommended due to certain inherent problems, as pointed out in an October, 1993 Usenet post by Tom Christiansen.)What follows is a tutorial on shell scripting .
9 It relies heavily on examples to illustrate various features of theshell. The example scripts work they've been tested and some of them are even useful in real life. Thereader can play with the actual working code of the examples in the source archive ( ), [3]give them execute permission (chmod u+rx scriptname), then run them to see what happens. Shouldthe source archive not be available, then cut and paste from the HTML, pdf, or text rendered versions. Beaware that some of the scripts below introduce features before they are explained, and this may require thereader to temporarily skip ahead for otherwise noted, the author of this book wrote the example scripts that bash scripting GuideChapter 1. Why Shell Programming?2 Chapter 2. Starting Off With a Sha BangIn the simplest case, a script is nothing more than a list of system commands stored in a file.
10 At the very least,this saves the effort of retyping that particular sequence of commands each time it is 2 1. cleanup: A script to clean up the log files in /var/log# cleanup# Run as root, of /var/logcat /dev/null > messagescat /dev/null > wtmpecho "Logs cleaned up."There is nothing unusual here, just a set of commands that could just as easily be invoked one by one from thecommand line on the console or in an xterm. The advantages of placing the commands in a script go beyondnot having to retype them time and again. The script can easily be modified, customized, or generalized for aparticular 2 2. cleanup: An enhanced and generalized version of above script.#!/bin/ bash # cleanup, version 2# Run as root, of # Only users with $UID 0 have root # Default number of lines # Can't change directory?E_NOTROOT=67 # Non root exit [ "$UID" ne "$ROOT_UID" ]then echo "Must be root to run this script.
