Sie sind auf Seite 1von 807

Advanced Bash-Scripting Guide

An in-depth exploration of the art of shell scripting


Mendel Cooper

< t h e g r e n d e l . a b s @ g m a i l . c o m >

6.6 27 Nov 2012 Revision History Revision 6.4 'VORTEXBERRY' release Revision 6.5 'TUNGSTENBERRY' release Revision 6.6 'YTTERBIUMBERRY' release

30 Aug 2011 05 Apr 2012 27 Nov 2012

Revised by: mc Revised by: mc Revised by: mc

This tutorial assumes no previous knowledge of scripting or programming, but progresses rapidly toward an intermediate/advanced level of instruction . . . all the while sneaking in little nuggets of UNIX wisdom and lore. It serves as a textbook, a manual for self-study, and as a reference and source of knowledge on shell scripting techniques. The exercises and heavily-commented examples invite active reader participation, under the premise that t h eo n l yw a yt o r e a l l yl e a r ns c r i p t i n gi st ow r i t es c r i p t s . This book is suitable for classroom use as a general introduction to programming concepts.

Dedication
For Anita, the source of all the magic Table of Contents Part 1. Introduction 1. Shell Programming! 2. Starting Off With a Sha-Bang Part 2. Basics 3. Special Characters 4. Introduction to Variables and Parameters 5. Quoting 6. Exit and Exit Status 7. Tests 8. Operations and Related Topics Part 3. Beyond the Basics 9. Another Look at Variables

10. Manipulating Variables 11. Loops and Branches 12. Command Substitution 13. Arithmetic Expansion 14. Recess Time Part 4. Commands 15. Internal Commands and Builtins 16. External Filters, Programs and Commands 17. System and Administrative Commands Part 5. Advanced Topics 18. Regular Expressions 19. Here Documents 20. I/O Redirection 21. Subshells 22. Restricted Shells 23. Process Substitution 24. Functions 25. Aliases 26. List Constructs 27. Arrays 28. Indirect References 29. / d e vand / p r o c 30. Network Programming 31. Of Zeros and Nulls 32. Debugging 33. Options 34. Gotchas 35. Scripting With Style 36. Miscellany 37. Bash, versions 2, 3, and 4 38. Endnotes 38.1. Author's Note 38.2. About the Author 38.3. Where to Go For Help 38.4. Tools Used to Produce This Book 38.5. Credits 38.6. Disclaimer Bibliography A. Contributed Scripts B. Reference Cards C. A Sed and Awk Micro-Primer C.1. Sed C.2. Awk D. Parsing and Managing Pathnames E. Exit Codes With Special Meanings F. A Detailed Introduction to I/O and I/O Redirection G. Command-Line Options

G.1. Standard Command-Line Options G.2. Bash Command-Line Options H. Important Files I. Important System Directories J. An Introduction to Programmable Completion K. Localization L. History Commands M. Sample . b a s h r cand . b a s h _ p r o f i l eFiles N. Converting DOS Batch Files to Shell Scripts O. Exercises O.1. Analyzing Scripts O.2. Writing Scripts P. Revision History Q. Download and Mirror Sites R. To Do List S. Copyright T. ASCII Table Index List of Tables 8-1. Operator Precedence 15-1. Job identifiers 33-1. Bash options 36-1. Numbers representing colors in Escape Sequences B-1. Special Shell Variables B-2. TEST Operators: Binary Comparison B-3. TEST Operators: Files B-4. Parameter Substitution and Expansion B-5. String Operations B-6. Miscellaneous Constructs C-1. Basic sed operators C-2. Examples of sed operators E-1. Reserved Exit Codes N-1. Batch file keywords / variables / operators, and their shell equivalents N-2. DOS commands and their UNIX equivalents P-1. Revision History List of Examples 2-1. cleanup: A script to clean up log files in /var/log 2-2. cleanup: An improved clean-up script 2-3. cleanup: An enhanced and generalized version of above scripts. 3-1. Code blocks and I/O redirection 3-2. Saving the output of a code block to a file 3-3. Running a loop in the background 3-4. Backup of all files changed in last day 4-1. Variable assignment and substitution 4-2. Plain Variable Assignment 4-3. Variable Assignment, plain and fancy 4-4. Integer or string? 4-5. Positional Parameters 4-6. wh, whois domain name lookup 4-7. Using shift 5-1. Echoing Weird Variables

5-2. Escaped Characters 5-3. Detecting key-presses 6-1. exit / exit status 6-2. Negating a condition using ! 7-1. What is truth? 7-2. Equivalence of test , / u s r / b i n / t e s t , [ ], and / u s r / b i n / [ 7-3. Arithmetic Tests using (( )) 7-4. Testing for broken links 7-5. Arithmetic and string comparisons 7-6. Testing whether a string is null 7-7. zmore 8-1. Greatest common divisor 8-2. Using Arithmetic Operations 8-3. Compound Condition Tests Using && and || 8-4. Representation of numerical constants 8-5. C-style manipulation of variables 9-1. $IFS and whitespace 9-2. Timed Input 9-3. Once more, timed input 9-4. Timed read 9-5. Am I root? 9-6. arglist : Listing arguments with $* and $@ 9-7. Inconsistent $ *and $ @behavior 9-8. $ *and $ @when $ I F Sis empty 9-9. Underscore variable 9-10. Using declare to type variables 9-11. Generating random numbers 9-12. Picking a random card from a deck 9-13. Brownian Motion Simulation 9-14. Random between values 9-15. Rolling a single die with RANDOM 9-16. Reseeding RANDOM 9-17. Pseudorandom numbers, using awk 10-1. Inserting a blank line between paragraphs in a text file 10-2. Generating an 8-character "random" string 10-3. Converting graphic file formats, with filename change 10-4. Converting streaming audio files to ogg 10-5. Emulating getopt 10-6. Alternate ways of extracting and locating substrings 10-7. Using parameter substitution and error messages 10-8. Parameter substitution and "usage" messages 10-9. Length of a variable 10-10. Pattern matching in parameter substitution 10-11. Renaming file extensions: 10-12. Using pattern matching to parse arbitrary strings 10-13. Matching patterns at prefix or suffix of string 11-1. Simple for loops 11-2. for loop with two parameters in each [list] element 11-3. Fileinfo: operating on a file list contained in a variable 11-4. Operating on files with a for loop 11-5. Missing i n[ l i s t ]in a for loop 11-6. Generating the [ l i s t ]in a for loop with command substitution 11-7. A grep replacement for binary files 11-8. Listing all users on the system 11-9. Checking all the binaries in a directory for authorship

11-10. Listing the symbolic links in a directory 11-11. Symbolic links in a directory, saved to a file 11-12. A C-style for loop 11-13. Using efax in batch mode 11-14. Simple while loop 11-15. Another while loop 11-16. while loop with multiple conditions 11-17. C-style syntax in a while loop 11-18. until loop 11-19. Nested Loop 11-20. Effects of break and continue in a loop 11-21. Breaking out of multiple loop levels 11-22. Continuing at a higher loop level 11-23. Using continue N in an actual task 11-24. Using case 11-25. Creating menus using case 11-26. Using command substitution to generate the case variable 11-27. Simple string matching 11-28. Checking for alphabetic input 11-29. Creating menus using select 11-30. Creating menus using select in a function 12-1. Stupid script tricks 12-2. Generating a variable from a loop 12-3. Finding anagrams 15-1. A script that spawns multiple instances of itself 15-2. printf in action 15-3. Variable assignment, using read 15-4. What happens when read has no variable 15-5. Multi-line input to read 15-6. Detecting the arrow keys 15-7. Using read with file redirection 15-8. Problems reading from a pipe 15-9. Changing the current working directory 15-10. Letting let do arithmetic. 15-11. Showing the effect of eval 15-12. Using eval to select among variables 15-13. Echoing the command-line parameters 15-14. Forcing a log-off 15-15. A version of rot13 15-16. Using set with positional parameters 15-17. Reversing the positional parameters 15-18. Reassigning the positional parameters 15-19. "Unsetting" a variable 15-20. Using export to pass a variable to an embedded awk script 15-21. Using getopts to read the options/arguments passed to a script 15-22. "Including" a data file 15-23. A (useless) script that sources itself 15-24. Effects of exec 15-25. A script that exec's itself 15-26. Waiting for a process to finish before proceeding 15-27. A script that kills itself 16-1. Using ls to create a table of contents for burning a CDR disk 16-2. Hello or Good-bye 16-3. Badname, eliminate file names in current directory containing bad characters and whitespace. 16-4. Deleting a file by its inode number

16-5. Logfile: Using xargs to monitor system log 16-6. Copying files in current directory to another 16-7. Killing processes by name 16-8. Word frequency analysis using xargs 16-9. Using expr 16-10. Using date 16-11. Date calculations 16-12. Word Frequency Analysis 16-13. Which files are scripts? 16-14. Generating 10-digit random numbers 16-15. Using tail to monitor the system log 16-16. Printing out the From lines in stored e-mail messages 16-17. Emulating grep in a script 16-18. Crossword puzzle solver 16-19. Looking up definitions in Webster's 1913 Dictionary 16-20. Checking words in a list for validity 16-21. toupper: Transforms a file to all uppercase. 16-22. lowercase: Changes all filenames in working directory to lowercase. 16-23. du: DOS to UNIX text file conversion. 16-24. rot13: ultra-weak encryption. 16-25. Generating "Crypto-Quote" Puzzles 16-26. Formatted file listing. 16-27. Using column to format a directory listing 16-28. nl: A self-numbering script. 16-29. manview: Viewing formatted manpages 16-30. Using cpio to move a directory tree 16-31. Unpacking an rpm archive 16-32. Stripping comments from C program files 16-33. Exploring / u s r / X 1 1 R 6 / b i n 16-34. An "improved" strings command 16-35. Using cmp to compare two files within a script. 16-36. basename and dirname 16-37. A script that copies itself in sections 16-38. Checking file integrity 16-39. Uudecoding encoded files 16-40. Finding out where to report a spammer 16-41. Analyzing a spam domain 16-42. Getting a stock quote 16-43. Updating FC4 16-44. Using ssh 16-45. A script that mails itself 16-46. Generating prime numbers 16-47. Monthly Payment on a Mortgage 16-48. Base Conversion 16-49. Invoking bc using a here document 16-50. Calculating PI 16-51. Converting a decimal number to hexadecimal 16-52. Factoring 16-53. Calculating the hypotenuse of a triangle 16-54. Using seq to generate loop arguments 16-55. Letter Count" 16-56. Using getopt to parse command-line options 16-57. A script that copies itself 16-58. Exercising dd 16-59. Capturing Keystrokes

16-60. Securely deleting a file 16-61. Filename generator 16-62. Converting meters to miles 16-63. Using m4 17-1. Setting a new password 17-2. Setting an erase character 17-3. secret password: Turning off terminal echoing 17-4. Keypress detection 17-5. Checking a remote server for identd 17-6. pidof helps kill a process 17-7. Checking a CD image 17-8. Creating a filesystem in a file 17-9. Adding a new hard drive 17-10. Using umask to hide an output file from prying eyes 17-11. Backlight : changes the brightness of the (laptop) screen backlight 17-12. killall, from / e t c / r c . d / i n i t . d 19-1. broadcast : Sends message to everyone logged in 19-2. dummyfile: Creates a 2-line dummy file 19-3. Multi-line message using cat 19-4. Multi-line message, with tabs suppressed 19-5. Here document with replaceable parameters 19-6. Upload a file pair to Sunsite incoming directory 19-7. Parameter substitution turned off 19-8. A script that generates another script 19-9. Here documents and functions 19-10. "Anonymous" Here Document 19-11. Commenting out a block of code 19-12. A self-documenting script 19-13. Prepending a line to a file 19-14. Parsing a mailbox 20-1. Redirecting s t d i nusing exec 20-2. Redirecting s t d o u tusing exec 20-3. Redirecting both s t d i nand s t d o u tin the same script with exec 20-4. Avoiding a subshell 20-5. Redirected while loop 20-6. Alternate form of redirected while loop 20-7. Redirected until loop 20-8. Redirected for loop 20-9. Redirected for loop (both s t d i nand s t d o u tredirected) 20-10. Redirected if/then test 20-11. Data file names.data for above examples 20-12. Logging events 21-1. Variable scope in a subshell 21-2. List User Profiles 21-3. Running parallel processes in subshells 22-1. Running a script in restricted mode 23-1. Code block redirection without forking 23-2. Redirecting the output of process substitution into a loop. 24-1. Simple functions 24-2. Function Taking Parameters 24-3. Functions and command-line args passed to the script 24-4. Passing an indirect reference to a function 24-5. Dereferencing a parameter passed to a function 24-6. Again, dereferencing a parameter passed to a function 24-7. Maximum of two numbers

24-8. Converting numbers to Roman numerals 24-9. Testing large return values in a function 24-10. Comparing two large integers 24-11. Real name from username 24-12. Local variable visibility 24-13. Demonstration of a simple recursive function 24-14. Another simple demonstration 24-15. Recursion, using a local variable 24-16. The Fibonacci Sequence 24-17. The Towers of Hanoi 25-1. Aliases within a script 25-2. unalias: Setting and unsetting an alias 26-1. Using an and list to test for command-line arguments 26-2. Another command-line arg test using an and list 26-3. Using or lists in combination with an and list 27-1. Simple array usage 27-2. Formatting a poem 27-3. Various array operations 27-4. String operations on arrays 27-5. Loading the contents of a script into an array 27-6. Some special properties of arrays 27-7. Of empty arrays and empty elements 27-8. Initializing arrays 27-9. Copying and concatenating arrays 27-10. More on concatenating arrays 27-11. The Bubble Sort 27-12. Embedded arrays and indirect references 27-13. The Sieve of Eratosthenes 27-14. The Sieve of Eratosthenes, Optimized 27-15. Emulating a push-down stack 27-16. Complex array application: Exploring a weird mathematical series 27-17. Simulating a two-dimensional array, then tilting it 28-1. Indirect Variable References 28-2. Passing an indirect reference to awk 29-1. Using / d e v / t c pfor troubleshooting 29-2. Playing music 29-3. Finding the process associated with a PID 29-4. On-line connect status 30-1. Print the server environment 30-2. IP addresses 31-1. Hiding the cookie jar 31-2. Setting up a swapfile using / d e v / z e r o 31-3. Creating a ramdisk 32-1. A buggy script 32-2. Missing keyword 32-3. test24: another buggy script 32-4. Testing a condition with an assert 32-5. Trapping at exit 32-6. Cleaning up after Control-C 32-7. A Simple Implementation of a Progress Bar 32-8. Tracing a variable 32-9. Running multiple processes (on an SMP box) 34-1. Numerical and string comparison are not equivalent 34-2. Subshell Pitfalls 34-3. Piping the output of echo to a read

36-1. shell wrapper 36-2. A slightly more complex shell wrapper 36-3. A generic shell wrapper that writes to a logfile 36-4. A shell wrapper around an awk script 36-5. A shell wrapper around another awk script 36-6. Perl embedded in a Bash script 36-7. Bash and Perl scripts combined 36-8. A (useless) script that recursively calls itself 36-9. A (useful) script that recursively calls itself 36-10. Another (useful) script that recursively calls itself 36-11. A "colorized" address database 36-12. Drawing a box 36-13. Echoing colored text 36-14. A "horserace" game 36-15. A Progress Bar 36-16. Return value trickery 36-17. Even more return value trickery 36-18. Passing and returning arrays 36-19. Fun with anagrams 36-20. Widgets invoked from a shell script 36-21. Test Suite 37-1. String expansion 37-2. Indirect variable references - the new way 37-3. Simple database application, using indirect variable referencing 37-4. Using arrays and other miscellaneous trickery to deal four random hands from a deck of cards 37-5. A simple address database 37-6. A somewhat more elaborate address database 37-7. Testing characters 37-8. Reading N characters 37-9. Using a here document to set a variable 37-10. Piping input to a read 37-11. Negative array indices 37-12. Negative parameter in string-extraction construct A-1. mailformat : Formatting an e-mail message A-2. rn: A simple-minded file renaming utility A-3. blank-rename: Renames filenames containing blanks A-4. encryptedpw: Uploading to an ftp site, using a locally encrypted password A-5. copy-cd: Copying a data CD A-6. Collatz series A-7. days-between: Days between two dates A-8. Making a dictionary A-9. Soundex conversion A-10. Game of Life A-11. Data file for Game of Life A-12. behead: Removing mail and news message headers A-13. password: Generating random 8-character passwords A-14. fifo: Making daily backups, using named pipes A-15. Generating prime numbers using the modulo operator A-16. tree: Displaying a directory tree A-17. tree2: Alternate directory tree script A-18. string functions: C-style string functions A-19. Directory information A-20. Library of hash functions A-21. Colorizing text using hash functions A-22. More on hash functions

A-23. Mounting USB keychain storage devices A-24. Converting to HTML A-25. Preserving weblogs A-26. Protecting literal strings A-27. Unprotecting literal strings A-28. Spammer Identification A-29. Spammer Hunt A-30. Making wget easier to use A-31. A podcasting script A-32. Nightly backup to a firewire HD A-33. An expanded cd command A-34. A soundcard setup script A-35. Locating split paragraphs in a text file A-36. Insertion sort A-37. Standard Deviation A-38. A pad file generator for shareware authors A-39. A man page editor A-40. Petals Around the Rose A-41. Quacky: a Perquackey-type word game A-42. Nim A-43. A command-line stopwatch A-44. An all-purpose shell scripting homework assignment solution A-45. The Knight's Tour A-46. Magic Squares A-47. Fifteen Puzzle A-48. The Towers of Hanoi, graphic version A-49. The Towers of Hanoi, alternate graphic version A-50. An alternate version of the getopt-simple.sh script A-51. The version of the UseGetOpt.sh example used in the Tab Expansion appendix A-52. Cycling through all the possible color backgrounds A-53. Morse Code Practice A-54. Base64 encoding/decoding A-55. The Gronsfeld Cipher A-56. Bingo Number Generator A-57. Basics Reviewed C-1. Counting Letter Occurrences J-1. Completion script for UseGetOpt.sh M-1. Sample . b a s h r cfile M-2. . b a s h _ p r o f i l efile N-1. VIEWDATA.BAT: DOS Batch File N-2. viewdata.sh: Shell Script Conversion of VIEWDATA.BAT T-1. A script that generates an ASCII table T-2. Another ASCII table script T-3. A third ASCII table script, using awk

Part 1. Introduction
Script: A writing; a written document. [Obs.] --Webster's Dictionary, 1913 ed. The shell is a command interpreter. More than just the insulating layer between the operating system kernel and the user, it's also a fairly powerful programming language. A shell program, called a script , is an easy-to-use tool for building applications by "gluing together" system calls, tools, utilities, and compiled binaries. Virtually the entire repertoire of UNIX commands, utilities, and tools is available for invocation by a shell script. If that were not enough, internal shell commands, such as testing

and loop constructs, lend additional power and flexibility to scripts. Shell scripts are especially well suited for administrative system tasks and other routine repetitive tasks not requiring the bells and whistles of a full-blown tightly structured programming language. Table of Contents 1. Shell Programming! 2. Starting Off With a Sha-Bang 2.1. Invoking the script 2.2. Preliminary Exercises

Chapter 1. Shell Programming!


No programming language is perfect. There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes. --Herbert Mayer A working knowledge of shell scripting is essential to anyone wishing to become reasonably proficient at system administration, even if they do not anticipate ever having to actually write a script. Consider that as a Linux machine boots up, it executes the shell scripts in / e t c / r c . dto restore the system configuration and set up services. A detailed understanding of these startup scripts is important for analyzing the behavior of a system, and possibly modifying it. The craft of scripting is not hard to master, since scripts can be built in bite-sized sections and there is only a fairly small set of shell-specific operators and options [1] to learn. The syntax is simple -- even austere -- similar to that of invoking and chaining together utilities at the command line, and there are only a few "rules" governing their use. Most short scripts work right the first time, and debugging even the longer ones is straightforward. In the early days of personal computing, the BASIC language enabled anyone reasonably computer proficient to write programs on an early generation of microcomputers. Decades later, the Bash scripting language enables anyone with a rudimentary knowledge of Linux or UNIX to do the same on modern machines. We now have miniaturized single-board computers with amazing capabilities, such as the Raspberry Pi. Bash scripting provides a way to explore the capabilities of these fascinating devices. A shell script is a quick-and-dirty method of prototyping a complex application. Getting even a limited subset of the functionality to work in a script is often a useful first stage in project development. In this way, the structure of the application can be tested and tinkered with, and the major pitfalls found before proceeding to the final coding in C, C++, Java, Perl, or Python. Shell scripting hearkens back to the classic UNIX philosophy of breaking complex projects into simpler subtasks, of chaining together components and utilities. Many consider this a better, or at least more esthetically pleasing approach to problem solving than using one of the new generation of high-powered all-in-one languages, such as Perl, which attempt to be all things to all people, but at the cost of forcing you to alter your thinking processes to fit the tool. According to Herbert Mayer, "a useful language needs arrays, pointers, and a generic mechanism for building data structures." By these criteria, shell scripting falls somewhat short of being "useful." Or, perhaps not. . . . When not to use shell scripts

Resource-intensive tasks, especially where speed is a factor (sorting, hashing, recursion [2] ...) Procedures involving heavy-duty math operations, especially floating point arithmetic, arbitrary precision calculations, or complex numbers (use C++ or FORTRAN instead) Cross-platform portability required (use C or Java instead) Complex applications, where structured programming is a necessity (type-checking of variables, function prototypes, etc.) Mission-critical applications upon which you are betting the future of the company Situations where security is important, where you need to guarantee the integrity of your system and protect 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 particularly clumsy and inefficient line-by-line fashion.) Need native support for multi-dimensional arrays Need data structures, such as linked lists or trees Need to generate / manipulate graphics or GUIs Need direct access to system hardware or external peripherals 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 all the world to see.) If any of the above applies, consider a more powerful scripting language -- perhaps Perl, Tcl, Python, Ruby -- or possibly a compiled language such as C, C++, or Java. Even then, prototyping the application as a shell script might still be a useful development step. We will be using Bash, an acronym [3] for "Bourne-Again shell" and a pun on Stephen Bourne's now classic Bourne shell. Bash has become a de facto standard for shell scripting on most flavors of UNIX. Most of the principles this book covers apply equally well to scripting with other shells, such as the Korn Shell, from which Bash derives some of its features, [4] and the C Shell and its variants. (Note that C Shell programming 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. It relies heavily on examples to illustrate various features of the shell. The example scripts work -- they've been tested, insofar as possible -- and some of them are even useful in real life. The reader can play with the actual working code of the examples in the source archive (s c r i p t n a m e . s hor s c r i p t n a m e . b a s h ), [5] give them execute permission (c h m o du + r xs c r i p t n a m e ), then run them to see what happens. Should the source archive not be available, then cut-and-paste from the HTML or pdf rendered versions. Be aware that some of the scripts presented here introduce features before they are explained, and this may require the reader to temporarily skip ahead for enlightenment. Unless otherwise noted, the author of this book wrote the example scripts that follow. His countenance was bold and bashed not. --Edmund Spenser

Chapter 2. Starting Off With a Sha-Bang


Shell programming is a 1950s juke box . . . --Larry Wall In the simplest case, a script is nothing more than a list of system commands stored in a file. At the very least, this saves the effort of retyping that particular sequence of commands each time it is invoked. Example 2-1. cleanup: A script to clean up log files in /var/log
#C l e a n u p #R u na sr o o t ,o fc o u r s e . c d/ v a r / l o g c a t/ d e v / n u l l>m e s s a g e s c a t/ d e v / n u l l>w t m p e c h o" L o gf i l e sc l e a n e du p . "

There is nothing unusual here, only a set of commands that could just as easily have been invoked one by one from the command-line on the console or in a terminal window. The advantages of placing the commands in a script go far beyond not having to retype them time and again. The script becomes a program -- a tool -- and it can easily be modified or customized for a particular application. Example 2-2. cleanup: An improved clean-up script
# ! / b i n / b a s h #P r o p e rh e a d e rf o raB a s hs c r i p t . #C l e a n u p ,v e r s i o n2 #R u na sr o o t ,o fc o u r s e . #I n s e r tc o d eh e r et op r i n te r r o rm e s s a g ea n de x i ti fn o tr o o t . L O G _ D I R = / v a r / l o g #V a r i a b l e sa r eb e t t e rt h a nh a r d c o d e dv a l u e s . c d$ L O G _ D I R c a t/ d e v / n u l l>m e s s a g e s c a t/ d e v / n u l l>w t m p

e c h o" L o g sc l e a n e du p . " e x i t# T h er i g h ta n dp r o p e rm e t h o do f" e x i t i n g "f r o mas c r i p t . # Ab a r e" e x i t "( n op a r a m e t e r )r e t u r n st h ee x i ts t a t u s # +o ft h ep r e c e d i n gc o m m a n d .

Now that's beginning to look like a real script. But we can go even farther . . . Example 2-3. cleanup: An enhanced and generalized version of above scripts.
# ! / b i n / b a s h #C l e a n u p ,v e r s i o n3 # W a r n i n g : # # T h i ss c r i p tu s e sq u i t ean u m b e ro ff e a t u r e st h a tw i l lb ee x p l a i n e d # +l a t e ro n . # B yt h et i m ey o u ' v ef i n i s h e dt h ef i r s th a l fo ft h eb o o k , # +t h e r es h o u l db en o t h i n gm y s t e r i o u sa b o u ti t .

L O G _ D I R = / v a r / l o g R O O T _ U I D = 0 #O n l yu s e r sw i t h$ U I D0h a v er o o tp r i v i l e g e s . L I N E S = 5 0 #D e f a u l tn u m b e ro fl i n e ss a v e d . E _ X C D = 8 6 #C a n ' tc h a n g ed i r e c t o r y ? E _ N O T R O O T = 8 7 #N o n r o o te x i te r r o r .

#R u na sr o o t ,o fc o u r s e . i f[" $ U I D "n e" $ R O O T _ U I D "] t h e n e c h o" M u s tb er o o tt or u nt h i ss c r i p t . " e x i t$ E _ N O T R O O T f i i f[n" $ 1 "] #T e s tw h e t h e rc o m m a n d l i n ea r g u m e n ti sp r e s e n t( n o n e m p t y ) . t h e n l i n e s = $ 1 e l s e l i n e s = $ L I N E S#D e f a u l t ,i fn o ts p e c i f i e do nc o m m a n d l i n e . f i

# S t e p h a n eC h a z e l a ss u g g e s t st h ef o l l o w i n g , # +a sab e t t e rw a yo fc h e c k i n gc o m m a n d l i n ea r g u m e n t s , # +b u tt h i si ss t i l lab i ta d v a n c e df o rt h i ss t a g eo ft h et u t o r i a l . # # E _ W R O N G A R G S = 8 5 #N o n n u m e r i c a la r g u m e n t( b a da r g u m e n tf o r m a t ) . # # c a s e" $ 1 "i n # " " )l i n e s = 5 0 ; ; # * [ ! 0 9 ] * )e c h o" U s a g e :` b a s e n a m e$ 0 `l i n e s t o c l e a n u p " ; # e x i t$ E _ W R O N G A R G S ; ; # * )l i n e s = $ 1 ; ; # e s a c # # *S k i pa h e a dt o" L o o p s "c h a p t e rt od e c i p h e ra l lt h i s .

c d$ L O G _ D I R i f[` p w d `! =" $ L O G _ D I R "] #o r i f[" $ P W D "! =" $ L O G _ D I R "] #N o ti n/ v a r / l o g ? t h e n e c h o" C a n ' tc h a n g et o$ L O G _ D I R . " e x i t$ E _ X C D f i #D o u b l e c h e c ki fi nr i g h td i r e c t o r yb e f o r em e s s i n gw i t hl o gf i l e . #F a rm o r ee f f i c i e n ti s : # #c d/ v a r / l o g| |{ # e c h o" C a n n o tc h a n g et on e c e s s a r yd i r e c t o r y . "> & 2 # e x i t$ E _ X C D ; #}

t a i ln$ l i n e sm e s s a g e s>m e s g . t e m p#S a v el a s ts e c t i o no fm e s s a g el o gf i l e . m vm e s g . t e m pm e s s a g e s #R e n a m ei ta ss y s t e ml o gf i l e .

# c a t/ d e v / n u l l>m e s s a g e s # *N ol o n g e rn e e d e d ,a st h ea b o v em e t h o di ss a f e r . c a t/ d e v / n u l l>w t m p # ' :>w t m p 'a n d' >w t m p ' h a v et h es a m ee f f e c t . e c h o" L o gf i l e sc l e a n e du p . " # N o t et h a tt h e r ea r eo t h e rl o gf i l e si n/ v a r / l o gn o ta f f e c t e d

# +b yt h i ss c r i p t . e x i t0 # Az e r or e t u r nv a l u ef r o mt h es c r i p tu p o ne x i ti n d i c a t e ss u c c e s s # +t ot h es h e l l .

Since you may not wish to wipe out the entire system log, this version of the script keeps the last section of the message log intact. You will constantly discover ways of fine-tuning previously written scripts for increased effectiveness. *** The sha-bang ( #!) [6] at the head of a script tells your system that this file is a set of commands to be fed to the command interpreter indicated. The #! is actually a two-byte [7] magic number, a special marker that designates a file type, or in this case an executable shell script (type m a nm a g i cfor more details on this fascinating topic). Immediately following the shabang is a path name. This is the path to the program that interprets the commands in the script, whether it be a shell, a programming language, or a utility. This command interpreter then executes the commands in the script, starting at the top (the line following the sha-bang line), and ignoring comments. [8]
# ! / b i n / s h # ! / b i n / b a s h # ! / u s r / b i n / p e r l # ! / u s r / b i n / t c l # ! / b i n / s e df # ! / b i n / a w kf

Each of the above script header lines calls a different command interpreter, be it / b i n / s h , the default shell (bash in a Linux system) or otherwise. [9] Using # ! / b i n / s h , the default Bourne shell in most commercial variants of UNIX, makes the script portable to non-Linux machines, though you sacrifice Bash-specific features. The script will, however, conform to the POSIX [10] sh standard. Note that the path given at the "sha-bang" must be correct, otherwise an error message -- usually "Command not found." -will be the only result of running the script. [11] #! can be omitted if the script consists only of a set of generic system commands, using no internal shell directives. The second example, above, requires the initial #!, since the variable assignment line, l i n e s = 5 0 , uses a shell-specific construct. [12] Note again that # ! / b i n / s hinvokes the default shell interpreter, which defaults to / b i n / b a s hon a Linux machine. This tutorial encourages a modular approach to constructing a script. Make note of and collect "boilerplate" code snippets that might be useful in future scripts. Eventually you will build quite an extensive library of nifty routines. As an example, the following script prolog tests whether the script has been invoked with the correct number of parameters.
E _ W R O N G _ A R G S = 8 5 s c r i p t _ p a r a m e t e r s = " ahmz " # a=a l l ,h=h e l p ,e t c . i f[$ #n e$ N u m b e r _ o f _ e x p e c t e d _ a r g s] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `$ s c r i p t _ p a r a m e t e r s " #` b a s e n a m e$ 0 `i st h es c r i p t ' sf i l e n a m e . e x i t$ E _ W R O N G _ A R G S f i

Many times, you will write a script that carries out one particular task. The first script in this chapter is an example. Later, it might occur to you to generalize the script to do other, similar tasks. Replacing the literal ("hard-wired") constants by variables is a step in that direction, as is replacing repetitive code blocks by functions.

2.1. Invoking the script

Having written the script, you can invoke it by s hs c r i p t n a m e , [13] or alternatively b a s hs c r i p t n a m e . (Not recommended is using s h< s c r i p t n a m e , since this effectively disables reading from s t d i nwithin the script.) Much more convenient is to make the script itself directly executable with a chmod. Either:
c h m o d5 5 5s c r i p t n a m e(gives everyone read/execute permission) [14]

or
c h m o d+ r xs c r i p t n a m e(gives everyone read/execute permission) c h m o du + r xs c r i p t n a m e(gives only the script owner read/execute permission)

Having made the script executable, you may now test it by . / s c r i p t n a m e . [15] If it begins with a "sha-bang" line, invoking the script calls the correct command interpreter to run it. As a final step, after testing and debugging, you would likely want to move it to / u s r / l o c a l / b i n(as root , of course), to make the script available to yourself and all other users as a systemwide executable. The script could then be invoked by simply typing scriptname [ENTER] from the command-line.

2.2. Preliminary Exercises


1. System administrators often write scripts to automate common tasks. Give several instances where such scripts would be useful. 2. Write a script that upon invocation shows the time and date, lists all logged-in users, and gives the system uptime. The script then saves this information to a logfile.

Part 2. Basics
Table of Contents 3. Special Characters 4. Introduction to Variables and Parameters 4.1. Variable Substitution 4.2. Variable Assignment 4.3. Bash Variables Are Untyped 4.4. Special Variable Types 5. Quoting 5.1. Quoting Variables 5.2. Escaping 6. Exit and Exit Status 7. Tests 7.1. Test Constructs 7.2. File test operators 7.3. Other Comparison Operators 7.4. Nested i f / t h e nCondition Tests 7.5. Testing Your Knowledge of Tests 8. Operations and Related Topics

8.1. Operators 8.2. Numerical Constants 8.3. The Double-Parentheses Construct 8.4. Operator Precedence

Chapter 3. Special Characters


What makes a character special? If it has a meaning beyond its literal meaning, a meta-meaning, then we refer to it as a special character. Along with commands and keywords, special characters are building blocks of Bash scripts. Special Characters Found In Scripts and Elsewhere # Comments. Lines beginning with a # (with the exception of #!) are comments and will not be executed.
#T h i sl i n ei sac o m m e n t .

Comments may also occur following the end of a command.


e c h o" Ac o m m e n tw i l lf o l l o w . "#C o m m e n th e r e . # ^N o t ew h i t e s p a c eb e f o r e#

Comments may also follow whitespace at the beginning of a line.


#At a bp r e c e d e st h i sc o m m e n t .

Comments may even be embedded within a pipe.


i n i t i a l = (` c a t" $ s t a r t f i l e "|s e de' / # / d '|t rd' \ n '| \ #D e l e t el i n e sc o n t a i n i n g' # 'c o m m e n tc h a r a c t e r . s e de' s / \ . / \ ./ g 'e' s / _ / _/ g ' `) #E x c e r p t e df r o ml i f e . s hs c r i p t

A command may not follow a comment on the same line. There is no method of terminating the comment, in order for "live code" to begin on the same line. Use a new line for the next command. Of course, a quoted or an escaped # in an echo statement does not begin a comment. Likewise, a # appears in certain parameter-substitution constructs and in numerical constant expressions.
e c h o" T h e#h e r ed o e sn o tb e g i nac o m m e n t . " e c h o' T h e#h e r ed o e sn o tb e g i nac o m m e n t . ' e c h oT h e\ #h e r ed o e sn o tb e g i nac o m m e n t . e c h oT h e#h e r eb e g i n sac o m m e n t . e c h o$ { P A T H # * : } #P a r a m e t e rs u b s t i t u t i o n ,n o tac o m m e n t . e c h o$ ( (2 # 1 0 1 0 1 1) ) #B a s ec o n v e r s i o n ,n o tac o m m e n t . #T h a n k s ,S . C .

The standard quoting and escape characters (" ' \) escape the #. Certain pattern matching operations also use the #. ; Command separator [semicolon]. Permits putting two or more commands on the same line.
e c h oh e l l o ;e c h ot h e r e

i f[x" $ f i l e n a m e "] ;t h e n # N o t et h es p a c ea f t e rt h es e m i c o l o n . # + ^ ^ e c h o" F i l e$ f i l e n a m ee x i s t s . " ;c p$ f i l e n a m e$ f i l e n a m e . b a k e l s e # ^ ^ e c h o" F i l e$ f i l e n a m en o tf o u n d . " ;t o u c h$ f i l e n a m e f i ;e c h o" F i l et e s tc o m p l e t e . "

Note that the ";" sometimes needs to be escaped. ;; Terminator in a case option [double semicolon].
c a s e" $ v a r i a b l e "i n a b c ) e c h o" \ $ v a r i a b l e=a b c "; ; x y z ) e c h o" \ $ v a r i a b l e=x y z "; ; e s a c

;;&, ;& Terminators in a case option (version 4+ of Bash). . "dot" command [period]. Equivalent to source (see Example 15-22). This is a bash builtin. . "dot", as a component of a filename. When working with filenames, a leading dot is the prefix of a "hidden" file, a file that an ls will not normally show.
b a s h $t o u c h. h i d d e n f i l e b a s h $l sl t o t a l1 0 r w r r 1b o z o r w r r 1b o z o r w r r 1b o z o

4 0 3 4J u l1 82 2 : 0 4d a t a 1 . a d d r e s s b o o k 4 6 0 2M a y2 51 3 : 5 8d a t a 1 . a d d r e s s b o o k . b a k 8 7 7D e c1 7 2 0 0 0e m p l o y m e n t . a d d r e s s b o o k

b a s h $l sa l t o t a l1 4 d r w x r w x r x 2b o z o d r w x - 5 2b o z o r w r r 1b o z o r w r r 1b o z o r w r r 1b o z o r w r w r 1b o z o

b o z o b o z o b o z o b o z o b o z o b o z o

1 0 2 4A u g2 92 0 : 5 4. / 3 0 7 2A u g2 92 0 : 5 1. . / 4 0 3 4J u l1 82 2 : 0 4d a t a 1 . a d d r e s s b o o k 4 6 0 2M a y2 51 3 : 5 8d a t a 1 . a d d r e s s b o o k . b a k 8 7 7D e c1 7 2 0 0 0e m p l o y m e n t . a d d r e s s b o o k 0A u g2 92 0 : 5 4. h i d d e n f i l e

When considering directory names, a single dot represents the current working directory, and two dots denote the parent directory.
b a s h $p w d / h o m e / b o z o / p r o j e c t s b a s h $c d. b a s h $p w d / h o m e / b o z o / p r o j e c t s b a s h $c d. . b a s h $p w d / h o m e / b o z o /

The dot often appears as the destination (directory) of a file movement command, in this context meaning current directory.
b a s h $c p/ h o m e / b o z o / c u r r e n t _ w o r k / j u n k / *.

Copy all the "junk" files to $PWD. . "dot" character match. When matching characters, as part of a regular expression, a "dot" matches a single character. " partial quoting [double quote]. "STRING" preserves (from interpretation) most of the special characters within STRING. See Chapter 5. ' full quoting [single quote]. 'STRING' preserves all special characters within STRING. This is a stronger form of quoting than "STRING" . See Chapter 5. , comma operator. The comma operator [16] links together a series of arithmetic operations. All are evaluated, but only the last one is returned.
l e t" t 2=( ( a=9 ,1 5/3 ) ) " #S e t" a=9 "a n d" t 2=1 5/3 "

The comma operator can also concatenate strings.


f o rf i l ei n/ { , u s r / } b i n / * c a l c # ^ F i n da l le x e c u t a b l ef i l e se n d i n gi n" c a l c " # + i n/ b i na n d/ u s r / b i nd i r e c t o r i e s . d o i f[x" $ f i l e "] t h e n e c h o$ f i l e f i d o n e #/ b i n / i p c a l c #/ u s r / b i n / k c a l c #/ u s r / b i n / o i d c a l c #/ u s r / b i n / o o c a l c

#T h a n ky o u ,R o r yW i n s t o n ,f o rp o i n t i n gt h i so u t .

,, , Lowercase conversion in parameter substitution (added in version 4 of Bash). \ escape [backslash]. A quoting mechanism for single characters.
\ Xescapes the character X.

This has the effect of "quoting" X, equivalent to 'X'. The \ may be used to quote " and ', so they are expressed literally. See Chapter 5 for an in-depth explanation of escaped characters. /

Filename path separator [forward slash]. Separates the components of a filename (as in / h o m e / b o z o / p r o j e c t s / M a k e f i l e ). This is also the division arithmetic operator. ` command substitution. The `command` construct makes available the output of command for assignment to a variable. This is also known as backquotes or backticks. : null command [colon]. This is the shell equivalent of a "NOP" (n oo p , a do-nothing operation). It may be considered a synonym for the shell builtin true. The ":" command is itself a Bash builtin, and its exit status is true (0).
: e c h o$ ? #0

Endless loop:
w h i l e: d o o p e r a t i o n 1 o p e r a t i o n 2 . . . o p e r a t i o n n d o n e #S a m ea s : # w h i l et r u e # d o # . . . # d o n e

Placeholder in if/then test:


i fc o n d i t i o n t h e n: #D on o t h i n ga n db r a n c ha h e a d e l s e #O re l s e. . . t a k e s o m e a c t i o n f i

Provide a placeholder where a binary operation is expected, see Example 8-2 and default parameters.
:$ { u s e r n a m e = ` w h o a m i ` } #$ { u s e r n a m e = ` w h o a m i ` } # G i v e sa ne r r o rw i t h o u tt h el e a d i n g: u n l e s s" u s e r n a m e "i sac o m m a n do rb u i l t i n . . . #F r o m" u s a g e m e s s a g e . s he x a m p l es c r i p t .

:$ { 1 ? " U s a g e :$ 0A R G U M E N T " }

Provide a placeholder where a command is expected in a here document. See Example 19-10. Evaluate string of variables using parameter substitution (as in Example 10-7).
:$ { H O S T N A M E ? }$ { U S E R ? }$ { M A I L ? } # P r i n t se r r o rm e s s a g e # +i fo n eo rm o r eo fe s s e n t i a le n v i r o n m e n t a lv a r i a b l e sn o ts e t .

Variable expansion / substring replacement. In combination with the > redirection operator, truncates a file to zero length, without changing its permissions. If the file did not previously exist, creates it.
:>d a t a . x x x #F i l e" d a t a . x x x "n o we m p t y .

#S a m ee f f e c ta s c a t/ d e v / n u l l> d a t a . x x x #H o w e v e r ,t h i sd o e sn o tf o r kan e wp r o c e s s ,s i n c e" : "i sab u i l t i n .

See also Example 16-15. In combination with the >> redirection operator, has no effect on a pre-existing target file (: > >t a r g e t _ f i l e ). If the file did not previously exist, creates it. This applies to regular files, not pipes, symlinks, and certain special files. May be used to begin a comment line, although this is not recommended. Using # for a comment turns off error checking for the remainder of that line, so almost anything may appear in a comment. However, this is not the case with :.
:T h i si sac o m m e n tt h a tg e n e r a t e sa ne r r o r ,(i f[$ xe q3 ]) .

The ":" serves as a field separator, in / e t c / p a s s w d , and in the $PATH variable.


b a s h $e c h o$ P A T H / u s r / l o c a l / b i n : / b i n : / u s r / b i n : / u s r / X 1 1 R 6 / b i n : / s b i n : / u s r / s b i n : / u s r / g a m e s

A colon is acceptable as a function name.


: ( ) { e c h o" T h en a m eo ft h i sf u n c t i o ni s" $ F U N C N A M E " #W h yu s eac o l o na saf u n c t i o nn a m e ? #I t ' saw a yo fo b f u s c a t i n gy o u rc o d e . } : #T h en a m eo ft h i sf u n c t i o ni s:

This is not portable behavior, and therefore not a recommended practice. A colon can serve as a placeholder in an otherwise empty function.
n o t _ e m p t y( ) { : }#C o n t a i n sa:( n u l lc o m m a n d ) ,a n ds oi sn o te m p t y .

! reverse (or negate) the sense of a test or exit status [bang]. The ! operator inverts the exit status of the command to which it is applied (see Example 6-2). It also inverts the meaning of a test operator. This can, for example, change the sense of equal ( = ) to not-equal ( != ). The ! operator is a Bash keyword. In a different context, the ! also appears in indirect variable references. In yet another context, from the command line, the ! invokes the Bash history mechanism (see Appendix L). Note that within a script, the history mechanism is disabled. * wild card [asterisk]. The * character serves as a "wild card" for filename expansion in globbing. By itself, it matches every filename in a given directory.
b a s h $e c h o* a b s b o o k . s g m la d d d r i v e . s ha g r a m . s ha l i a s . s h

The * also represents any number (or zero) characters in a regular expression.

* arithmetic operator. In the context of arithmetic operations, the * denotes multiplication. ** A double asterisk can represent the exponentiation operator or extended file-match globbing. ? test operator. Within certain expressions, the ? indicates a test for a condition. In a double-parentheses construct, the ? can serve as an element of a C-style trinary operator. [17]
c o n d i t i o n ?r e s u l t i f t r u e :r e s u l t i f f a l s e ( (v a r 0=v a r 1 < 9 8 ? 9 : 2 1) ) # ^^ #i f[" $ v a r 1 "l t9 8] #t h e n # v a r 0 = 9 #e l s e # v a r 0 = 2 1 #f i

In a parameter substitution expression, the ? tests whether a variable has been set. ? wild card. The ? character serves as a single-character "wild card" for filename expansion in globbing, as well as representing one character in an extended regular expression. $ Variable substitution (contents of a variable).
v a r 1 = 5 v a r 2 = 2 3 s k i d o o e c h o$ v a r 1 e c h o$ v a r 2 #5 #2 3 s k i d o o

A $ prefixing a variable name indicates the value the variable holds. $ end-of-line. In a regular expression, a "$" addresses the end of a line of text. ${} Parameter substitution. $' ... ' Quoted string expansion. This construct expands single or multiple escaped octal or hex values into ASCII [18] or Unicode characters. $*, $@ positional parameters. $? exit status variable. The $? variable holds the exit status of a command, a function, or of the script itself.

$$ process ID variable. The $$ variable holds the process ID [19] of the script in which it appears. () command group.
( a = h e l l o ;e c h o$ a )

A listing of commands within p a r e n t h e s e sstarts a subshell. Variables inside parentheses, within the subshell, are not visible to the rest of the script. The parent process, the script, cannot read variables created in the child process, the subshell.
a = 1 2 3 (a = 3 2 1 ;) e c h o" a=$ a " #a=1 2 3 #" a "w i t h i np a r e n t h e s e sa c t sl i k eal o c a lv a r i a b l e .

array initialization.
A r r a y = ( e l e m e n t 1e l e m e n t 2e l e m e n t 3 )

{xxx,yyy,zzz,...} Brace expansion.


e c h o\ " { T h e s e , w o r d s , a r e , q u o t e d } \ " #" T h e s e "" w o r d s "" a r e "" q u o t e d " #"p r e f i xa n ds u f f i x

c a t{ f i l e 1 , f i l e 2 , f i l e 3 }>c o m b i n e d _ f i l e #C o n c a t e n a t e st h ef i l e sf i l e 1 ,f i l e 2 ,a n df i l e 3i n t oc o m b i n e d _ f i l e . c pf i l e 2 2 . { t x t , b a c k u p } #C o p i e s" f i l e 2 2 . t x t "t o" f i l e 2 2 . b a c k u p "

A command may act upon a comma-separated list of file specs within b r a c e s . [20] Filename expansion (globbing) applies to the file specs between the braces. No spaces allowed within the braces unless the spaces are quoted or escaped.
e c h o{ f i l e 1 , f i l e 2 } \: { \A , "B " , 'C ' } f i l e 1:Af i l e 1:Bf i l e 1:Cf i l e 2:Af i l e 2:Bf i l e 2:C

{a..z} Extended Brace expansion.


e c h o{ a . . z }#abcdefghijklmnopqrstuvwxyz #E c h o e sc h a r a c t e r sb e t w e e naa n dz . e c h o{ 0 . . 3 }#0123 #E c h o e sc h a r a c t e r sb e t w e e n0a n d3 .

b a s e 6 4 _ c h a r s e t = ({ A . . Z }{ a . . z }{ 0 . . 9 }+/=) #I n i t i a l i z i n ga na r r a y ,u s i n ge x t e n d e db r a c ee x p a n s i o n . #F r o mv l a d z ' s" b a s e 6 4 . s h "e x a m p l es c r i p t .

The {a..z} extended brace expansion construction is a feature introduced in version 3 of Bash. {}

Block of code [curly brackets]. Also referred to as an inline group, this construct, in effect, creates an anonymous function (a function without a name). However, unlike in a "standard" function, the variables inside a code block remain visible to the remainder of the script.
b a s h ${l o c a la ; a = 1 2 3 ;} b a s h :l o c a l :c a no n l yb eu s e di na f u n c t i o n

a = 1 2 3 {a = 3 2 1 ;} e c h o" a=$ a " #T h a n k s ,S . C .

#a=3 2 1

( v a l u ei n s i d ec o d eb l o c k )

The code block enclosed in braces may have I/O redirected to and from it. Example 3-1. Code blocks and I/O redirection
# ! / b i n / b a s h #R e a d i n gl i n e si n/ e t c / f s t a b . F i l e = / e t c / f s t a b { r e a dl i n e 1 r e a dl i n e 2 }<$ F i l e e c h o" F i r s tl i n ei n$ F i l ei s : " e c h o" $ l i n e 1 " e c h o e c h o" S e c o n dl i n ei n$ F i l ei s : " e c h o" $ l i n e 2 " e x i t0 #N o w ,h o wd oy o up a r s et h es e p a r a t ef i e l d so fe a c hl i n e ? #H i n t :u s ea w k ,o r... #...H a n s J o e r gD i e r ss u g g e s t su s i n gt h e" s e t "B a s hb u i l t i n .

Example 3-2. Saving the output of a code block to a file


# ! / b i n / b a s h #r p m c h e c k . s h # Q u e r i e sa nr p mf i l ef o rd e s c r i p t i o n ,l i s t i n g , # +a n dw h e t h e ri tc a nb ei n s t a l l e d . # S a v e so u t p u tt oaf i l e . # # T h i ss c r i p ti l l u s t r a t e su s i n gac o d eb l o c k . S U C C E S S = 0 E _ N O A R G S = 6 5 i f[z" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `r p m f i l e " e x i t$ E _ N O A R G S f i {#B e g i nc o d eb l o c k . e c h o e c h o" A r c h i v eD e s c r i p t i o n : " r p mq p i$ 1 #Q u e r yd e s c r i p t i o n .

e c h o e c h o" A r c h i v eL i s t i n g : " r p mq p l$ 1 #Q u e r yl i s t i n g . e c h o r p mit e s t$ 1 #Q u e r yw h e t h e rr p mf i l ec a nb ei n s t a l l e d . i f[" $ ? "e q$ S U C C E S S] t h e n e c h o" $ 1c a nb ei n s t a l l e d . " e l s e e c h o" $ 1c a n n o tb ei n s t a l l e d . " f i e c h o #E n dc o d eb l o c k . }>" $ 1 . t e s t " #R e d i r e c t so u t p u to fe v e r y t h i n gi nb l o c kt of i l e . e c h o" R e s u l t so fr p mt e s ti nf i l e$ 1 . t e s t " #S e er p mm a np a g ef o re x p l a n a t i o no fo p t i o n s . e x i t0

Unlike a command group within (parentheses), as above, a code block enclosed by {braces} will not normally launch a subshell. [21] {} placeholder for text. Used after xargs i(replace strings option). The {} double curly brackets are a placeholder for output text.
l s.|x a r g sitc p. / { }$ 1 # ^ ^ ^ ^ #F r o m" e x 4 2 . s h "( c o p y d i r . s h )e x a m p l e .

{} \; pathname. Mostly used in find constructs. This is not a shell builtin. Definition: A pathname is a filename that includes the complete path. As an example, / h o m e / b o z o / N o t e s / T h u r s d a y / s c h e d u l e . t x t . This is sometimes referred to as the absolute path. The ";" ends the e x e coption of a find command sequence. It needs to be escaped to protect it from interpretation by the shell. [] test. Test expression between [ ]. Note that [ is part of the shell builtin test (and a synonym for it), not a link to the external command / u s r / b i n / t e s t . [[ ]] test. Test expression between [[ ]]. More flexible than the single-bracket [ ] test, this is a shell keyword. See the discussion on the [[ ... ]] construct. [] array element. In the context of an array, brackets set off the numbering of each element of that array.

A r r a y [ 1 ] = s l o t _ 1 e c h o$ { A r r a y [ 1 ] }

[] range of characters. As part of a regular expression, brackets delineate a range of characters to match. $[ ... ] integer expansion. Evaluate integer expression between $[ ].
a = 3 b = 7 e c h o$ [ $ a + $ b ] e c h o$ [ $ a * $ b ] #1 0 #2 1

Note that this usage is deprecated, and has been replaced by the (( ... )) construct. (( )) integer expansion. Expand and evaluate integer expression between (( )). See the discussion on the (( ... )) construct. > &> >& >> < <> redirection.
s c r i p t n a m e> f i l e n a m eredirects the output of s c r i p t n a m eto

file f i l e n a m e . Overwrite f i l e n a m eif it already

exists.
c o m m a n d& > f i l e n a m eredirects both the s t d o u tand

the s t d e r rof c o m m a n dto f i l e n a m e .

This is useful for suppressing output when testing for a condition. For example, let us test whether a certain command exists.
b a s h $t y p eb o g u s _ c o m m a n d& > / d e v / n u l l

b a s h $e c h o$ ? 1

Or in a script:
c o m m a n d _ t e s t( ){t y p e" $ 1 "& > / d e v / n u l l ;} # ^ c m d = r m d i r #L e g i t i m a t ec o m m a n d . c o m m a n d _ t e s t$ c m d ;e c h o$ ? #0

c m d = b o g u s _ c o m m a n d #I l l e g i t i m a t ec o m m a n d c o m m a n d _ t e s t$ c m d ;e c h o$ ? #1

c o m m a n d> & 2redirects s t d o u tof c o m m a n dto s t d e r r . s c r i p t n a m e> > f i l e n a m eappends the output of s c r i p t n a m eto

file f i l e n a m e . If f i l e n a m edoes not already

exist, it is created.
[ i ] < > f i l e n a m eopens file f i l e n a m efor reading and

writing, and assigns file descriptor i to it. If f i l e n a m edoes

not exist, it is created. process substitution.


( c o m m a n d ) > < ( c o m m a n d )

In a different context, the "<" and ">" characters act as string comparison operators. In yet another context, the "<" and ">" characters act as integer comparison operators. See also Example 16-9. << redirection used in a here document. <<< redirection used in a here string. <, > ASCII comparison.
v e g 1 = c a r r o t s v e g 2 = t o m a t o e s i f[ [" $ v e g 1 "<" $ v e g 2 "] ] t h e n e c h o" A l t h o u g h$ v e g 1p r e c e d e$ v e g 2i nt h ed i c t i o n a r y , " e c h on" t h i sd o e sn o tn e c e s s a r i l yi m p l ya n y t h i n g" e c h o" a b o u tm yc u l i n a r yp r e f e r e n c e s . " e l s e e c h o" W h a tk i n do fd i c t i o n a r ya r ey o uu s i n g ,a n y h o w ? " f i

\<, \> word boundary in a regular expression.


b a s h $g r e p' \ < t h e \ > 't e x t f i l e

| pipe. Passes the output (s t d o u t ) of a previous command to the input (s t d i n ) of the next one, or to the shell. This is a method of chaining commands together.
e c h ol sl|s h # P a s s e st h eo u t p u to f" e c h ol sl "t ot h es h e l l , # +w i t ht h es a m er e s u l ta sas i m p l e" l sl " .

c a t* . l s t|s o r t|u n i q #M e r g e sa n ds o r t sa l l" . l s t "f i l e s ,t h e nd e l e t e sd u p l i c a t el i n e s .

A pipe, as a classic method of interprocess communication, sends the s t d o u tof one process to the s t d i nof another. In a typical case, a command, such as cat or echo, pipes a stream of data to a filter, a command that

transforms its input for processing. [22]


c a t$ f i l e n a m e 1$ f i l e n a m e 2|g r e p$ s e a r c h _ w o r d

For an interesting note on the complexity of using UNIX pipes, see the UNIX FAQ, Part 3. The output of a command or commands may be piped to a script.
# ! / b i n / b a s h #u p p e r c a s e . s h:C h a n g e si n p u tt ou p p e r c a s e . t r' a z '' A Z ' # L e t t e rr a n g e sm u s tb eq u o t e d # +t op r e v e n tf i l e n a m eg e n e r a t i o nf r o ms i n g l e l e t t e rf i l e n a m e s . e x i t0

Now, let us pipe the output of ls -l to this script.


b a s h $l sl|. / u p p e r c a s e . s h R W R W R 1B O Z O B O Z O R W R W R 1B O Z O B O Z O R W R R 1B O Z O B O Z O 1 0 9A P R 71 9 : 4 91 . T X T 1 0 9A P R1 41 6 : 4 82 . T X T 7 2 5A P R2 02 0 : 5 6D A T A F I L E

The s t d o u tof each process in a pipe must be read as the s t d i nof the next. If this is not the case, the data stream will block , and the pipe will not behave as expected.
c a tf i l e 1f i l e 2|l sl|s o r t #T h eo u t p u tf r o m" c a tf i l e 1f i l e 2 "d i s a p p e a r s .

A pipe runs as a child process, and therefore cannot alter script variables.
v a r i a b l e = " i n i t i a l _ v a l u e " e c h o" n e w _ v a l u e "|r e a dv a r i a b l e e c h o" v a r i a b l e=$ v a r i a b l e " #v a r i a b l e=i n i t i a l _ v a l u e

If one of the commands in the pipe aborts, this prematurely terminates execution of the pipe. Called a broken pipe, this condition sends a S I G P I P Esignal. >| force redirection (even if the noclobber option is set). This will forcibly overwrite an existing file. || OR logical operator. In a test construct, the || operator causes a return of 0 (success) if either of the linked test conditions is true. & Run job in background. A command followed by an & will run in the background.
b a s h $s l e e p1 0& [ 1 ]8 5 0 [ 1 ] + D o n e

s l e e p1 0

Within a script, commands and even loops may run in the background. Example 3-3. Running a loop in the background
# ! / b i n / b a s h #b a c k g r o u n d l o o p . s h f o rii n1234567891 0 d o #F i r s tl o o p .

e c h on" $ i" d o n e&#R u nt h i sl o o pi nb a c k g r o u n d . #W i l ls o m e t i m e se x e c u t ea f t e rs e c o n dl o o p . e c h o #T h i s' e c h o 's o m e t i m e sw i l ln o td i s p l a y . #S e c o n dl o o p .

f o rii n1 11 21 31 41 51 61 71 81 92 0 d o e c h on" $ i" d o n e e c h o

#T h i s' e c h o 's o m e t i m e sw i l ln o td i s p l a y .

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #T h ee x p e c t e do u t p u tf r o mt h es c r i p t : #1234567891 0 #1 11 21 31 41 51 61 71 81 92 0 #S o m e t i m e s ,t h o u g h ,y o ug e t : #1 11 21 31 41 51 61 71 81 92 0 #1234567891 0b o z o$ #( T h es e c o n d' e c h o 'd o e s n ' te x e c u t e .W h y ? ) #O c c a s i o n a l l ya l s o : #1234567891 01 11 21 31 41 51 61 71 81 92 0 #( T h ef i r s t' e c h o 'd o e s n ' te x e c u t e .W h y ? ) #V e r yr a r e l ys o m e t h i n gl i k e : #1 11 21 31234567891 01 41 51 61 71 81 92 0 #T h ef o r e g r o u n dl o o pp r e e m p t st h eb a c k g r o u n do n e . e x i t0 # N a s i m u d d i nA n s a r is u g g e s t sa d d i n g s l e e p1 # +a f t e rt h e e c h on" $ i " i nl i n e s6a n d1 4 , # +f o rs o m er e a lf u n .

A command run in the background within a script may cause the script to hang, waiting for a keystroke. Fortunately, there is a remedy for this. && AND logical operator. In a test construct, the && operator causes a return of 0 (success) only if both the linked test conditions are true. option, prefix. Option flag for a command or filter. Prefix for an operator. Prefix for a default parameter in parameter substitution.
C O M M A N D[ O p t i o n 1 ] [ O p t i o n 2 ] [ . . . ] l sa l s o r td f u$ f i l e n a m e i f[$ f i l e 1o t$ f i l e 2] t h e n# ^ e c h o" F i l e$ f i l e 1i so l d e rt h a n$ f i l e 2 . " f i i f[" $ a "e q" $ b "] t h e n# ^ e c h o" $ ai se q u a lt o$ b . " f i

i f[" $ c "e q2 4a" $ d "e q4 7] t h e n# ^ ^ e c h o" $ ce q u a l s2 4a n d$ de q u a l s4 7 . " f i

p a r a m 2 = $ { p a r a m 1 : $ D E F A U L T V A L } # ^

-The double-dash -prefixes long (verbatim) options to commands.


s o r ti g n o r e l e a d i n g b l a n k s

Used with a Bash builtin, it means the end of options to that particular command. This provides a handy means of removing files whose names begin with a dash.
b a s h $l sl r w r r -1b o z ob o z o0N o v2 51 2 : 2 9b a d n a m e

b a s h $r m-b a d n a m e b a s h $l sl t o t a l0

The double-dash is also used in conjunction with set.


s e t-$ v a r i a b l e(as in Example 15-18)

redirection from/to s t d i nor s t d o u t[dash].


b a s h $c a ta b c a b c . . . C t l D

As expected, c a t -echoes s t d i n , in this case keyboarded user input, to s t d o u t . But, does I/O redirection using have real-world applications?
( c d/ s o u r c e / d i r e c t o r y& &t a rc f-.)|( c d/ d e s t / d i r e c t o r y& &t a rx p v f) #M o v ee n t i r ef i l et r e ef r o mo n ed i r e c t o r yt oa n o t h e r #[ c o u r t e s yA l a nC o x< a . c o x @ s w a n s e a . a c . u k > ,w i t ham i n o rc h a n g e ] #1 )c d/ s o u r c e / d i r e c t o r y # S o u r c ed i r e c t o r y ,w h e r et h ef i l e st ob em o v e da r e . #2 )& & # " A n d l i s t " :i ft h e' c d 'o p e r a t i o ns u c c e s s f u l , # t h e ne x e c u t et h en e x tc o m m a n d . #3 )t a rc f-. # T h e' c 'o p t i o n' t a r 'a r c h i v i n gc o m m a n dc r e a t e san e wa r c h i v e , # t h e' f '( f i l e )o p t i o n ,f o l l o w e db y' 'd e s i g n a t e st h et a r g e tf i l e # a ss t d o u t ,a n dd oi ti nc u r r e n td i r e c t o r yt r e e( ' . ' ) . #4 )| # P i p e dt o. . . #5 )(. . .) # as u b s h e l l #6 )c d/ d e s t / d i r e c t o r y

# C h a n g et ot h ed e s t i n a t i o nd i r e c t o r y . #7 )& & # " A n d l i s t " ,a sa b o v e #8 )t a rx p v f# U n a r c h i v e( ' x ' ) ,p r e s e r v eo w n e r s h i pa n df i l ep e r m i s s i o n s( ' p ' ) , # a n ds e n dv e r b o s em e s s a g e st os t d o u t( ' v ' ) , # r e a d i n gd a t af r o ms t d i n( ' f 'f o l l o w e db y' ' ) . # # N o t et h a t' x 'i sac o m m a n d ,a n d' p ' ,' v ' ,' f 'a r eo p t i o n s . # #W h e w !

#M o r ee l e g a n tt h a n ,b u te q u i v a l e n tt o : # c ds o u r c e / d i r e c t o r y # t a rc f-.|( c d. . / d e s t / d i r e c t o r y ;t a rx p v f) # # A l s oh a v i n gs a m ee f f e c t : #c pa/ s o u r c e / d i r e c t o r y / */ d e s t / d i r e c t o r y # O r : #c pa/ s o u r c e / d i r e c t o r y / */ s o u r c e / d i r e c t o r y / . [ ^ . ] */ d e s t / d i r e c t o r y # I ft h e r ea r eh i d d e nf i l e si n/ s o u r c e / d i r e c t o r y . b u n z i p 2cl i n u x 2 . 6 . 1 6 . t a r . b z 2|t a rx v f# u n c o m p r e s st a rf i l e |t h e np a s si tt o" t a r " # I f" t a r "h a sn o tb e e np a t c h e dt oh a n d l e" b u n z i p 2 " , # +t h i sn e e d st ob ed o n ei nt w od i s c r e t es t e p s ,u s i n gap i p e . # T h ep u r p o s eo ft h ee x e r c i s ei st ou n a r c h i v e" b z i p p e d "k e r n e ls o u r c e .

Note that in this context the "-" is not itself a Bash operator, but rather an option recognized by certain UNIX utilities that write to s t d o u t , such as tar, cat, etc.
b a s h $e c h o" w h a t e v e r "|c a tw h a t e v e r

Where a filename is expected, -redirects output to s t d o u t(sometimes seen with t a rc f ), or accepts input from s t d i n , rather than from a file. This is a method of using a file-oriented utility as a filter in a pipe.
b a s h $f i l e U s a g e :f i l e[ b c i k n v z L ][ fn a m e f i l e ][ mm a g i c f i l e s ]f i l e . . .

By itself on the command-line, file fails with an error message. Add a "-" for a more useful result. This causes the shell to await user input.
b a s h $f i l ea b c s t a n d a r di n p u t : A S C I It e x t

b a s h $f i l e# ! / b i n / b a s h s t a n d a r di n p u t :

B o u r n e A g a i ns h e l ls c r i p tt e x te x e c u t a b l e

Now the command accepts input from s t d i nand analyzes it. The "-" can be used to pipe s t d o u tto other commands. This permits such stunts as prepending lines to a file. Using diff to compare a file with a section of another:
g r e pL i n u xf i l e 1|d i f ff i l e 2-

Finally, a real-world example using -with tar.

Example 3-4. Backup of all files changed in last day


# ! / b i n / b a s h # B a c k su pa l lf i l e si nc u r r e n td i r e c t o r ym o d i f i e dw i t h i nl a s t2 4h o u r s # +i na" t a r b a l l "( t a r r e da n dg z i p p e df i l e ) . B A C K U P F I L E = b a c k u p $ ( d a t e+ % m % d % Y ) # E m b e d sd a t ei nb a c k u pf i l e n a m e . # T h a n k s ,J o s h u aT s c h i d a ,f o rt h ei d e a . a r c h i v e = $ { 1 : $ B A C K U P F I L E } # I fn ob a c k u p a r c h i v ef i l e n a m es p e c i f i e do nc o m m a n d l i n e , # +i tw i l ld e f a u l tt o" b a c k u p M M D D Y Y Y Y . t a r . g z . " t a rc v f-` f i n d.m t i m e1t y p efp r i n t `>$ a r c h i v e . t a r g z i p$ a r c h i v e . t a r e c h o" D i r e c t o r y$ P W Db a c k e du pi na r c h i v ef i l e\ " $ a r c h i v e . t a r . g z \ " . "

# S t e p h a n eC h a z e l a sp o i n t so u tt h a tt h ea b o v ec o d ew i l lf a i l # +i ft h e r ea r et o om a n yf i l e sf o u n d # +o ri fa n yf i l e n a m e sc o n t a i nb l a n kc h a r a c t e r s . #H es u g g e s t st h ef o l l o w i n ga l t e r n a t i v e s : ## f i n d.m t i m e1t y p efp r i n t 0|x a r g s0t a rr v f" $ a r c h i v e . t a r " # u s i n gt h eG N Uv e r s i o no f" f i n d " .

# f i n d.m t i m e1t y p efe x e ct a rr v f" $ a r c h i v e . t a r "' { } '\ ; # p o r t a b l et oo t h e rU N I Xf l a v o r s ,b u tm u c hs l o w e r . #-

e x i t0

Filenames beginning with "-" may cause problems when coupled with the "-" redirection operator. A script should check for this and add an appropriate prefix to such filenames, for example . / F I L E N A M E ,$ P W D / F I L E N A M E , or $ P A T H N A M E / F I L E N A M E . If the value of a variable begins with a , this may likewise create problems.
v a r = " n " e c h o$ v a r #H a st h ee f f e c to f" e c h on " ,a n do u t p u t sn o t h i n g .

previous working directory. A cd - command changes to the previous working directory. This uses the $OLDPWD environmental variable. Do not confuse the "-" used in this sense with the "-" redirection operator just discussed. The interpretation of the "-" depends on the context in which it appears. Minus. Minus sign in an arithmetic operation. = Equals. Assignment operator
a = 2 8 e c h o$ a #2 8

In a different context, the "=" is a string comparison operator.

+ Plus. Addition arithmetic operator. In a different context, the + is a Regular Expression operator. + Option. Option flag for a command or filter. Certain commands and builtins use the +to enable certain options and the -to disable them. In parameter substitution, the +prefixes an alternate value that a variable expands to. % modulo. Modulo (remainder of a division) arithmetic operation.
l e t" z=5%3 " e c h o$ z #2

In a different context, the % is a pattern matching operator. ~ home directory [tilde]. This corresponds to the $HOME internal variable. ~ b o z ois bozo's home directory, and ls ~bozo lists the contents of it. ~/ is the current user's home directory, and ls ~/ lists the contents of it.
b a s h $e c h o~ b o z o / h o m e / b o z o b a s h $e c h o~ / h o m e / b o z o b a s h $e c h o~ / / h o m e / b o z o / b a s h $e c h o~ : / h o m e / b o z o : b a s h $e c h o~ n o n e x i s t e n t u s e r ~ n o n e x i s t e n t u s e r

~+ current working directory. This corresponds to the $PWD internal variable. ~previous working directory. This corresponds to the $OLDPWD internal variable. =~ regular expression match. This operator was introduced with version 3 of Bash. ^ beginning-of-line. In a regular expression, a "^" addresses the beginning of a line of text. ^, ^^ Uppercase conversion in parameter substitution (added in version 4 of Bash).

Control Characters change the behavior of the terminal or text display. A control character is a CONTROL + key combination (pressed simultaneously). A control character may also be written in octal or hexadecimal notation, following an escape. Control characters are not normally useful inside a script.
C t l A

Moves cursor to beginning of line of text (on the command-line).


C t l B B a c k s p a c e(nondestructive). C t l C B r e a k . Terminate a foreground C t l D

job.

Log out from a shell (similar to exit).


E O F(end-of-file).

This also terminates input from s t d i n .

When typing text on the console or in an xterm window, C t l Derases the character under the cursor. When there are no characters present, C t l Dlogs out of the session, as expected. In an xterm window, this has the effect of closing the window.
C t l E

Moves cursor to end of line of text (on the command-line).


C t l F

Moves cursor forward one character position (on the command-line).


C t l G B E L . On some old-time teletype terminals, C t l H R u b o u t(destructive backspace).

this would actually ring a bell. In an xterm it might beep.

Erases characters the cursor backs over while backspacing.

# ! / b i n / b a s h #E m b e d d i n gC t l Hi nas t r i n g . a = " ^ H ^ H " e c h o" a b c d e f " e c h o e c h on" a b c d e f $ a" # S p a c ea te n d ^ e c h o e c h on" a b c d e f $ a " # N os p a c ea te n d e c h o ;e c h o #C o n s t a n t i nH a g e m e i e rs u g g e s t st r y i n g : #a = $ ' \ 0 1 0 \ 0 1 0 ' #T w oC t l H ' s-b a c k s p a c e s #c t l Vc t l H ,u s i n gv i / v i m #a b c d e f #a b c df ^ B a c k s p a c e st w i c e . #a b c d e f ^D o e s n ' tb a c k s p a c e( w h y ? ) . #R e s u l t sm a yn o tb eq u i t ea se x p e c t e d .

#a = $ ' \ b \ b ' #a = $ ' \ x 0 8 \ x 0 8 ' #B u t ,t h i sd o e sn o tc h a n g et h er e s u l t s . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #N o w ,t r yt h i s . r u b o u t = " ^ H ^ H ^ H ^ H ^ H " e c h on" 1 2 3 4 5 6 7 8 " s l e e p2 e c h on" $ r u b o u t " s l e e p2 C t l I H o r i z o n t a lt a b . C t l J N e w l i n e(line feed). C t l K V e r t i c a lt a b . #5xC t l H .

In a script, may also be expressed in octal notation -- '\012' or in hexadecimal -- '\x0a'.

When typing text on the console or in an xterm window, C t l Kerases from the character under the cursor to end of line. Within a script, C t l Kmay behave differently, as in Lee Lee Maschmeyer's example, below.
C t l L F o r m f e e d(clear the terminal screen).

In a terminal, this has the same effect as the clear command. When sent to a printer, a C t l Lcauses an advance to end of the paper sheet.
C t l M C a r r i a g er e t u r n . # ! / b i n / b a s h #T h a n ky o u ,L e eM a s c h m e y e r ,f o rt h i se x a m p l e . r e a dn1sp\ $ ' C o n t r o l Ml e a v e sc u r s o ra tb e g i n n i n go ft h i sl i n e .P r e s sE n t e r .\ x 0 d ' #O fc o u r s e ,' 0 d 'i st h eh e xe q u i v a l e n to fC o n t r o l M . e c h o> & 2 # T h e' s 'm a k e sa n y t h i n gt y p e ds i l e n t , # +s oi ti sn e c e s s a r yt og ot on e wl i n ee x p l i c i t l y . r e a dn1sp$ ' C o n t r o l Jl e a v e sc u r s o ro nn e x tl i n e .\ x 0 a ' # ' 0 a 'i st h eh e xe q u i v a l e n to fC o n t r o l J ,l i n e f e e d . e c h o> & 2 # # # r e a dn1sp$ ' A n dC o n t r o l K \ x 0 b g o e ss t r a i g h td o w n . ' e c h o> & 2 # C o n t r o l Ki sv e r t i c a lt a b . #Ab e t t e re x a m p l eo ft h ee f f e c to fav e r t i c a lt a bi s : v a r = $ ' \ x 0 a T h i si st h eb o t t o ml i n e \ x 0 b T h i si st h et o pl i n e \ x 0 a ' e c h o" $ v a r " # T h i sw o r k st h es a m ew a ya st h ea b o v ee x a m p l e .H o w e v e r : e c h o" $ v a r "|c o l # T h i sc a u s e st h er i g h te n do ft h el i n et ob eh i g h e rt h a nt h el e f te n d . # I ta l s oe x p l a i n sw h yw es t a r t e da n de n d e dw i t hal i n ef e e d-

# +t oa v o i dag a r b l e ds c r e e n . #A sL e eM a s c h m e y e re x p l a i n s : ## I nt h e[ f i r s tv e r t i c a lt a be x a m p l e ]...t h ev e r t i c a lt a b # +m a k e st h ep r i n t i n gg os t r a i g h td o w nw i t h o u tac a r r i a g er e t u r n . # T h i si st r u eo n l yo nd e v i c e s ,s u c ha st h eL i n u xc o n s o l e , # +t h a tc a n ' tg o" b a c k w a r d . " # T h er e a lp u r p o s eo fV Ti st og os t r a i g h tU P ,n o td o w n . # I tc a nb eu s e dt op r i n ts u p e r s c r i p t so nap r i n t e r . # T h ec o lu t i l i t yc a nb eu s e dt oe m u l a t et h ep r o p e rb e h a v i o ro fV T . e x i t0 C t l N

Erases a line of text recalled from history buffer [23] (on the command-line).
C t l O

Issues a newline (on the command-line).


C t l P

Recalls last command from history buffer (on the command-line).


C t l Q

Resume (X O N ). This resumes s t d i nin a terminal.


C t l R

Backwards search for text in history buffer (on the command-line).


C t l S

Suspend (X O F F ). This freezes s t d i nin a terminal. (Use Ctl-Q to restore input.)


C t l T

Reverses the position of the character the cursor is on with the previous character (on the command-line).
C t l U

Erase a line of input, from the cursor backward to beginning of line. In some settings, C t l Uerases the entire line of input, regardless of cursor position.
C t l V

When inputting text, C t l Vpermits inserting control characters. For example, the following two are equivalent:
e c h oe' \ x 0 a ' e c h o< C t l V > < C t l J > C t l Vis primarily useful from within a text editor. C t l W

When typing text on the console or in an xterm window, C t l Werases from the character under the cursor

backwards to the first instance of whitespace. In some settings, C t l Werases backwards to first nonalphanumeric character.
C t l X

In certain word processing programs, Cuts highlighted text and copies to clipboard.
C t l Y

Pastes back text previously erased (with C t l Uor C t l W ).


C t l Z

Pauses a foreground job. Substitute operation in certain word processing applications.


E O F(end-of-file) character in the MSDOS

filesystem.

Whitespace functions as a separator between commands and/or variables. Whitespace consists of either spaces, tabs, blank lines, or any combination thereof. [24] In some contexts, such as variable assignment, whitespace is not permitted, and results in a syntax error. Blank lines have no effect on the action of a script, and are therefore useful for visually separating functional sections. $IFS, the special variable separating fields of input to certain commands. It defaults to whitespace.
D e f i n i t i o n :A field

is a discrete chunk of data expressed as a string of consecutive characters. Separating each field from adjacent fields is either whitespace or some other designated character (often determined by the $IFS). In some contexts, a field may be called a record. To preserve whitespace within a string or in a variable, use quoting. UNIX filters can target and operate on whitespace using the POSIX character class [:space:].

Chapter 4. Introduction to Variables and Parameters


Variables are how programming and scripting languages represent data. A variable is nothing more than a label, a name assigned to a location or set of locations in computer memory holding an item of data. Variables appear in arithmetic operations and manipulation of quantities, and in string parsing.

4.1. Variable Substitution


The name of a variable is a placeholder for its value, the data it holds. Referencing (retrieving) its value is called variable substitution. $ Let us carefully distinguish between the name of a variable and its value. If v a r i a b l e 1is the name of a variable, then $ v a r i a b l e 1is a reference to its value, the data item it contains. [25]

b a s h $v a r i a b l e 1 = 2 3

b a s h $e c h ov a r i a b l e 1 v a r i a b l e 1 b a s h $e c h o$ v a r i a b l e 1 2 3

The only times a variable appears "naked" -- without the $ prefix -- is when declared or assigned, when unset , when exported, in an arithmetic expression within double parentheses (( ... )), or in the special case of a variable representing a signal (see Example 32-5). Assignment may be with an = (as in v a r 1 = 2 7 ), in a read statement, and at the head of a loop (f o rv a r 2i n123 ). Enclosing a referenced value in double quotes (" ... ") does not interfere with variable substitution. This is called partial quoting, sometimes referred to as "weak quoting." Using single quotes (' ... ') causes the variable name to be used literally, and no substitution will take place. This is full quoting, sometimes referred to as 'strong quoting.' See Chapter 5 for a detailed discussion. Note that $ v a r i a b l eis actually a simplified form of $ { v a r i a b l e } . In contexts where the $ v a r i a b l esyntax causes an error, the longer form may work (see Section 10.2, below). Example 4-1. Variable assignment and substitution
# ! / b i n / b a s h #e x 9 . s h #V a r i a b l e s :a s s i g n m e n ta n ds u b s t i t u t i o n a = 3 7 5 h e l l o = $ a # ^^ # #N os p a c ep e r m i t t e do ne i t h e rs i d eo f=s i g nw h e ni n i t i a l i z i n gv a r i a b l e s . #W h a th a p p e n si ft h e r ei sas p a c e ? # " V A R I A B L E= v a l u e " # ^ # %S c r i p tt r i e st or u n" V A R I A B L E "c o m m a n dw i t ho n ea r g u m e n t ," = v a l u e " . # " V A R I A B L E =v a l u e " # ^ # %S c r i p tt r i e st or u n" v a l u e "c o m m a n dw i t h # +t h ee n v i r o n m e n t a lv a r i a b l e" V A R I A B L E "s e tt o" " . # -

e c h oh e l l o #h e l l o #N o tav a r i a b l er e f e r e n c e ,j u s tt h es t r i n g" h e l l o ". . . e c h o$ h e l l o #3 7 5 # ^ T h i s* i s *av a r i a b l er e f e r e n c e . e c h o$ { h e l l o }#3 7 5 # L i k e w i s eav a r i a b l er e f e r e n c e ,a sa b o v e . #Q u o t i n g... e c h o" $ h e l l o " #3 7 5 e c h o" $ { h e l l o } " #3 7 5 e c h o h e l l o = " AB C D " e c h o$ h e l l o #ABCD e c h o" $ h e l l o "#AB C D #A sw es e e ,e c h o$ h e l l o a n d

e c h o" $ h e l l o "

g i v ed i f f e r e n tr e s u l t s .

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #Q u o t i n gav a r i a b l ep r e s e r v e sw h i t e s p a c e . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = e c h o e c h o' $ h e l l o ' #$ h e l l o # ^ ^ # V a r i a b l er e f e r e n c i n gd i s a b l e d( e s c a p e d )b ys i n g l eq u o t e s , # +w h i c hc a u s e st h e" $ "t ob ei n t e r p r e t e dl i t e r a l l y . #N o t i c et h ee f f e c to fd i f f e r e n tt y p e so fq u o t i n g .

h e l l o = #S e t t i n gi tt oan u l lv a l u e . e c h o" \ $ h e l l o( n u l lv a l u e )=$ h e l l o " #$ h e l l o( n u l lv a l u e )= # N o t et h a ts e t t i n gav a r i a b l et oan u l lv a l u ei sn o tt h es a m ea s # +u n s e t t i n gi t ,a l t h o u g ht h ee n dr e s u l ti st h es a m e( s e eb e l o w ) . ## I ti sp e r m i s s i b l et os e tm u l t i p l ev a r i a b l e so nt h es a m el i n e , # +i fs e p a r a t e db yw h i t es p a c e . # C a u t i o n ,t h i sm a yr e d u c el e g i b i l i t y ,a n dm a yn o tb ep o r t a b l e . v a r 1 = 2 1 v a r 2 = 2 2 v a r 3 = $ V 3 e c h o e c h o" v a r 1 = $ v a r 1 v a r 2 = $ v a r 2

v a r 3 = $ v a r 3 "

#M a yc a u s ep r o b l e m sw i t hl e g a c yv e r s i o n so f" s h "... #e c h o ;e c h o n u m b e r s = " o n et w ot h r e e " # ^ ^ o t h e r _ n u m b e r s = " 123 " # ^^ # I ft h e r ei sw h i t e s p a c ee m b e d d e dw i t h i nav a r i a b l e , # +t h e nq u o t e sa r en e c e s s a r y . # o t h e r _ n u m b e r s = 123 #G i v e sa ne r r o rm e s s a g e . e c h o" n u m b e r s=$ n u m b e r s " e c h o" o t h e r _ n u m b e r s=$ o t h e r _ n u m b e r s " #o t h e r _ n u m b e r s=123 # E s c a p i n gt h ew h i t e s p a c ea l s ow o r k s . m i x e d _ b a g = 2 \\W h a t e v e r # ^ ^S p a c ea f t e re s c a p e( \ ) . e c h o" $ m i x e d _ b a g " e c h o ;e c h o e c h o" u n i n i t i a l i z e d _ v a r i a b l e=$ u n i n i t i a l i z e d _ v a r i a b l e " #U n i n i t i a l i z e dv a r i a b l eh a sn u l lv a l u e( n ov a l u ea ta l l ! ) . u n i n i t i a l i z e d _ v a r i a b l e = # D e c l a r i n g ,b u tn o ti n i t i a l i z i n gi t# +s a m ea ss e t t i n gi tt oan u l lv a l u e ,a sa b o v e . e c h o" u n i n i t i a l i z e d _ v a r i a b l e=$ u n i n i t i a l i z e d _ v a r i a b l e " #I ts t i l lh a san u l lv a l u e . u n i n i t i a l i z e d _ v a r i a b l e = 2 3 #S e ti t . u n s e tu n i n i t i a l i z e d _ v a r i a b l e #U n s e ti t . e c h o" u n i n i t i a l i z e d _ v a r i a b l e=$ u n i n i t i a l i z e d _ v a r i a b l e " #u n i n i t i a l i z e d _ v a r i a b l e= #I ts t i l lh a san u l lv a l u e . e c h o e x i t0 #2-W h a t e v e r

An uninitialized variable has a "null" value -- no assigned value at all (not zero!).
i f[z" $ u n a s s i g n e d "] t h e n e c h o" \ $ u n a s s i g n e di sN U L L . " f i #$ u n a s s i g n e di sN U L L .

Using a variable before assigning a value to it may cause problems. It is nevertheless possible to perform arithmetic operations on an uninitialized variable.
e c h o" $ u n i n i t i a l i z e d " l e t" u n i n i t i a l i z e d+ =5 " e c h o" $ u n i n i t i a l i z e d " #( b l a n kl i n e ) #A d d5t oi t . #5

# C o n c l u s i o n : # A nu n i n i t i a l i z e dv a r i a b l eh a sn ov a l u e , # +h o w e v e ri te v a l u a t e sa s0i na na r i t h m e t i co p e r a t i o n .

See also Example 15-23.

4.2. Variable Assignment


= the assignment operator (no space before and after) Do not confuse this with = and -eq, which test, rather than assign! Note that = can be either an assignment or a test operator, depending on context. Example 4-2. Plain Variable Assignment
# ! / b i n / b a s h #N a k e dv a r i a b l e s e c h o #W h e ni sav a r i a b l e" n a k e d " ,i . e . ,l a c k i n gt h e' $ 'i nf r o n t ? #W h e ni ti sb e i n ga s s i g n e d ,r a t h e rt h a nr e f e r e n c e d . #A s s i g n m e n t a = 8 7 9 e c h o" T h ev a l u eo f\ " a \ "i s$ a . " #A s s i g n m e n tu s i n g' l e t ' l e ta = 1 6 + 5 e c h o" T h ev a l u eo f\ " a \ "i sn o w$ a . " e c h o #I na' f o r 'l o o p( r e a l l y ,at y p eo fd i s g u i s e da s s i g n m e n t ) : e c h on" V a l u e so f\ " a \ "i nt h el o o pa r e :" f o rai n7891 1 d o e c h on" $ a" d o n e e c h o e c h o #I na' r e a d 's t a t e m e n t( a l s oat y p eo fa s s i g n m e n t ) : e c h on" E n t e r\ " a \ "" r e a da e c h o" T h ev a l u eo f\ " a \ "i sn o w$ a . "

e c h o e x i t0

Example 4-3. Variable Assignment, plain and fancy


# ! / b i n / b a s h a = 2 3 e c h o$ a b = $ a e c h o$ b #S i m p l ec a s e

#N o w ,g e t t i n gal i t t l eb i tf a n c i e r( c o m m a n ds u b s t i t u t i o n ) . a = ` e c h oH e l l o ! ` #A s s i g n sr e s u l to f' e c h o 'c o m m a n dt o' a '. . . e c h o$ a # N o t et h a ti n c l u d i n ga ne x c l a m a t i o nm a r k( ! )w i t h i na # +c o m m a n ds u b s t i t u t i o nc o n s t r u c tw i l ln o tw o r kf r o mt h ec o m m a n d l i n e , # +s i n c et h i st r i g g e r st h eB a s h" h i s t o r ym e c h a n i s m . " # I n s i d eas c r i p t ,h o w e v e r ,t h eh i s t o r yf u n c t i o n sa r ed i s a b l e d . a = ` l sl ` e c h o$ a e c h o e c h o" $ a " #A s s i g n sr e s u l to f' l sl 'c o m m a n dt o' a ' #U n q u o t e d ,h o w e v e r ,i tr e m o v e st a b sa n dn e w l i n e s . #T h eq u o t e dv a r i a b l ep r e s e r v e sw h i t e s p a c e . #( S e et h ec h a p t e ro n" Q u o t i n g . " )

e x i t0

Variable assignment using the $(...) mechanism (a newer method than backquotes). This is likewise a form of command substitution.
#F r o m/ e t c / r c . d / r c . l o c a l R = $ ( c a t/ e t c / r e d h a t r e l e a s e ) a r c h = $ ( u n a m em )

4.3. Bash Variables Are Untyped


Unlike many other programming languages, Bash does not segregate its variables by "type." Essentially, Bash variables are character strings, but, depending on context, Bash permits arithmetic operations and comparisons on variables. The determining factor is whether the value of a variable contains only digits. Example 4-4. Integer or string?
# ! / b i n / b a s h #i n t o r s t r i n g . s h a = 2 3 3 4 l e t" a+ =1 " e c h o" a=$ a" e c h o #I n t e g e r . #a=2 3 3 5 #I n t e g e r ,s t i l l .

b = $ { a / 2 3 / B B } e c h o" b=$ b " d e c l a r eib e c h o" b=$ b " l e t" b+ =1 " e c h o" b=$ b "

#S u b s t i t u t e" B B "f o r" 2 3 " . #T h i st r a n s f o r m s$ bi n t oas t r i n g . #b=B B 3 5 #D e c l a r i n gi ta ni n t e g e rd o e s n ' th e l p . #b=B B 3 5 #B B 3 5+1 #b=1

e c h o c = B B 3 4 e c h o" c=$ c " d = $ { c / B B / 2 3 } e c h o" d=$ d " l e t" d+ =1 " e c h o" d=$ d " e c h o

#B a s hs e t st h e" i n t e g e rv a l u e "o fas t r i n gt o0 .

#c=B B 3 4 #S u b s t i t u t e" 2 3 "f o r" B B " . #T h i sm a k e s$ da ni n t e g e r . #d=2 3 3 4 #2 3 3 4+1 #d=2 3 3 5

#W h a ta b o u tn u l lv a r i a b l e s ? e = ' ' #. . .O re = " ". . .O re = e c h o" e=$ e " #e= l e t" e+ =1 " #A r i t h m e t i co p e r a t i o n sa l l o w e do nan u l lv a r i a b l e ? e c h o" e=$ e " #e=1 e c h o #N u l lv a r i a b l et r a n s f o r m e di n t oa ni n t e g e r . #W h a ta b o u tu n d e c l a r e dv a r i a b l e s ? e c h o" f=$ f " #f= l e t" f+ =1 " #A r i t h m e t i co p e r a t i o n sa l l o w e d ? e c h o" f=$ f " #f=1 e c h o #U n d e c l a r e dv a r i a b l et r a n s f o r m e di n t oa ni n t e g e r . # #H o w e v e r. . . l e t" f/ =$ u n d e c l _ v a r " #D i v i d eb yz e r o ? # l e t :f/ =:s y n t a xe r r o r :o p e r a n de x p e c t e d( e r r o rt o k e ni s"" ) #S y n t a xe r r o r !V a r i a b l e$ u n d e c l _ v a ri sn o ts e tt oz e r oh e r e ! # #B u ts t i l l. . . l e t" f/ =0 " # l e t :f/ =0 :d i v i s i o nb y0( e r r o rt o k e ni s" 0 " ) #E x p e c t e db e h a v i o r .

# B a s h( u s u a l l y )s e t st h e" i n t e g e rv a l u e "o fn u l lt oz e r o # +w h e np e r f o r m i n ga na r i t h m e t i co p e r a t i o n . # B u t ,d o n ' tt r yt h i sa th o m e ,f o l k s ! # I t ' su n d o c u m e n t e da n dp r o b a b l yn o n p o r t a b l eb e h a v i o r .

#C o n c l u s i o n :V a r i a b l e si nB a s ha r eu n t y p e d , # +w i t ha l la t t e n d a n tc o n s e q u e n c e s . e x i t$ ?

Untyped variables are both a blessing and a curse. They permit more flexibility in scripting and make it easier to grind out lines of code (and give you enough rope to hang yourself!). However, they likewise permit subtle errors to creep in and encourage sloppy programming habits. To lighten the burden of keeping track of variable types in a script, Bash does permit declaring variables.

4.4. Special Variable Types


L o c a lv a r i a b l e s

Variables visible only within a code block or function (see also local variables in functions)
E n v i r o n m e n t a lv a r i a b l e s

Variables that affect the behavior of the shell and user interface In a more general context, each process has an "environment", that is, a group of variables that the

process may reference. In this sense, the shell behaves like any other process. Every time a shell starts, it creates shell variables that correspond to its own environmental variables. Updating or adding new environmental variables causes the shell to update its environment, and all the shell's child processes (the commands it executes) inherit this environment. The space allotted to the environment is limited. Creating too many environmental variables or ones that use up excessive space may cause problems.
b a s h $e v a l" ` s e q1 0 0 0 0|s e de' s / . * / e x p o r tv a r & = Z Z Z Z Z Z Z Z Z Z Z Z Z Z / ' ` " b a s h $d u b a s h :/ u s r / b i n / d u :A r g u m e n tl i s tt o ol o n g

Note: this "error" has been fixed, as of kernel version 2.6.23. (Thank you, Stphane Chazelas for the clarification, and for providing the above example.) If a script sets environmental variables, they need to be "exported," that is, reported to the environment local to the script. This is the function of the export command. A script can export variables only to child processes, that is, only to commands or processes which that particular script initiates. A script invoked from the command-line c a n n o texport variables back to the command-line environment. Child processes cannot export variables back to the parent processes that spawned them.
D e f i n i t i o n :A child P o s i t i o n a lp a r a m e t e r s

process is a subprocess launched by another process, its parent.

Arguments passed to the script from the command line [26] : $ 0 ,$ 1 ,$ 2 ,$ 3. . .


$ 0is the name of the script itself, $ 1is the first argument, $ 2the second, $ 3the third,

and so forth. [27] After $ 9 , the

arguments must be enclosed in brackets, for example, $ { 1 0 } ,$ { 1 1 } ,$ { 1 2 } . The special variables $* and $@ denote all the positional parameters. Example 4-5. Positional Parameters
# ! / b i n / b a s h #C a l lt h i ss c r i p tw i t ha tl e a s t1 0p a r a m e t e r s ,f o re x a m p l e #. / s c r i p t n a m e1234567891 0 M I N P A R A M S = 1 0 e c h o e c h o" T h en a m eo ft h i ss c r i p ti s\ " $ 0 \ " . " #A d d s. /f o rc u r r e n td i r e c t o r y e c h o" T h en a m eo ft h i ss c r i p ti s\ " ` b a s e n a m e$ 0 ` \ " . " #S t r i p so u tp a t hn a m ei n f o( s e e' b a s e n a m e ' ) e c h o i f[n" $ 1 "] #T e s t e dv a r i a b l ei sq u o t e d . t h e n e c h o" P a r a m e t e r# 1i s$ 1 " #N e e dq u o t e st oe s c a p e# f i i f[n" $ 2 "] t h e n

e c h o" P a r a m e t e r# 2i s$ 2 " f i i f[n" $ 3 "] t h e n e c h o" P a r a m e t e r# 3i s$ 3 " f i #. . .

i f[n" $ { 1 0 } "] #P a r a m e t e r s>$ 9m u s tb ee n c l o s e di n{ b r a c k e t s } . t h e n e c h o" P a r a m e t e r# 1 0i s$ { 1 0 } " f i e c h o" " e c h o" A l lt h ec o m m a n d l i n ep a r a m e t e r sa r e :" $ * " " i f[$ #l t" $ M I N P A R A M S "] t h e n e c h o e c h o" T h i ss c r i p tn e e d sa tl e a s t$ M I N P A R A M Sc o m m a n d l i n ea r g u m e n t s ! " f i e c h o e x i t0

Bracket notation for positional parameters leads to a fairly simple way of referencing the last argument passed to a script on the command-line. This also requires indirect referencing.
a r g s = $ # #N u m b e ro fa r g sp a s s e d . l a s t a r g = $ { ! a r g s } #N o t e :T h i si sa n* i n d i r e c tr e f e r e n c e *t o$ a r g s. . .

#O r : l a s t a r g = $ { ! # } ( T h a n k s ,C h r i sM o n s o n . ) #T h i si sa n* i n d i r e c tr e f e r e n c e *t ot h e$ #v a r i a b l e . #N o t et h a tl a s t a r g = $ { ! $ # }d o e s n ' tw o r k .

Some scripts can perform different operations, depending on which name they are invoked with. For this to work, the script needs to check $ 0 , the name it was invoked by. [28] There must also exist symbolic links to all the alternate names of the script. See Example 16-2. If a script expects a command-line parameter but is invoked without one, this may cause a null variable assignment , generally an undesirable result. One way to prevent this is to append an extra character to both sides of the assignment statement using the expected positional parameter.
v a r i a b l e 1 _ = $ 1 _ #R a t h e rt h a nv a r i a b l e 1 = $ 1 #T h i sw i l lp r e v e n ta ne r r o r ,e v e ni fp o s i t i o n a lp a r a m e t e ri sa b s e n t . c r i t i c a l _ a r g u m e n t 0 1 = $ v a r i a b l e 1 _ #T h ee x t r ac h a r a c t e rc a nb es t r i p p e do f fl a t e r ,l i k es o . v a r i a b l e 1 = $ { v a r i a b l e 1 _ / _ / } #S i d ee f f e c t so n l yi f$ v a r i a b l e 1 _b e g i n sw i t ha nu n d e r s c o r e . #T h i su s e so n eo ft h ep a r a m e t e rs u b s t i t u t i o nt e m p l a t e sd i s c u s s e dl a t e r . #( L e a v i n go u tt h er e p l a c e m e n tp a t t e r nr e s u l t si nad e l e t i o n . ) # Am o r es t r a i g h t f o r w a r dw a yo fd e a l i n gw i t ht h i si s # +t os i m p l yt e s tw h e t h e re x p e c t e dp o s i t i o n a lp a r a m e t e r sh a v eb e e np a s s e d . i f[z$ 1] t h e n e x i t$ E _ M I S S I N G _ P O S _ P A R A M f i

# H o w e v e r ,a sF a b i a nK r e u t zp o i n t so u t , # +t h ea b o v em e t h o dm a yh a v eu n e x p e c t e ds i d e e f f e c t s . # Ab e t t e rm e t h o di sp a r a m e t e rs u b s t i t u t i o n : # $ { 1 : $ D e f a u l t V a l } # S e et h e" P a r a m e t e rS u b s t i t i o n "s e c t i o n # +i nt h e" V a r i a b l e sR e v i s i t e d "c h a p t e r .

--Example 4-6. wh, whois domain name lookup


# ! / b i n / b a s h #e x 1 8 . s h #D o e sa' w h o i sd o m a i n n a m e 'l o o k u po na n yo f3a l t e r n a t es e r v e r s : # r i p e . n e t ,c w . n e t ,r a d b . n e t #P l a c et h i ss c r i p t-r e n a m e d' w h '-i n/ u s r / l o c a l / b i n #R e q u i r e ss y m b o l i cl i n k s : #l ns/ u s r / l o c a l / b i n / w h/ u s r / l o c a l / b i n / w h r i p e #l ns/ u s r / l o c a l / b i n / w h/ u s r / l o c a l / b i n / w h a p n i c #l ns/ u s r / l o c a l / b i n / w h/ u s r / l o c a l / b i n / w h t u c o w s E _ N O A R G S = 7 5

i f[z" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `[ d o m a i n n a m e ] " e x i t$ E _ N O A R G S f i #C h e c ks c r i p tn a m ea n dc a l lp r o p e rs e r v e r . c a s e` b a s e n a m e$ 0 `i n #O r : c a s e$ { 0 # # * / }i n " w h " )w h o i s$ 1 @ w h o i s . t u c o w s . c o m ; ; " w h r i p e " )w h o i s$ 1 @ w h o i s . r i p e . n e t ; ; " w h a p n i c ")w h o i s$ 1 @ w h o i s . a p n i c . n e t ; ; " w h c w " )w h o i s$ 1 @ w h o i s . c w . n e t ; ; * )e c h o" U s a g e :` b a s e n a m e$ 0 `[ d o m a i n n a m e ] " ; ; e s a c e x i t$ ?

--The shift command reassigns the positional parameters, in effect shifting them to the left one notch.
$ 1<--- $ 2 ,$ 2<--- $ 3 ,$ 3<--- $ 4 , etc.

The old $ 1disappears, but $ 0(the script name) does not change. If you use a large number of positional parameters to a script, shift lets you access those past 1 0 , although {bracket} notation also permits this. Example 4-7. Using shift
# ! / b i n / b a s h #s h f t . s h :U s i n g' s h i f t 't os t e pt h r o u g ha l lt h ep o s i t i o n a lp a r a m e t e r s . # N a m et h i ss c r i p ts o m e t h i n gl i k es h f t . s h , # +a n di n v o k ei tw i t hs o m ep a r a m e t e r s . # +F o re x a m p l e : # s hs h f t . s habcd e f8 3b a r n d o o r u n t i l[z" $ 1 "] #U n t i la l lp a r a m e t e r su s e du p... d o

e c h on" $ 1" s h i f t d o n e e c h o #E x t r al i n e f e e d .

#B u t ,w h a th a p p e n st ot h e" u s e d u p "p a r a m e t e r s ? e c h o" $ 2 " # N o t h i n ge c h o e s ! # W h e n$ 2s h i f t si n t o$ 1( a n dt h e r ei sn o$ 3t os h i f ti n t o$ 2 ) # +t h e n$ 2r e m a i n se m p t y . # S o ,i ti sn o tap a r a m e t e r* c o p y * ,b u ta* m o v e * . e x i t # S e ea l s ot h ee c h o p a r a m s . s hs c r i p tf o ra" s h i f t l e s s " # +a l t e r n a t i v em e t h o do fs t e p p i n gt h r o u g ht h ep o s i t i o n a lp a r a m s .

The shift command can take a numerical parameter indicating how many positions to shift.
# ! / b i n / b a s h #s h i f t p a s t . s h s h i f t3 #S h i f t3p o s i t i o n s . # n = 3 ;s h i f t$ n # H a st h es a m ee f f e c t . e c h o" $ 1 " e x i t0 #= = = = = = = = = = = = = = = = = = = = = = = =#

$s hs h i f t p a s t . s h12345 4 # H o w e v e r ,a sE l e n iF r a g k i a d a k i ,p o i n t so u t , # +a t t e m p t i n ga' s h i f t 'p a s tt h en u m b e ro f # +p o s i t i o n a lp a r a m e t e r s( $ # )r e t u r n sa ne x i ts t a t u so f1 , # +a n dt h ep o s i t i o n a lp a r a m e t e r st h e m s e l v e sd on o tc h a n g e . # T h i sm e a n sp o s s i b l yg e t t i n gs t u c ki na ne n d l e s sl o o p .... # F o re x a m p l e : # u n t i l[z" $ 1 "] # d o # e c h on" $ 1" # s h i f t2 0 # I fl e s st h a n2 0p o sp a r a m s , # d o n e # +t h e nl o o pn e v e re n d s ! # #W h e ni nd o u b t ,a d das a n i t yc h e c k .... # s h i f t2 0| |b r e a k # ^ ^ ^ ^ ^ ^ ^ ^

The shift command works in a similar fashion on parameters passed to a function. See Example 36-16.

Chapter 5. Quoting
Quoting means just that, bracketing a string in quotes. This has the effect of protecting special characters in the string from reinterpretation or expansion by the shell or shell script. (A character is "special" if it has an interpretation other than its literal meaning. For example, the asterisk * represents a wild card character in globbing and Regular Expressions).
b a s h $l sl[ V v ] *

r w r w r r w r w r r w r w r -

1b o z o b o z o 1b o z o b o z o 1b o z o b o z o

3 2 4A p r 21 5 : 0 5V I E W D A T A . B A T 5 0 7M a y 41 4 : 2 5v a r t r a c e . s h 5 3 9A p r1 41 7 : 1 1v i e w d a t a . s h

b a s h $l sl' [ V v ] * ' l s :[ V v ] * :N os u c hf i l eo rd i r e c t o r y

In everyday speech or writing, when we "quote" a phrase, we set it apart and give it special meaning. In a Bash script, when we quote a string, we set it apart and protect its literal meaning. Certain programs and utilities reinterpret or expand special characters in a quoted string. An important use of quoting is protecting a command-line parameter from the shell, but still letting the calling program expand it.
b a s h $g r e p' [ F f ] i r s t '* . t x t f i l e 1 . t x t : T h i si st h ef i r s tl i n eo ff i l e 1 . t x t . f i l e 2 . t x t : T h i si st h eF i r s tl i n eo ff i l e 2 . t x t .

Note that the unquoted g r e p[ F f ] i r s t* . t x tworks under the Bash shell. [29] Quoting can also suppress echo's "appetite" for newlines.
b a s h $e c h o$ ( l sl ) t o t a l8r w r w r -1b ob o1 3A u g2 11 2 : 5 7t . s hr w r w r -1b ob o7 8A u g2 11 2 : 5 7u . s h

b a s h $e c h o" $ ( l sl ) " t o t a l8 r w r w r - 1b ob o 1 3A u g2 11 2 : 5 7t . s h r w r w r - 1b ob o 7 8A u g2 11 2 : 5 7u . s h

5.1. Quoting Variables


When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape). [30] Keeping $ as a special character within double quotes permits referencing a quoted variable (" $ v a r i a b l e " ), that is, replacing the variable with its value (see Example 4-1, above). Use double quotes to prevent word splitting. [31] An argument enclosed in double quotes presents itself as a single word, even if it contains whitespace separators.
L i s t = " o n et w ot h r e e " f o rai n$ L i s t d o e c h o" $ a " d o n e #o n e #t w o #t h r e e e c h o" " f o rai n" $ L i s t " d o# ^ ^ e c h o" $ a " d o n e #o n et w ot h r e e #P r e s e r v e sw h i t e s p a c ei nas i n g l ev a r i a b l e . #S p l i t st h ev a r i a b l ei np a r t sa tw h i t e s p a c e .

A more elaborate example:

v a r i a b l e 1 = " av a r i a b l ec o n t a i n i n gf i v ew o r d s " C O M M A N DT h i si s$ v a r i a b l e 1 #E x e c u t e sC O M M A N Dw i t h7a r g u m e n t s : #" T h i s "" i s "" a "" v a r i a b l e "" c o n t a i n i n g "" f i v e "" w o r d s " C O M M A N D" T h i si s$ v a r i a b l e 1 " #E x e c u t e sC O M M A N Dw i t h1a r g u m e n t : #" T h i si sav a r i a b l ec o n t a i n i n gf i v ew o r d s "

v a r i a b l e 2 = " "

#E m p t y .

C O M M A N D$ v a r i a b l e 2$ v a r i a b l e 2$ v a r i a b l e 2 #E x e c u t e sC O M M A N Dw i t hn oa r g u m e n t s . C O M M A N D" $ v a r i a b l e 2 "" $ v a r i a b l e 2 "" $ v a r i a b l e 2 " #E x e c u t e sC O M M A N Dw i t h3e m p t ya r g u m e n t s . C O M M A N D" $ v a r i a b l e 2$ v a r i a b l e 2$ v a r i a b l e 2 " #E x e c u t e sC O M M A N Dw i t h1a r g u m e n t( 2s p a c e s ) . #T h a n k s ,S t p h a n eC h a z e l a s .

Enclosing the arguments to an echo statement in double quotes is necessary only when word splitting or preservation of whitespace is an issue. Example 5-1. Echoing Weird Variables
# ! / b i n / b a s h #w e i r d v a r s . s h :E c h o i n gw e i r dv a r i a b l e s . e c h o v a r = " ' ( ] \ \ { } \ $ \ " " e c h o$ v a r #' ( ] \ { } $ " e c h o" $ v a r " #' ( ] \ { } $ " e c h o I F S = ' \ ' e c h o$ v a r e c h o" $ v a r "

D o e s n ' tm a k ead i f f e r e n c e .

#' ( ]{ } $ " #' ( ] \ { } $ "

\c o n v e r t e dt os p a c e .W h y ?

#E x a m p l e sa b o v es u p p l i e db yS t e p h a n eC h a z e l a s . e c h o v a r 2 = " \ \ \ \ \ " " e c h o$ v a r 2 # " e c h o" $ v a r 2 " #\ \ " e c h o #B u t. . .v a r 2 = " \ \ \ \ " "i si l l e g a l .W h y ? v a r 3 = ' \ \ \ \ ' e c h o" $ v a r 3 " #\ \ \ \ #S t r o n gq u o t i n gw o r k s ,t h o u g h .

#* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *# #A st h ef i r s te x a m p l ea b o v es h o w s ,n e s t i n gq u o t e si sp e r m i t t e d . e c h o" $ ( e c h o' " ' ) " # ^ ^ #"

#A tt i m e st h i sc o m e si nu s e f u l . v a r 1 = " T w ob i t s " e c h o" \ $ v a r 1=" $ v a r 1 " " # ^ ^

#$ v a r 1=T w ob i t s

#O r ,a sC h r i sH i e s t a n dp o i n t so u t. . .

i f[ [" $ ( d u" $ M y _ F i l e 1 " ) "g t" $ ( d u" $ M y _ F i l e 2 " ) "] ] ;t h e n. . . #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *#

Single quotes (' ') operate similarly to double quotes, but do not permit referencing variables, since the special meaning of $ is turned off. Within single quotes, every special character except ' gets interpreted literally. Consider single quotes ("full quoting") to be a stricter method of quoting than double quotes ("partial quoting"). Since even the escape character (\) gets a literal interpretation within single quotes, trying to enclose a single quote within single quotes will not yield the expected result.
e c h o" W h yc a n ' tIw r i t e' sb e t w e e ns i n g l eq u o t e s " e c h o #T h er o u n d a b o u tm e t h o d . e c h o' W h yc a n ' \ ' ' tIw r i t e' " ' " ' sb e t w e e ns i n g l eq u o t e s ' # | | | | | | #T h r e es i n g l e q u o t e ds t r i n g s ,w i t he s c a p e da n dq u o t e ds i n g l eq u o t e sb e t w e e n . #T h i se x a m p l ec o u r t e s yo fS t p h a n eC h a z e l a s .

5.2. Escaping
Escaping is a method of quoting single characters. The escape (\) preceding a character tells the shell to interpret that character literally. With certain commands and utilities, such as echo and sed, escaping a character may have the opposite effect - it can toggle on a special meaning for that character. Special meanings of certain escaped characters used with echo and sed \n means newline \r means return \t means tab \v means vertical tab \b means backspace \a means alert (beep or flash) \0xx

translates to the octal ASCII equivalent of 0 n n , where n nis a string of digits The $ '. . . 'quoted string-expansion construct is a mechanism that uses escaped octal or hex values to assign ASCII characters to variables, e.g., quote=$'\042'. Example 5-2. Escaped Characters
# ! / b i n / b a s h #e s c a p e d . s h :e s c a p e dc h a r a c t e r s # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #F i r s t ,l e t ' ss h o ws o m eb a s i ce s c a p e d c h a r a c t e ru s a g e .# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #E s c a p i n gan e w l i n e . #e c h o" " e c h o" T h i sw i l lp r i n t a st w ol i n e s . " #T h i sw i l lp r i n t #a st w ol i n e s . e c h o" T h i sw i l lp r i n t\ a so n el i n e . " #T h i sw i l lp r i n ta so n el i n e . e c h o ;e c h o e c h o" = = = = = = = = = = = = = "

e c h o" \ v \ v \ v \ v " #P r i n t s\ v \ v \ v \ vl i t e r a l l y . #U s et h eeo p t i o nw i t h' e c h o 't op r i n te s c a p e dc h a r a c t e r s . e c h o" = = = = = = = = = = = = = " e c h o" V E R T I C A LT A B S " e c h oe" \ v \ v \ v \ v " #P r i n t s4v e r t i c a lt a b s . e c h o" = = = = = = = = = = = = = = " e c h o" Q U O T A T I O NM A R K " e c h oe" \ 0 4 2 " #P r i n t s"( q u o t e ,o c t a lA S C I Ic h a r a c t e r4 2 ) . e c h o" = = = = = = = = = = = = = = "

#T h e$ ' \ X 'c o n s t r u c tm a k e st h eeo p t i o nu n n e c e s s a r y . e c h o ;e c h o" N E W L I N Ea n d( m a y b e )B E E P " e c h o$ ' \ n ' #N e w l i n e . e c h o$ ' \ a ' #A l e r t( b e e p ) . #M a yo n l yf l a s h ,n o tb e e p ,d e p e n d i n go nt e r m i n a l . #W eh a v es e e n$ ' \ n n n "s t r i n ge x p a n s i o n ,a n dn o w... #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #V e r s i o n2o fB a s hi n t r o d u c e dt h e$ ' \ n n n 's t r i n ge x p a n s i o nc o n s t r u c t . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# e c h o" I n t r o d u c i n gt h e\ $ \ '. . .\ 's t r i n g e x p a n s i o nc o n s t r u c t..." e c h o" ...f e a t u r i n gm o r eq u o t a t i o nm a r k s . " e c h o$ ' \ t\ 0 4 2\ t ' #Q u o t e( " )f r a m e db yt a b s . #N o t et h a t ' \ n n n 'i sa no c t a lv a l u e . #I ta l s ow o r k sw i t hh e x a d e c i m a lv a l u e s ,i na n$ ' \ x h h h 'c o n s t r u c t . e c h o$ ' \ t\ x 2 2\ t ' #Q u o t e( " )f r a m e db yt a b s .

#T h a n ky o u ,G r e gK e r a u n e n ,f o rp o i n t i n gt h i so u t . #E a r l i e rB a s hv e r s i o n sa l l o w e d' \ x 0 2 2 ' . e c h o

#A s s i g n i n gA S C I Ic h a r a c t e r st oav a r i a b l e . #q u o t e = $ ' \ 0 4 2 ' #"a s s i g n e dt oav a r i a b l e . e c h o" $ q u o t eQ u o t e ds t r i n g$ q u o t ea n dt h i sl i e so u t s i d et h eq u o t e s . " e c h o #C o n c a t e n a t i n gA S C I Ic h a r si nav a r i a b l e . t r i p l e _ u n d e r l i n e = $ ' \ 1 3 7 \ 1 3 7 \ 1 3 7 ' #1 3 7i so c t a lA S C I Ic o d ef o r' _ ' . e c h o" $ t r i p l e _ u n d e r l i n eU N D E R L I N E$ t r i p l e _ u n d e r l i n e " e c h o A B C = $ ' \ 1 0 1 \ 1 0 2 \ 1 0 3 \ 0 1 0 ' e c h o$ A B C e c h o e s c a p e = $ ' \ 0 3 3 ' #0 3 3i so c t a lf o re s c a p e . e c h o" \ " e s c a p e \ "e c h o e sa s$ e s c a p e " # n ov i s i b l eo u t p u t . e c h o e x i t0 #1 0 1 ,1 0 2 ,1 0 3a r eo c t a lA ,B ,C .

A more elaborate example: Example 5-3. Detecting key-presses


# ! / b i n / b a s h #A u t h o r :S i g u r dS o l a a s ,2 0A p r2 0 1 1 #U s e di nA B SG u i d ew i t hp e r m i s s i o n . #R e q u i r e sv e r s i o n4 . 2 +o fB a s h . k e y = " n ov a l u ey e t " w h i l et r u e ;d o c l e a r e c h o" B a s hE x t r aK e y sD e m o .K e y st ot r y : " e c h o e c h o" *I n s e r t ,D e l e t e ,H o m e ,E n d ,P a g e _ U pa n dP a g e _ D o w n " e c h o" *T h ef o u ra r r o wk e y s " e c h o" *T a b ,e n t e r ,e s c a p e ,a n ds p a c ek e y " e c h o" *T h el e t t e ra n dn u m b e rk e y s ,e t c . " e c h o e c h o" d=s h o wd a t e / t i m e " e c h o" q=q u i t " e c h o" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " e c h o #C o n v e r tt h es e p a r a t eh o m e k e yt oh o m e k e y _ n u m _ 7 : i f[" $ k e y "=$ ' \ x 1 b \ x 4 f \ x 4 8 '] ;t h e n k e y = $ ' \ x 1 b \ x 5 b \ x 3 1 \ x 7 e ' # Q u o t e ds t r i n g e x p a n s i o nc o n s t r u c t . f i #C o n v e r tt h es e p a r a t ee n d k e yt oe n d k e y _ n u m _ 1 . i f[" $ k e y "=$ ' \ x 1 b \ x 4 f \ x 4 6 '] ;t h e n k e y = $ ' \ x 1 b \ x 5 b \ x 3 4 \ x 7 e ' f i c a s e" $ k e y "i n

$ ' \ x 1 b \ x 5 b \ x 3 2 \ x 7 e ' ) #I n s e r t e c h oI n s e r tK e y ; ; $ ' \ x 1 b \ x 5 b \ x 3 3 \ x 7 e ' ) #D e l e t e e c h oD e l e t eK e y ; ; $ ' \ x 1 b \ x 5 b \ x 3 1 \ x 7 e ' ) #H o m e _ k e y _ n u m _ 7 e c h oH o m eK e y ; ; $ ' \ x 1 b \ x 5 b \ x 3 4 \ x 7 e ' ) #E n d _ k e y _ n u m _ 1 e c h oE n dK e y ; ; $ ' \ x 1 b \ x 5 b \ x 3 5 \ x 7 e ' ) #P a g e _ U p e c h oP a g e _ U p ; ; $ ' \ x 1 b \ x 5 b \ x 3 6 \ x 7 e ' ) #P a g e _ D o w n e c h oP a g e _ D o w n ; ; $ ' \ x 1 b \ x 5 b \ x 4 1 ' ) #U p _ a r r o w e c h oU pa r r o w ; ; $ ' \ x 1 b \ x 5 b \ x 4 2 ' ) #D o w n _ a r r o w e c h oD o w na r r o w ; ; $ ' \ x 1 b \ x 5 b \ x 4 3 ' ) #R i g h t _ a r r o w e c h oR i g h ta r r o w ; ; $ ' \ x 1 b \ x 5 b \ x 4 4 ' ) #L e f t _ a r r o w e c h oL e f ta r r o w ; ; $ ' \ x 0 9 ' ) #T a b e c h oT a bK e y ; ; $ ' \ x 0 a ' ) #E n t e r e c h oE n t e rK e y ; ; $ ' \ x 1 b ' ) #E s c a p e e c h oE s c a p eK e y ; ; $ ' \ x 2 0 ' ) #S p a c e e c h oS p a c eK e y ; ; d ) d a t e ; ; q ) e c h oT i m et oq u i t . . . e c h o e x i t0 ; ; * ) e c h oY o up r e s s e d :\ ' " $ k e y " \ ' ; ; e s a c e c h o e c h o" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " u n s e tK 1K 2K 3 r e a dsN 1p" P r e s sak e y :" K 1 = " $ R E P L Y " r e a dsN 2t0 . 0 0 1 K 2 = " $ R E P L Y " r e a dsN 1t0 . 0 0 1 K 3 = " $ R E P L Y " k e y = " $ K 1 $ K 2 $ K 3 " d o n e

e x i t$ ?

See also Example 37-1. \" gives the quote its literal meaning
e c h o" H e l l o " e c h o" \ " H e l l o \ ". . .h es a i d . " #H e l l o #" H e l l o ". . .h es a i d .

\$ gives the dollar sign its literal meaning (variable name following \$ will not be referenced)
e c h o" \ $ v a r i a b l e 0 1 " #$ v a r i a b l e 0 1 e c h o" T h eb o o kc o s t\ $ 7 . 9 8 . " #T h eb o o kc o s t$ 7 . 9 8 .

\\ gives the backslash its literal meaning


e c h o" \ \ " #R e s u l t si n\ #W h e r e a s... e c h o" \ " #I n v o k e ss e c o n d a r yp r o m p tf r o mt h ec o m m a n d l i n e . #I nas c r i p t ,g i v e sa ne r r o rm e s s a g e .

#H o w e v e r... e c h o' \ ' #R e s u l t si n\

The behavior of \ depends on whether it is escaped, strong-quoted, weak-quoted, or appearing within command substitution or a here document.
e c h o\ z e c h o\ \ z e c h o' \ z ' e c h o' \ \ z ' e c h o" \ z " e c h o" \ \ z " # S i m p l ee s c a p i n ga n dq u o t i n g # z #\ z #\ z #\ \ z #\ z #\ z # C o m m a n ds u b s t i t u t i o n # z # z #\ z #\ z #\ z #\ \ z #\ z #\ z #H e r ed o c u m e n t c a t< < E O F \ z E O F c a t< < E O F \ \ z E O F

e c h o` e c h o\ z ` e c h o` e c h o\ \ z ` e c h o` e c h o\ \ \ z ` e c h o` e c h o\ \ \ \ z ` e c h o` e c h o\ \ \ \ \ \ z ` e c h o` e c h o\ \ \ \ \ \ \ z ` e c h o` e c h o" \ z " ` e c h o` e c h o" \ \ z " `

#\ z

#\ z

#T h e s ee x a m p l e ss u p p l i e db yS t p h a n eC h a z e l a s .

Elements of a string assigned to a variable may be escaped, but the escape character alone may not be assigned to a

variable.
v a r i a b l e = \ e c h o" $ v a r i a b l e " #W i l ln o tw o r k-g i v e sa ne r r o rm e s s a g e : #t e s t . s h ::c o m m a n dn o tf o u n d #A" n a k e d "e s c a p ec a n n o ts a f e l yb ea s s i g n e dt oav a r i a b l e . # # W h a ta c t u a l l yh a p p e n sh e r ei st h a tt h e" \ "e s c a p e st h en e w l i n ea n d # +t h ee f f e c ti s v a r i a b l e = e c h o" $ v a r i a b l e " # + i n v a l i dv a r i a b l ea s s i g n m e n t v a r i a b l e = \ 2 3 s k i d o o e c h o" $ v a r i a b l e "

# 2 3 s k i d o o # T h i sw o r k s ,s i n c et h es e c o n dl i n e # +i sav a l i dv a r i a b l ea s s i g n m e n t .

v a r i a b l e = \ # \ ^ e s c a p ef o l l o w e db ys p a c e e c h o" $ v a r i a b l e " #s p a c e v a r i a b l e = \ \ e c h o" $ v a r i a b l e "

#\

v a r i a b l e = \ \ \ e c h o" $ v a r i a b l e " #W i l ln o tw o r k-g i v e sa ne r r o rm e s s a g e : #t e s t . s h :\ :c o m m a n dn o tf o u n d # # F i r s te s c a p ee s c a p e ss e c o n do n e ,b u tt h et h i r do n ei sl e f t" n a k e d " , # +w i t hs a m er e s u l ta sf i r s ti n s t a n c e ,a b o v e . v a r i a b l e = \ \ \ \ e c h o" $ v a r i a b l e "

#\ \ #S e c o n da n df o u r t he s c a p e se s c a p e d . #T h i si so . k .

Escaping a space can prevent word splitting in a command's argument list.


f i l e _ l i s t = " / b i n / c a t/ b i n / g z i p/ b i n / m o r e/ u s r / b i n / l e s s/ u s r / b i n / e m a c s 2 0 . 7 " #L i s to ff i l e sa sa r g u m e n t ( s )t oac o m m a n d . #A d dt w of i l e st ot h el i s t ,a n dl i s ta l l . l sl/ u s r / X 1 1 R 6 / b i n / x s e t r o o t/ s b i n / d u m p$ f i l e _ l i s t e c h o" " #W h a th a p p e n si fw ee s c a p eac o u p l eo fs p a c e s ? l sl/ u s r / X 1 1 R 6 / b i n / x s e t r o o t \/ s b i n / d u m p \$ f i l e _ l i s t #E r r o r :t h ef i r s tt h r e ef i l e sc o n c a t e n a t e di n t oas i n g l ea r g u m e n tt o' l sl ' # b e c a u s et h et w oe s c a p e ds p a c e sp r e v e n ta r g u m e n t( w o r d )s p l i t t i n g .

The escape also provides a means of writing a multi-line command. Normally, each separate line constitutes a different command, but an escape at the end of a line escapes the newline character, and the command sequence continues on to the next line.
( c d/ s o u r c e / d i r e c t o r y& &t a rc f-.)|\ ( c d/ d e s t / d i r e c t o r y& &t a rx p v f) #R e p e a t i n gA l a nC o x ' sd i r e c t o r yt r e ec o p yc o m m a n d , #b u ts p l i ti n t ot w ol i n e sf o ri n c r e a s e dl e g i b i l i t y . #A sa na l t e r n a t i v e : t a rc f-C/ s o u r c e / d i r e c t o r y.| t a rx p v f-C/ d e s t / d i r e c t o r y #S e en o t eb e l o w . #( T h a n k s ,S t p h a n eC h a z e l a s . )

If a script line ends with a |, a pipe character, then a \, an escape, is not strictly necessary. It is, however, good programming practice to always escape the end of a line of code that continues to the following line.
e c h o" f o o b a r " # f o o # b a r e c h o e c h o' f o o b a r ' #N od i f f e r e n c ey e t . # f o o # b a r e c h o e c h of o o \ b a r #N e w l i n ee s c a p e d . # f o o b a r e c h o e c h o" f o o \ b a r " #S a m eh e r e ,a s\s t i l li n t e r p r e t e da se s c a p ew i t h i nw e a kq u o t e s . # f o o b a r e c h o e c h o' f o o \ b a r ' #E s c a p ec h a r a c t e r\t a k e nl i t e r a l l yb e c a u s eo fs t r o n gq u o t i n g . # f o o \ # b a r #E x a m p l e ss u g g e s t e db yS t p h a n eC h a z e l a s .

Chapter 6. Exit and Exit Status


... there are dark corners in the Bourne shell, and people use all of them. --Chet Ramey The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script's parent process. Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Wellbehaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions. Likewise, functions within a script and the script itself return an exit status. The last command executed in the function or script determines the exit status. Within a script, an e x i tn n ncommand may be used to deliver an n n nexit status to the shell (n n nmust be an integer in the 0 - 255 range). When a script ends with an exit that has no parameter, the exit status of the script is the exit status of the last command executed in the script (previous to the exit).
# ! / b i n / b a s h C O M M A N D _ 1

... C O M M A N D _ L A S T #W i l le x i tw i t hs t a t u so fl a s tc o m m a n d . e x i t

The equivalent of a bare exit is exit $? or even just omitting the exit.
# ! / b i n / b a s h C O M M A N D _ 1 ... C O M M A N D _ L A S T #W i l le x i tw i t hs t a t u so fl a s tc o m m a n d . e x i t$ ? # ! / b i n / b a s h C O M M A N D 1 ... C O M M A N D _ L A S T #W i l le x i tw i t hs t a t u so fl a s tc o m m a n d .

$ ?reads the exit status of the last command

executed. After a function returns, $ ?gives the exit status of the last command executed in the function. This is Bash's way of giving functions a "return value." [32] Following the execution of a pipe, a $ ?gives the exit status of the last command executed. After a script terminates, a $ ?from the command-line gives the exit status of the script, that is, the last command executed in the script, which is, by convention, 0on success or an integer in the range 1 - 255 on error. Example 6-1. exit / exit status
# ! / b i n / b a s h e c h oh e l l o e c h o$ ? #E x i ts t a t u s0r e t u r n e db e c a u s ec o m m a n de x e c u t e ds u c c e s s f u l l y . l s k d f e c h o$ ? e c h o e x i t1 1 3 #W i l lr e t u r n1 1 3t os h e l l . #T ov e r i f yt h i s ,t y p e" e c h o$ ? "a f t e rs c r i p tt e r m i n a t e s . #U n r e c o g n i z e dc o m m a n d . #N o n z e r oe x i ts t a t u sr e t u r n e d-c o m m a n df a i l e dt oe x e c u t e .

# B yc o n v e n t i o n ,a n' e x i t0 'i n d i c a t e ss u c c e s s , # +w h i l ean o n z e r oe x i tv a l u em e a n sa ne r r o ro ra n o m a l o u sc o n d i t i o n . # S e et h e" E x i tC o d e sW i t hS p e c i a lM e a n i n g s "a p p e n d i x .

$? is especially useful for testing the result of a command in a script (see Example 16-35 and Example 16-20). The !, the logical not qualifier, reverses the outcome of a test or command, and this affects its exit status.

Example 6-2. Negating a condition using !


t r u e #T h e" t r u e "b u i l t i n . e c h o" e x i ts t a t u so f\ " t r u e \ "=$ ? " #0

!t r u e e c h o" e x i ts t a t u so f\ " !t r u e \ "=$ ? " #1 #N o t et h a tt h e" ! "n e e d sas p a c eb e t w e e ni ta n dt h ec o m m a n d . # ! t r u e l e a d st oa" c o m m a n dn o tf o u n d "e r r o r # #T h e' ! 'o p e r a t o rp r e f i x i n gac o m m a n di n v o k e st h eB a s hh i s t o r ym e c h a n i s m . t r u e ! t r u e #N oe r r o rt h i st i m e ,b u tn on e g a t i o ne i t h e r . #I tj u s tr e p e a t st h ep r e v i o u sc o m m a n d( t r u e ) .

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #P r e c e d i n ga_ p i p e _w i t h!i n v e r t st h ee x i ts t a t u sr e t u r n e d . l s|b o g u s _ c o m m a n d #b a s h :b o g u s _ c o m m a n d :c o m m a n dn o tf o u n d e c h o$ ? #1 2 7 !l s|b o g u s _ c o m m a n d #b a s h :b o g u s _ c o m m a n d :c o m m a n dn o tf o u n d e c h o$ ? #0 #N o t et h a tt h e!d o e sn o tc h a n g et h ee x e c u t i o no ft h ep i p e . #O n l yt h ee x i ts t a t u sc h a n g e s . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #T h a n k s ,S t p h a n eC h a z e l a sa n dK r i s t o p h e rN e w s o m e .

Certain exit status codes have reserved meanings and should not be user-specified in a script.

Chapter 7. Tests
Every reasonably complete programming language can test for a condition, then act according to the result of the test. Bash has the test command, various bracket and parenthesis operators, and the if/then construct.

7.1. Test Constructs


An if/then construct tests whether the exit status of a list of commands is 0 (since 0 means "success" by UNIX convention), and if so, executes one or more commands. There exists a dedicated command called [ (left bracket special character). It is a synonym for test, and a builtin for efficiency reasons. This command considers its arguments as comparison expressions or file tests and returns an exit status corresponding to the result of the comparison (0 for true, 1 for false). With version 2.02, Bash introduced the [[ ... ]] extended test command, which performs comparisons in a manner more familiar to programmers from other languages. Note that [[ is a keyword, not a command. Bash sees [ [$ al t$ b] ]as a single element, which returns an exit status. The (( ... )) and let ... constructs return an exit status, according to whether the arithmetic expressions they evaluate expand to a non-zero value. These arithmetic-expansion constructs may therefore be used to perform arithmetic comparisons.
( (0& &1) ) e c h o$ ? #1 #L o g i c a lA N D * * *

#A n ds o. . . l e t" n u m=( (0& &1) ) " e c h o$ n u m #0 #B u t. . . l e t" n u m=( (0& &1) ) " e c h o$ ? #1 * * *

( (2 0 0| |1 1) ) #L o g i c a lO R e c h o$ ? #0 * * * #. . . l e t" n u m=( (2 0 0| |1 1) ) " e c h o$ n u m #1 l e t" n u m=( (2 0 0| |1 1) ) " e c h o$ ? #0 * * *

( (2 0 0|1 1) ) e c h o$ ? #. . . l e t" n u m=( (2 0 0|1 1) ) " e c h o$ n u m l e t" n u m=( (2 0 0|1 1) ) " e c h o$ ?

#B i t w i s eO R #0 * * *

#2 0 3 #0 * * *

#T h e" l e t "c o n s t r u c tr e t u r n st h es a m ee x i ts t a t u s # +a st h ed o u b l e p a r e n t h e s e sa r i t h m e t i ce x p a n s i o n .

Again, note that the exit status of an arithmetic expression is not an error value.
v a r = 2& &( (v a r + = 2) ) e c h o$ ? #1

v a r = 2& &( (v a r + = 2) )& &e c h o$ v a r #W i l ln o te c h o$ v a r !

An if can test any command, not just conditions enclosed within brackets.
i fc m pab& >/ d e v / n u l l #S u p p r e s so u t p u t . t h e ne c h o" F i l e saa n dba r ei d e n t i c a l . " e l s ee c h o" F i l e saa n dbd i f f e r . " f i #T h ev e r yu s e f u l" i f g r e p "c o n s t r u c t : #i fg r e pqB a s hf i l e t h e ne c h o" F i l ec o n t a i n sa tl e a s to n eo c c u r r e n c eo fB a s h . " f i w o r d = L i n u x l e t t e r _ s e q u e n c e = i n u i fe c h o" $ w o r d "|g r e pq" $ l e t t e r _ s e q u e n c e " #T h e" q "o p t i o nt og r e ps u p p r e s s e so u t p u t . t h e n e c h o" $ l e t t e r _ s e q u e n c ef o u n di n$ w o r d " e l s e e c h o" $ l e t t e r _ s e q u e n c en o tf o u n di n$ w o r d " f i

i fC O M M A N D _ W H O S E _ E X I T _ S T A T U S _ I S _ 0 _ U N L E S S _ E R R O R _ O C C U R R E D t h e ne c h o" C o m m a n ds u c c e e d e d . " e l s ee c h o" C o m m a n df a i l e d . " f i

These last two examples courtesy of Stphane Chazelas.

Example 7-1. What is truth?


# ! / b i n / b a s h # T i p : # I fy o u ' r eu n s u r eh o wac e r t a i nc o n d i t i o nm i g h te v a l u a t e , # +t e s ti ti na ni f t e s t . e c h o e c h o" T e s t i n g\ " 0 \ " " i f[0] #z e r o t h e n e c h o" 0i st r u e . " e l s e #O re l s e. . . e c h o" 0i sf a l s e . " f i #0i st r u e . e c h o e c h o" T e s t i n g\ " 1 \ " " i f[1] #o n e t h e n e c h o" 1i st r u e . " e l s e e c h o" 1i sf a l s e . " f i #1i st r u e . e c h o e c h o" T e s t i n g\ " 1 \ " " i f[1] #m i n u so n e t h e n e c h o" 1i st r u e . " e l s e e c h o" 1i sf a l s e . " f i #1i st r u e . e c h o e c h o" T e s t i n g\ " N U L L \ " " i f[] #N U L L( e m p t yc o n d i t i o n ) t h e n e c h o" N U L Li st r u e . " e l s e e c h o" N U L Li sf a l s e . " f i #N U L Li sf a l s e . e c h o e c h o" T e s t i n g\ " x y z \ " " i f[x y z] #s t r i n g t h e n e c h o" R a n d o ms t r i n gi st r u e . " e l s e e c h o" R a n d o ms t r i n gi sf a l s e . " f i #R a n d o ms t r i n gi st r u e . e c h o e c h o" T e s t i n g\ " \ $ x y z \ " " i f[$ x y z] #T e s t si f$ x y zi sn u l l ,b u t . . . #i t ' so n l ya nu n i n i t i a l i z e dv a r i a b l e . t h e n e c h o" U n i n i t i a l i z e dv a r i a b l ei st r u e . " e l s e e c h o" U n i n i t i a l i z e dv a r i a b l ei sf a l s e . " f i #U n i n i t i a l i z e dv a r i a b l ei sf a l s e .

e c h o e c h o" T e s t i n g\ " n\ $ x y z \ " " i f[n" $ x y z "] #M o r ep e d a n t i c a l l yc o r r e c t . t h e n e c h o" U n i n i t i a l i z e dv a r i a b l ei st r u e . " e l s e e c h o" U n i n i t i a l i z e dv a r i a b l ei sf a l s e . " f i #U n i n i t i a l i z e dv a r i a b l ei sf a l s e . e c h o

x y z =

#I n i t i a l i z e d ,b u ts e tt on u l lv a l u e .

e c h o" T e s t i n g\ " n\ $ x y z \ " " i f[n" $ x y z "] t h e n e c h o" N u l lv a r i a b l ei st r u e . " e l s e e c h o" N u l lv a r i a b l ei sf a l s e . " f i #N u l lv a r i a b l ei sf a l s e .

e c h o

#W h e ni s" f a l s e "t r u e ? e c h o" T e s t i n g\ " f a l s e \ " " i f[" f a l s e "] # I ts e e m st h a t" f a l s e "i sj u s tas t r i n g. . . t h e n e c h o" \ " f a l s e \ "i st r u e . "# +a n di tt e s t st r u e . e l s e e c h o" \ " f a l s e \ "i sf a l s e . " f i #" f a l s e "i st r u e . e c h o e c h o" T e s t i n g\ " \ $ f a l s e \ " " #A g a i n ,u n i n i t i a l i z e dv a r i a b l e . i f[" $ f a l s e "] t h e n e c h o" \ " \ $ f a l s e \ "i st r u e . " e l s e e c h o" \ " \ $ f a l s e \ "i sf a l s e . " f i #" $ f a l s e "i sf a l s e . #N o w ,w eg e tt h ee x p e c t e dr e s u l t . # W h a tw o u l dh a p p e ni fw et e s t e dt h eu n i n i t i a l i z e dv a r i a b l e" $ t r u e " ? e c h o e x i t0

Exercise. Explain the behavior of Example 7-1, above.


i f[c o n d i t i o n t r u e] t h e n c o m m a n d1 c o m m a n d2 . . . e l s e #O re l s e. . . #A d d sd e f a u l tc o d eb l o c ke x e c u t i n gi fo r i g i n a lc o n d i t i o nt e s t sf a l s e . c o m m a n d3 c o m m a n d4 . . . f i

When if and then are on same line in a condition test, a semicolon must terminate the if statement. Both if and then are keywords. Keywords (or commands) begin statements, and before a new statement on the same line begins, the old one must terminate.
i f[x" $ f i l e n a m e "] ;t h e n

Else if and elif elif


e l i fis a contraction for else if . i f[c o n d i t i o n 1] t h e n c o m m a n d 1 c o m m a n d 2 c o m m a n d 3 e l i f[c o n d i t i o n 2] #S a m ea se l s ei f t h e n c o m m a n d 4 c o m m a n d 5 e l s e d e f a u l t c o m m a n d f i

The effect is to nest an inner if/then construct within an outer one.

The i ft e s tc o n d i t i o n t r u econstruct is the exact equivalent of i f[c o n d i t i o n t r u e] . As it happens, the left bracket, [ , is a token [33] which invokes the test command. The closing right bracket, ] , in an if/test should not therefore be strictly necessary, however newer versions of Bash require it. The test command is a Bash builtin which tests file types and compares strings. Therefore, in a Bash script, test does not call the external / u s r / b i n / t e s tbinary, which is part of the sh-utils package. Likewise, [ does not call / u s r / b i n / [ , which is linked to / u s r / b i n / t e s t .
b a s h $t y p et e s t t e s ti sas h e l lb u i l t i n b a s h $t y p e' [ ' [i sas h e l lb u i l t i n b a s h $t y p e' [ [ ' [ [i sas h e l lk e y w o r d b a s h $t y p e' ] ] ' ] ]i sas h e l lk e y w o r d b a s h $t y p e' ] ' b a s h :t y p e :] :n o tf o u n d

If, for some reason, you wish to use / u s r / b i n / t e s tin a Bash script, then specify it by full pathname. Example 7-2. Equivalence of test , / u s r / b i n / t e s t , [ ], and / u s r / b i n / [
# ! / b i n / b a s h e c h o i ft e s tz" $ 1 " t h e n e c h o" N oc o m m a n d l i n ea r g u m e n t s . " e l s e e c h o" F i r s tc o m m a n d l i n ea r g u m e n ti s$ 1 . " f i e c h o

i f/ u s r / b i n / t e s tz" $ 1 " #E q u i v a l e n tt o" t e s t "b u i l t i n . # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ #S p e c i f y i n gf u l lp a t h n a m e . t h e n e c h o" N oc o m m a n d l i n ea r g u m e n t s . " e l s e e c h o" F i r s tc o m m a n d l i n ea r g u m e n ti s$ 1 . " f i e c h o i f[z" $ 1 "] #F u n c t i o n a l l yi d e n t i c a lt oa b o v ec o d eb l o c k s . # i f[z" $ 1 " s h o u l dw o r k ,b u t . . . # + B a s hr e s p o n d st oam i s s i n gc l o s e b r a c k e tw i t ha ne r r o rm e s s a g e . t h e n e c h o" N oc o m m a n d l i n ea r g u m e n t s . " e l s e e c h o" F i r s tc o m m a n d l i n ea r g u m e n ti s$ 1 . " f i e c h o

i f/ u s r / b i n / [z" $ 1 "] #A g a i n ,f u n c t i o n a l l yi d e n t i c a lt oa b o v e . #i f/ u s r / b i n / [z" $ 1 " #W o r k s ,b u tg i v e sa ne r r o rm e s s a g e . # #N o t e : # T h i sh a sb e e nf i x e di nB a s h ,v e r s i o n3 . x . t h e n e c h o" N oc o m m a n d l i n ea r g u m e n t s . " e l s e e c h o" F i r s tc o m m a n d l i n ea r g u m e n ti s$ 1 . " f i e c h o e x i t0

The [[ ]] construct is the more versatile Bash version of [ ]. This is the extended test command, adopted from ksh88. *** No filename expansion or word splitting takes place between [[ and ]], but there is parameter expansion and command substitution.
f i l e = / e t c / p a s s w d i f[ [e$ f i l e] ] t h e n e c h o" P a s s w o r df i l ee x i s t s . " f i

Using the [[ ... ]] test construct, rather than [ ... ] can prevent many logic errors in scripts. For example, the &&, ||, <, and > operators work within a [[ ]] test, despite giving an error within a [ ] construct. Arithmetic evaluation of octal / hexadecimal constants takes place automatically within a [[ ... ]] construct.
#[ [O c t a la n dh e x a d e c i m a le v a l u a t i o n] ] #T h a n ky o u ,M o r i t zG r o n b a c h ,f o rp o i n t i n gt h i so u t .

d e c i m a l = 1 5 o c t a l = 0 1 7 #=1 5( d e c i m a l ) h e x = 0 x 0 f #=1 5( d e c i m a l ) i f[" $ d e c i m a l "e q" $ o c t a l "] t h e n e c h o" $ d e c i m a le q u a l s$ o c t a l " e l s e e c h o" $ d e c i m a li sn o te q u a lt o$ o c t a l "

#1 5i sn o te q u a lt o0 1 7

f i

#D o e s n ' te v a l u a t ew i t h i n[s i n g l eb r a c k e t s] !

i f[ [" $ d e c i m a l "e q" $ o c t a l "] ] t h e n e c h o" $ d e c i m a le q u a l s$ o c t a l " #1 5e q u a l s0 1 7 e l s e e c h o" $ d e c i m a li sn o te q u a lt o$ o c t a l " f i #E v a l u a t e sw i t h i n[ [d o u b l eb r a c k e t s] ] ! i f[ [" $ d e c i m a l "e q" $ h e x "] ] t h e n e c h o" $ d e c i m a le q u a l s$ h e x " e l s e e c h o" $ d e c i m a li sn o te q u a lt o$ h e x " f i #[ [$ h e x a d e c i m a l] ]a l s oe v a l u a t e s !

#1 5e q u a l s0 x 0 f

Following an if, neither the test command nor the test brackets ( [ ] or [[ ]] ) are strictly necessary.
d i r = / h o m e / b o z o i fc d" $ d i r "2 > / d e v / n u l l ;t h e n e c h o" N o wi n$ d i r . " e l s e e c h o" C a n ' tc h a n g et o$ d i r . " f i #" 2 > / d e v / n u l l "h i d e se r r o rm e s s a g e .

The "if COMMAND" construct returns the exit status of COMMAND. Similarly, a condition within test brackets may stand alone without an if, when used in combination with a list construct.
v a r 1 = 2 0 v a r 2 = 2 2 [" $ v a r 1 "n e" $ v a r 2 "]& &e c h o" $ v a r 1i sn o te q u a lt o$ v a r 2 " h o m e = / h o m e / b o z o [d" $ h o m e "]| |e c h o" $ h o m ed i r e c t o r yd o e sn o te x i s t . "

The (( )) construct expands and evaluates an arithmetic expression. If the expression evaluates as zero, it returns an exit status of 1, or "false". A non-zero expression returns an exit status of 0, or "true". This is in marked contrast to using the test and [ ] constructs previously discussed. Example 7-3. Arithmetic Tests using (( ))
# ! / b i n / b a s h #a r i t h t e s t s . s h #A r i t h m e t i ct e s t s . #T h e( (. . .) )c o n s t r u c te v a l u a t e sa n dt e s t sn u m e r i c a le x p r e s s i o n s . #E x i ts t a t u so p p o s i t ef r o m[. . .]c o n s t r u c t ! ( (0) ) e c h o" E x i ts t a t u so f\ " ( (0) ) \ "i s$ ? . " ( (1) ) e c h o" E x i ts t a t u so f\ " ( (1) ) \ "i s$ ? . " ( (5>4) ) e c h o" E x i ts t a t u so f\ " ( (5>4) ) \ "i s$ ? . " ( (5>9) ) e c h o" E x i ts t a t u so f\ " ( (5>9) ) \ "i s$ ? . " ( (5= =5) ) e c h o" E x i ts t a t u so f\ " ( (5= =5) ) \ "i s$ ? . "

#1

#0 #t r u e #0 #f a l s e #1 #t r u e #0

#( (5=5) ) g i v e sa ne r r o rm e s s a g e . ( (5-5) ) e c h o" E x i ts t a t u so f\ " ( (5-5) ) \ "i s$ ? . " ( (5/4) ) e c h o" E x i ts t a t u so f\ " ( (5/4) ) \ "i s$ ? . " ( (1/2) ) e c h o" E x i ts t a t u so f\ " ( (1/2) ) \ "i s$ ? . " #0 #1 #D i v i s i o no . k . #0 #D i v i s i o nr e s u l t<1 . #R o u n d e do f ft o0 . #1 #I l l e g a ld i v i s i o nb y0 . #1

( (1/0) )2 > / d e v / n u l l # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ e c h o" E x i ts t a t u so f\ " ( (1/0) ) \ "i s$ ? . " #W h a te f f e c td o e st h e" 2 > / d e v / n u l l "h a v e ? #W h a tw o u l dh a p p e ni fi tw e r er e m o v e d ? #T r yr e m o v i n gi t ,t h e nr e r u n n i n gt h es c r i p t . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #( (. . .) )a l s ou s e f u li na ni f t h e nt e s t . v a r 1 = 5 v a r 2 = 4 i f( (v a r 1>v a r 2) ) t h e n# ^ ^ N o t e :N o t$ v a r 1 ,$ v a r 2 .W h y ? e c h o" $ v a r 1i sg r e a t e rt h a n$ v a r 2 " f i #5i sg r e a t e rt h a n4 e x i t0

7.2. File test operators


Returns true if... -e file exists -a file exists This is identical in effect to -e. It has been "deprecated," [34] and its use is discouraged. -f file is a r e g u l a rfile (not a directory or device file) -s file is not zero size -d file is a directory -b file is a block device

-c file is a character device


d e v i c e 0 = " / d e v / s d a 2 " #/ ( r o o td i r e c t o r y ) i f[b" $ d e v i c e 0 "] t h e n e c h o" $ d e v i c e 0i sab l o c kd e v i c e . " f i #/ d e v / s d a 2i sab l o c kd e v i c e .

d e v i c e 1 = " / d e v / t t y S 1 " #P C M C I Am o d e mc a r d . i f[c" $ d e v i c e 1 "] t h e n e c h o" $ d e v i c e 1i sac h a r a c t e rd e v i c e . " f i #/ d e v / t t y S 1i sac h a r a c t e rd e v i c e .

-p file is a pipe
f u n c t i o ns h o w _ i n p u t _ t y p e ( ) { [p/ d e v / f d / 0]& &e c h oP I P E| |e c h oS T D I N } s h o w _ i n p u t _ t y p e" I n p u t " e c h o" I n p u t "|s h o w _ i n p u t _ t y p e #T h i se x a m p l ec o u r t e s yo fC a r lA n d e r s o n . #S T D I N #P I P E

-h file is a symbolic link -L file is a symbolic link -S file is a socket -t file (descriptor) is associated with a terminal device This test option may be used to check whether the s t d i n[ t 0 ]or s t d o u t[ t 1 ]in a given script is a terminal. -r file has read permission (for the user running the test ) -w file has write permission (for the user running the test) -x

file has execute permission (for the user running the test) -g set-group-id (sgid) flag set on file or directory If a directory has the s g i dflag set, then a file created within that directory belongs to the group that owns the directory, not necessarily to the group of the user who created the file. This may be useful for a directory shared by a workgroup. -u set-user-id (suid) flag set on file A binary owned by root with s e t u s e r i dflag set runs with root privileges, even when an ordinary user invokes it. [35] This is useful for executables (such as pppd and cdrecord) that need to access system hardware. Lacking the suid flag, these binaries could not be invoked by a non-root user.
r w s r x r t 1r o o t 1 7 8 2 3 6O c t 2 2 0 0 0/ u s r / s b i n / p p p d

A file with the s u i dflag set shows an s in its permissions. -k


s t i c k yb i tset

Commonly known as the sticky bit, the save-text-mode flag is a special type of file permission. If a file has this flag set, that file will be kept in cache memory, for quicker access. [36] If set on a directory, it restricts write permission. Setting the sticky bit adds a t to the permissions on the file or directory listing.
d r w x r w x r w t 7r o o t 1 0 2 4M a y1 92 1 : 2 6t m p /

If a user does not own a directory that has the sticky bit set, but has write permission in that directory, she can only delete those files that she owns in it. This keeps users from inadvertently overwriting or deleting each other's files in a publicly accessible directory, such as / t m p . (The owner of the directory or root can, of course, delete or rename files there.) -O you are owner of file -G group-id of file same as yours -N file modified since it was last read f1 -nt f2 file f 1is newer than f 2 f1 -ot f2 file f 1is older than f 2

f1 -ef f2 files f 1and f 2are hard links to the same file ! "not" -- reverses the sense of the tests above (returns true if condition absent). Example 7-4. Testing for broken links
# ! / b i n / b a s h #b r o k e n l i n k . s h #W r i t t e nb yL e eb i g e l o w< l i g e l o w b e e @ y a h o o . c o m > #U s e di nA B SG u i d ew i t hp e r m i s s i o n . # Ap u r es h e l ls c r i p tt of i n dd e a ds y m l i n k sa n do u t p u tt h e mq u o t e d # +s ot h e yc a nb ef e dt ox a r g sa n dd e a l tw i t h: ) # +e g .s hb r o k e n l i n k . s h/ s o m e d i r/ s o m e o t h e r d i r | x a r g sr m # # T h i s ,h o w e v e r ,i sab e t t e rm e t h o d : # # f i n d" s o m e d i r "t y p elp r i n t 0 | \ # x a r g sr 0f i l e | \ # g r e p" b r o k e ns y m b o l i c " | # s e de' s / ^ \ | :* b r o k e ns y m b o l i c . * $ / " / g ' # # +b u tt h a tw o u l d n ' tb ep u r eB a s h ,n o ww o u l di t . # C a u t i o n :b e w a r et h e/ p r o cf i l es y s t e ma n da n yc i r c u l a rl i n k s ! # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

# I fn oa r g sa r ep a s s e dt ot h es c r i p ts e td i r e c t o r i e s t o s e a r c h # +t oc u r r e n td i r e c t o r y . O t h e r w i s es e tt h ed i r e c t o r i e s t o s e a r c h # +t ot h ea r g sp a s s e d . # # # # # # # # # # # # # # # # # # # # # # [$ #e q0]& &d i r e c t o r y s = ` p w d `| |d i r e c t o r y s = $ @

# S e t u pt h ef u n c t i o nl i n k c h kt oc h e c kt h ed i r e c t o r yi ti sp a s s e d # +f o rf i l e st h a ta r el i n k sa n dd o n ' te x i s t ,t h e np r i n tt h e mq u o t e d . # I fo n eo ft h ee l e m e n t si nt h ed i r e c t o r yi sas u b d i r e c t o r yt h e n # +s e n dt h a ts u b d i r e c t o r yt ot h el i n k c h e c kf u n c t i o n . # # # # # # # # # # l i n k c h k( ){ f o re l e m e n ti n$ 1 / * ;d o [h" $ e l e m e n t "a!e" $ e l e m e n t "]& &e c h o\ " $ e l e m e n t \ " [d" $ e l e m e n t "]& &l i n k c h k$ e l e m e n t #O fc o u r s e ,' h 't e s t sf o rs y m b o l i cl i n k ,' d 'f o rd i r e c t o r y . d o n e } # S e n de a c ha r gt h a tw a sp a s s e dt ot h es c r i p tt ot h el i n k c h k ( )f u n c t i o n # +i fi ti sav a l i dd i r e c t o y . I fn o t ,t h e np r i n tt h ee r r o rm e s s a g e # +a n du s a g ei n f o . # # # # # # # # # # # # # # # # # # f o rd i r e c t o r yi n$ d i r e c t o r y s ;d o i f[d$ d i r e c t o r y] t h e nl i n k c h k$ d i r e c t o r y e l s e e c h o" $ d i r e c t o r yi sn o tad i r e c t o r y " e c h o" U s a g e :$ 0d i r 1d i r 2. . . " f i d o n e e x i t$ ?

Example 31-1, Example 11-7, Example 11-3, Example 31-3, and Example A-1 also illustrate uses of the file test operators.

7.3. Other Comparison Operators


A binary comparison operator compares two variables or quantities. Note that integer and string comparison use a different set of operators. integer comparison -eq is equal to
i f[" $ a "e q" $ b "]

-ne is not equal to


i f[" $ a "n e" $ b "]

-gt is greater than


i f[" $ a "g t" $ b "]

-ge is greater than or equal to


i f[" $ a "g e" $ b "]

-lt is less than


i f[" $ a "l t" $ b "]

-le is less than or equal to


i f[" $ a "l e" $ b "]

< is less than (within double parentheses)


( ( " $ a "<" $ b " ) )

<= is less than or equal to (within double parentheses)


( ( " $ a "< =" $ b " ) )

> is greater than (within double parentheses)

( ( " $ a ">" $ b " ) )

>= is greater than or equal to (within double parentheses)


( ( " $ a "> =" $ b " ) )

string comparison = is equal to


i f[" $ a "=" $ b "]

Note the whitespace framing the =.


i f[" $ a " = " $ b " ]is not

equivalent to the above.

== is equal to
i f[" $ a "= =" $ b "]

This is a synonym for =. The == comparison operator behaves differently within a double-brackets test than within single brackets.
[ [$ a= =z *] ] #T r u ei f$ as t a r t sw i t ha n" z "( p a t t e r nm a t c h i n g ) . [ [$ a= =" z * "] ]#T r u ei f$ ai se q u a lt oz *( l i t e r a lm a t c h i n g ) . [$ a= =z *] #F i l eg l o b b i n ga n dw o r ds p l i t t i n gt a k ep l a c e . [" $ a "= =" z * "]#T r u ei f$ ai se q u a lt oz *( l i t e r a lm a t c h i n g ) . #T h a n k s ,S t p h a n eC h a z e l a s

!= is not equal to
i f[" $ a "! =" $ b "]

This operator uses pattern matching within a [[ ... ]] construct. < is less than, in ASCII alphabetical order
i f[ [" $ a "<" $ b "] ] i f[" $ a "\ <" $ b "]

Note that the "<" needs to be escaped within a [ ]construct. > is greater than, in ASCII alphabetical order
i f[ [" $ a ">" $ b "] ] i f[" $ a "\ >" $ b "]

Note that the ">" needs to be escaped within a [ ]construct. See Example 27-11 for an application of this comparison operator. -z string is null, that is, has zero length
S t r i n g = ' ' #Z e r o l e n g t h( " n u l l " )s t r i n gv a r i a b l e .

i f[z" $ S t r i n g "] t h e n e c h o" \ $ S t r i n gi sn u l l . " e l s e e c h o" \ $ S t r i n gi sN O Tn u l l . " f i #$ S t r i n gi sn u l l .

-n string is not null. The ntest requires that the string be quoted within the test brackets. Using an unquoted string with ! -z, or even just the unquoted string alone within test brackets (see Example 7-6) normally works, however, this is an unsafe practice. Always quote a tested string. [37] Example 7-5. Arithmetic and string comparisons
# ! / b i n / b a s h a = 4 b = 5 # H e r e" a "a n d" b "c a nb et r e a t e de i t h e ra si n t e g e r so rs t r i n g s . # T h e r ei ss o m eb l u r r i n gb e t w e e nt h ea r i t h m e t i ca n ds t r i n gc o m p a r i s o n s , # +s i n c eB a s hv a r i a b l e sa r en o ts t r o n g l yt y p e d . # B a s hp e r m i t si n t e g e ro p e r a t i o n sa n dc o m p a r i s o n so nv a r i a b l e s # +w h o s ev a l u ec o n s i s t so fa l l i n t e g e rc h a r a c t e r s . # C a u t i o na d v i s e d ,h o w e v e r . e c h o i f[" $ a "n e" $ b "] t h e n e c h o" $ ai sn o te q u a lt o$ b " e c h o" ( a r i t h m e t i cc o m p a r i s o n ) " f i e c h o i f[" $ a "! =" $ b "] t h e n e c h o" $ ai sn o te q u a lt o$ b . " e c h o" ( s t r i n gc o m p a r i s o n ) " # " 4 " ! =" 5 " #A S C I I5 2! =A S C I I5 3 f i #I nt h i sp a r t i c u l a ri n s t a n c e ,b o t h" n e "a n d" ! = "w o r k . e c h o e x i t0

Example 7-6. Testing whether a string is null

# ! / b i n / b a s h # s t r t e s t . s h :T e s t i n gn u l ls t r i n g sa n du n q u o t e ds t r i n g s , # +b u tn o ts t r i n g sa n ds e a l i n gw a x ,n o tt om e n t i o nc a b b a g e sa n dk i n g s... #U s i n g i f[. . .]

#I fas t r i n gh a sn o tb e e ni n i t i a l i z e d ,i th a sn od e f i n e dv a l u e . #T h i ss t a t ei sc a l l e d" n u l l "( n o tt h es a m ea sz e r o ! ) . i f[n$ s t r i n g 1] #s t r i n g 1h a sn o tb e e nd e c l a r e do ri n i t i a l i z e d . t h e n e c h o" S t r i n g\ " s t r i n g 1 \ "i sn o tn u l l . " e l s e e c h o" S t r i n g\ " s t r i n g 1 \ "i sn u l l . " f i #W r o n gr e s u l t . #S h o w s$ s t r i n g 1a sn o tn u l l ,a l t h o u g hi tw a sn o ti n i t i a l i z e d . e c h o #L e t ' st r yi ta g a i n . i f[n" $ s t r i n g 1 "] #T h i st i m e ,$ s t r i n g 1i sq u o t e d . t h e n e c h o" S t r i n g\ " s t r i n g 1 \ "i sn o tn u l l . " e l s e e c h o" S t r i n g\ " s t r i n g 1 \ "i sn u l l . " f i #Q u o t es t r i n g sw i t h i nt e s tb r a c k e t s ! e c h o i f[$ s t r i n g 1] #T h i st i m e ,$ s t r i n g 1s t a n d sn a k e d . t h e n e c h o" S t r i n g\ " s t r i n g 1 \ "i sn o tn u l l . " e l s e e c h o" S t r i n g\ " s t r i n g 1 \ "i sn u l l . " f i #T h i sw o r k sf i n e . #T h e[. . .]t e s to p e r a t o ra l o n ed e t e c t sw h e t h e rt h es t r i n gi sn u l l . #H o w e v e ri ti sg o o dp r a c t i c et oq u o t ei t( i f[" $ s t r i n g 1 "] ) . # #A sS t e p h a n eC h a z e l a sp o i n t so u t , # i f[$ s t r i n g 1] h a so n ea r g u m e n t ," ] " # i f[" $ s t r i n g 1 "] h a st w oa r g u m e n t s ,t h ee m p t y" $ s t r i n g 1 "a n d" ] "

e c h o

s t r i n g 1 = i n i t i a l i z e d i f[$ s t r i n g 1] #A g a i n ,$ s t r i n g 1s t a n d su n q u o t e d . t h e n e c h o" S t r i n g\ " s t r i n g 1 \ "i sn o tn u l l . " e l s e e c h o" S t r i n g\ " s t r i n g 1 \ "i sn u l l . " f i #A g a i n ,g i v e sc o r r e c tr e s u l t . #S t i l l ,i ti sb e t t e rt oq u o t ei t( " $ s t r i n g 1 " ) ,b e c a u s e...

s t r i n g 1 = " a=b " i f[$ s t r i n g 1] #A g a i n ,$ s t r i n g 1s t a n d su n q u o t e d . t h e n e c h o" S t r i n g\ " s t r i n g 1 \ "i sn o tn u l l . " e l s e e c h o" S t r i n g\ " s t r i n g 1 \ "i sn u l l . " f i #N o tq u o t i n g" $ s t r i n g 1 "n o wg i v e sw r o n gr e s u l t ! e x i t0 #T h a n ky o u ,a l s o ,F l o r i a nW i s s e r ,f o rt h e" h e a d s u p " .

Example 7-7. zmore


# ! / b i n / b a s h #z m o r e #V i e wg z i p p e df i l e sw i t h' m o r e 'f i l t e r . E _ N O A R G S = 8 5 E _ N O T F O U N D = 8 6 E _ N O T G Z I P = 8 7 i f[$ #e q0]#s a m ee f f e c ta s : i f[z" $ 1 "] #$ 1c a ne x i s t ,b u tb ee m p t y : z m o r e" "a r g 2a r g 3 t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e "> & 2 #E r r o rm e s s a g et os t d e r r . e x i t$ E _ N O A R G S #R e t u r n s8 5a se x i ts t a t u so fs c r i p t( e r r o rc o d e ) . f i f i l e n a m e = $ 1 i f[!f" $ f i l e n a m e "] #Q u o t i n g$ f i l e n a m ea l l o w sf o rp o s s i b l es p a c e s . t h e n e c h o" F i l e$ f i l e n a m en o tf o u n d ! "> & 2 #E r r o rm e s s a g et os t d e r r . e x i t$ E _ N O T F O U N D f i i f[$ { f i l e n a m e # # * . }! =" g z "] #U s i n gb r a c k e ti nv a r i a b l es u b s t i t u t i o n . t h e n e c h o" F i l e$ 1i sn o tag z i p p e df i l e ! " e x i t$ E _ N O T G Z I P f i z c a t$ 1|m o r e #U s e st h e' m o r e 'f i l t e r . #M a ys u b s t i t u t e' l e s s 'i fd e s i r e d . e x i t$ ? #S c r i p tr e t u r n se x i ts t a t u so fp i p e . # A c t u a l l y" e x i t$ ? "i su n n e c e s s a r y ,a st h es c r i p tw i l l ,i na n yc a s e , # +r e t u r nt h ee x i ts t a t u so ft h el a s tc o m m a n de x e c u t e d .

compound comparison -a logical and


e x p 1ae x p 2returns true if both

exp1 and exp2 are true.

-o logical or
e x p 1oe x p 2returns true if either exp1

or exp2 is true.

These are similar to the Bash comparison operators && and ||, used within double brackets.
[ [c o n d i t i o n 1& &c o n d i t i o n 2] ]

The -o and -a operators work with the test command or occur within single test brackets.
i f[" $ e x p r 1 "a" $ e x p r 2 "] t h e n e c h o" B o t he x p r 1a n de x p r 2a r et r u e . " e l s e

e c h o" E i t h e re x p r 1o re x p r 2i sf a l s e . " f i

But, as rihad points out:


[1e q1]& &[n" ` e c h ot r u e1 > & 2 ` "] #t r u e [1e q2]& &[n" ` e c h ot r u e1 > & 2 ` "] #( n oo u t p u t ) #^ ^ ^ ^ ^ ^ ^F a l s ec o n d i t i o n .S of a r ,e v e r y t h i n ga se x p e c t e d . #H o w e v e r. . . [1e q2an" ` e c h ot r u e1 > & 2 ` "] #t r u e #^ ^ ^ ^ ^ ^ ^F a l s ec o n d i t i o n .S o ,w h y" t r u e "o u t p u t ? #I si tb e c a u s eb o t hc o n d i t i o nc l a u s e sw i t h i nb r a c k e t se v a l u a t e ? [ [1e q2& &n" ` e c h ot r u e1 > & 2 ` "] ] #( n oo u t p u t ) #N o ,t h a t ' sn o ti t . #A p p a r e n t l y& &a n d| |" s h o r t c i r c u i t "w h i l eaa n dod on o t .

Refer to Example 8-3, Example 27-17, and Example A-29 to see compound comparison operators in action.

7.4. Nested i f / t h e nCondition Tests


Condition tests using the i f / t h e nconstruct may be nested. The net result is equivalent to using the && compound comparison operator.
a = 3 i f[" $ a "g t0] t h e n i f[" $ a "l t5] t h e n e c h o" T h ev a l u eo f\ " a \ "l i e ss o m e w h e r eb e t w e e n0a n d5 . " f i f i #S a m er e s u l ta s : i f[" $ a "g t0]& &[" $ a "l t5] t h e n e c h o" T h ev a l u eo f\ " a \ "l i e ss o m e w h e r eb e t w e e n0a n d5 . " f i

Example 37-4 and Example 17-11 demonstrate nested i f / t h e ncondition tests.

7.5. Testing Your Knowledge of Tests


The systemwide x i n i t r cfile can be used to launch the X server. This file contains quite a number of if/then tests. The following is excerpted from an "ancient" version of x i n i t r c(Red Hat 7.1, or thereabouts).
i f[f$ H O M E / . X c l i e n t s] ;t h e n e x e c$ H O M E / . X c l i e n t s e l i f[f/ e t c / X 1 1 / x i n i t / X c l i e n t s] ;t h e n e x e c/ e t c / X 1 1 / x i n i t / X c l i e n t s e l s e #f a i l s a f es e t t i n g s . A l t h o u g hw es h o u l dn e v e rg e th e r e #( w ep r o v i d ef a l l b a c k si nX c l i e n t sa sw e l l )i tc a n ' th u r t . x c l o c kg e o m e t r y1 0 0 x 1 0 0 5 + 5& x t e r mg e o m e t r y8 0 x 5 0 5 0 + 1 5 0& i f[f/ u s r / b i n / n e t s c a p eaf/ u s r / s h a r e / d o c / H T M L / i n d e x . h t m l] ;t h e n

n e t s c a p e/ u s r / s h a r e / d o c / H T M L / i n d e x . h t m l& f i f i

Explain the test constructs in the above snippet, then examine an updated version of the file, / e t c / X 1 1 / x i n i t / x i n i t r c , and analyze the if/then test constructs there. You may need to refer ahead to the discussions of grep, sed, and regular expressions.

Chapter 8. Operations and Related Topics 8.1. Operators


assignment
v a r i a b l ea s s i g n m e n t

Initializing or changing the value of a variable = All-purpose assignment operator, which works for both arithmetic and string assignments.
v a r = 2 7 c a t e g o r y = m i n e r a l s #N os p a c e sa l l o w e da f t e rt h e" = " .

Do not confuse the "=" assignment operator with the = test operator.
# = a sat e s to p e r a t o r

i f[" $ s t r i n g 1 "=" $ s t r i n g 2 "] t h e n c o m m a n d f i # i f[" X $ s t r i n g 1 "=" X $ s t r i n g 2 "]i ss a f e r , # +t op r e v e n ta ne r r o rm e s s a g es h o u l do n eo ft h ev a r i a b l e sb ee m p t y . # ( T h ep r e p e n d e d" X "c h a r a c t e r sc a n c e lo u t . )

arithmetic operators + plus minus * multiplication / division **

exponentiation
#B a s h ,v e r s i o n2 . 0 2 ,i n t r o d u c e dt h e" * * "e x p o n e n t i a t i o no p e r a t o r . l e t" z = 5 * * 3 " e c h o" z=$ z " #5*5*5 #z=1 2 5

% modulo, or mod (returns the remainder of an integer division operation)


b a s h $e x p r5%3 2

5/3 = 1, with remainder 2 This operator finds use in, among other things, generating numbers within a specific range (see Example 9-11 and Example 9-15) and formatting program output (see Example 27-16 and Example A-6). It can even be used to generate prime numbers, (see Example A-15). Modulo turns up surprisingly often in numerical recipes. Example 8-1. Greatest common divisor
# ! / b i n / b a s h #g c d . s h :g r e a t e s tc o m m o nd i v i s o r # U s e sE u c l i d ' sa l g o r i t h m # T h e" g r e a t e s tc o m m o nd i v i s o r "( g c d )o ft w oi n t e g e r s # +i st h el a r g e s ti n t e g e rt h a tw i l ld i v i d eb o t h ,l e a v i n gn or e m a i n d e r . # E u c l i d ' sa l g o r i t h mu s e ss u c c e s s i v ed i v i s i o n . # I ne a c hp a s s , # + d i v i d e n d< - d i v i s o r # + d i v i s o r < - r e m a i n d e r # + u n t i lr e m a i n d e r=0 . # T h eg c d=d i v i d e n d ,o nt h ef i n a lp a s s . # # F o ra ne x c e l l e n td i s c u s s i o no fE u c l i d ' sa l g o r i t h m ,s e e # +J i mL o y ' ss i t e ,h t t p : / / w w w . j i m l o y . c o m / n u m b e r / e u c l i d s . h t m .

##A r g u m e n tc h e c k A R G S = 2 E _ B A D A R G S = 8 5 i f[$ #n e" $ A R G S "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i r s t n u m b e rs e c o n d n u m b e r " e x i t$ E _ B A D A R G S f i #-

g c d( ) { d i v i d e n d = $ 1 d i v i s o r = $ 2 # A r b i t r a r ya s s i g n m e n t . # !I td o e s n ' tm a t t e rw h i c ho ft h et w oi sl a r g e r . # W h yn o t ? # I fa nu n i n i t i a l i z e dv a r i a b l ei su s e di n s i d e # +t e s tb r a c k e t s ,a ne r r o rm e s s a g er e s u l t s .

r e m a i n d e r = 1

u n t i l[" $ r e m a i n d e r "e q0] d o # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ M u s tb ep r e v i o u s l yi n i t i a l i z e d ! l e t" r e m a i n d e r=$ d i v i d e n d%$ d i v i s o r "

d i v i d e n d = $ d i v i s o r d i v i s o r = $ r e m a i n d e r d o n e }

#N o wr e p e a tw i t h2s m a l l e s tn u m b e r s . #E u c l i d ' sa l g o r i t h m #L a s t$ d i v i d e n di st h eg c d .

g c d$ 1$ 2 e c h o ;e c h o" G C Do f$ 1a n d$ 2=$ d i v i d e n d " ;e c h o

#E x e r c i s e s: ##1 )C h e c kc o m m a n d l i n ea r g u m e n t st om a k es u r et h e ya r ei n t e g e r s , # + a n de x i tt h es c r i p tw i t ha na p p r o p r i a t ee r r o rm e s s a g ei fn o t . #2 )R e w r i t et h eg c d( )f u n c t i o nt ou s el o c a lv a r i a b l e s . e x i t0

+= plus-equal (increment variable by a constant) [38]


l e t" v a r+ =5 "results in v a rbeing incremented

by 5 .

-= minus-equal (decrement variable by a constant) *= times-equal (multiply variable by a constant)


l e t" v a r* =4 "results in v a rbeing multiplied

by 4 .

/= slash-equal (divide variable by a constant) %= mod-equal (remainder of dividing variable by a constant) Arithmetic operators often occur in an expr or let expression. Example 8-2. Using Arithmetic Operations
# ! / b i n / b a s h #C o u n t i n gt o1 1i n1 0d i f f e r e n tw a y s . n = 1 ;e c h on" $ n" l e t" n=$ n+1 " e c h on" $ n" #l e t" n=n+1 " a l s ow o r k s .

:$ ( ( n=$ n+1 ) ) # " : "n e c e s s a r yb e c a u s eo t h e r w i s eB a s ha t t e m p t s # +t oi n t e r p r e t" $ ( ( n=$ n+1 ) ) "a sac o m m a n d . e c h on" $ n" ( (n=n+1) ) # As i m p l e ra l t e r n a t i v et ot h em e t h o da b o v e . # T h a n k s ,D a v i dL o m b a r d ,f o rp o i n t i n gt h i so u t . e c h on" $ n"

n = $ ( ( $ n+1 ) ) e c h on" $ n" :$ [n=$ n+1] # " : "n e c e s s a r yb e c a u s eo t h e r w i s eB a s ha t t e m p t s # +t oi n t e r p r e t" $ [n=$ n+1] "a sac o m m a n d . # W o r k se v e ni f" n "w a si n i t i a l i z e da sas t r i n g . e c h on" $ n" n = $ [$ n+1] # W o r k se v e ni f" n "w a si n i t i a l i z e da sas t r i n g . # *A v o i dt h i st y p eo fc o n s t r u c t ,s i n c ei ti so b s o l e t ea n dn o n p o r t a b l e . # T h a n k s ,S t e p h a n eC h a z e l a s . e c h on" $ n" #N o wf o rC s t y l ei n c r e m e n to p e r a t o r s . #T h a n k s ,F r a n kW a n g ,f o rp o i n t i n gt h i so u t . l e t" n + + " e c h on" $ n" ( (n + +) ) e c h on" $ n" :$ ( (n + +) ) e c h on" $ n" :$ [n + +] e c h on" $ n" e c h o e x i t0 #l e t" + + n " a l s ow o r k s .

#( (+ + n) ) a l s ow o r k s .

#:$ ( (+ + n) )a l s ow o r k s .

#:$ [+ + n]a l s ow o r k s

Integer variables in older versions of Bash were signed long (32-bit) integers, in the range of -2147483648 to 2147483647. An operation that took a variable outside these limits gave an erroneous result.
e c h o$ B A S H _ V E R S I O N a = 2 1 4 7 4 8 3 6 4 6 e c h o" a=$ a " l e t" a + = 1 " e c h o" a=$ a " l e t" a + = 1 " e c h o" a=$ a " #1 . 1 4

#a=2 1 4 7 4 8 3 6 4 6 #I n c r e m e n t" a " . #a=2 1 4 7 4 8 3 6 4 7 #i n c r e m e n t" a "a g a i n ,p a s tt h el i m i t . #a=2 1 4 7 4 8 3 6 4 8 # E R R O R :o u to fr a n g e , #+ a n dt h el e f t m o s tb i t ,t h es i g nb i t , #+ h a sb e e ns e t ,m a k i n gt h er e s u l tn e g a t i v e .

As of version >= 2.05b, Bash supports 64-bit integers. Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings.
a = 1 . 5 l e t" b=$ a+1 . 3 " #E r r o r . #t 2 . s h :l e t :b=1 . 5+1 . 3 :s y n t a xe r r o ri ne x p r e s s i o n # ( e r r o rt o k e ni s" . 5+1 . 3 " ) e c h o" b=$ b " #b = 1

Use bc in scripts that that need floating point calculations or math library functions. bitwise operators. The bitwise operators seldom make an appearance in shell scripts. Their chief use seems to be manipulating and testing values read from ports or sockets. "Bit flipping" is more relevant to compiled languages, such as C

and C++, which provide direct access to system hardware. However, see vladz's ingenious use of bitwise operators in his base64.sh (Example A-54) script. bitwise operators << bitwise left shift (multiplies by 2for each shift position) <<= left-shift-equal
l e t" v a r< < =2 "results in v a rleft-shifted 2bits (multiplied

by 4 )

>> bitwise right shift (divides by 2for each shift position) >>= right-shift-equal (inverse of <<=) & bitwise AND &= bitwise AND-equal | bitwise OR |= bitwise OR-equal ~ bitwise NOT ^ bitwise XOR ^= bitwise XOR-equal logical (boolean) operators ! NOT
i f[!f$ F I L E N A M E] t h e n . . .

&& AND
i f[$ c o n d i t i o n 1]& &[$ c o n d i t i o n 2] # S a m ea s : i f[$ c o n d i t i o n 1a$ c o n d i t i o n 2] # R e t u r n st r u ei fb o t hc o n d i t i o n 1a n dc o n d i t i o n 2h o l dt r u e . . . i f[ [$ c o n d i t i o n 1& &$ c o n d i t i o n 2] ] #A l s ow o r k s . # N o t et h a t& &o p e r a t o rn o tp e r m i t t e di n s i d eb r a c k e t s # +o f[. . .]c o n s t r u c t .

&& may also be used, depending on context, in an and list to concatenate commands. || OR
i f[$ c o n d i t i o n 1]| |[$ c o n d i t i o n 2] #S a m ea s : i f[$ c o n d i t i o n 1o$ c o n d i t i o n 2] #R e t u r n st r u ei fe i t h e rc o n d i t i o n 1o rc o n d i t i o n 2h o l d st r u e . . . i f[ [$ c o n d i t i o n 1| |$ c o n d i t i o n 2] ] #A l s ow o r k s . # N o t et h a t| |o p e r a t o rn o tp e r m i t t e di n s i d eb r a c k e t s # +o fa[. . .]c o n s t r u c t .

Bash tests the exit status of each statement linked with a logical operator. Example 8-3. Compound Condition Tests Using && and ||
# ! / b i n / b a s h a = 2 4 b = 4 7 i f[" $ a "e q2 4]& &[" $ b "e q4 7] t h e n e c h o" T e s t# 1s u c c e e d s . " e l s e e c h o" T e s t# 1f a i l s . " f i #E R R O R : i f[" $ a "e q2 4& &" $ b "e q4 7] # + a t t e m p t st oe x e c u t e '[" $ a "e q2 4' # + a n df a i l st of i n d i n gm a t c h i n g' ] ' . # # N o t e : i f[ [$ ae q2 4& &$ be q2 4] ] w o r k s . # T h ed o u b l e b r a c k e ti f t e s ti sm o r ef l e x i b l e # +t h a nt h es i n g l e b r a c k e tv e r s i o n . # ( T h e" & & "h a sad i f f e r e n tm e a n i n gi nl i n e1 7t h a ni nl i n e6 . ) # T h a n k s ,S t e p h a n eC h a z e l a s ,f o rp o i n t i n gt h i so u t .

i f[" $ a "e q9 8]| |[" $ b "e q4 7] t h e n e c h o" T e s t# 2s u c c e e d s . " e l s e e c h o" T e s t# 2f a i l s . " f i

# T h eaa n doo p t i o n sp r o v i d e # +a na l t e r n a t i v ec o m p o u n dc o n d i t i o nt e s t . # T h a n k st oP a t r i c kC a l l a h a nf o rp o i n t i n gt h i so u t .

i f[" $ a "e q2 4a" $ b "e q4 7] t h e n e c h o" T e s t# 3s u c c e e d s . " e l s e e c h o" T e s t# 3f a i l s . " f i

i f[" $ a "e q9 8o" $ b "e q4 7] t h e n e c h o" T e s t# 4s u c c e e d s . " e l s e e c h o" T e s t# 4f a i l s . " f i

a = r h i n o b = c r o c o d i l e i f[" $ a "=r h i n o]& &[" $ b "=c r o c o d i l e] t h e n e c h o" T e s t# 5s u c c e e d s . " e l s e e c h o" T e s t# 5f a i l s . " f i e x i t0

The && and || operators also find use in an arithmetic context.


b a s h $e c h o$ ( (1& &2) )$ ( ( 3& &0 ) )$ ( ( 4| |0 ) )$ ( ( 0| |0 ) ) 1010

miscellaneous operators , Comma operator The comma operator chains together two or more arithmetic operations. All the operations are evaluated (with possible side effects. [39]
l e t" t 1=( ( 5+3 ,7-1 ,1 5-4 ) ) " e c h o" t 1=$ t 1 " ^ ^ ^ ^ ^ ^ #t 1=1 1 #H e r et 1i ss e tt ot h er e s u l to ft h el a s to p e r a t i o n .W h y ? l e t" t 2=( ( a=9 ,1 5/3 ) ) " e c h o" t 2=$ t 2 a=$ a " #S e t" a "a n dc a l c u l a t e" t 2 " . #t 2=5 a=9

The comma operator finds use mainly in for loops. See Example 11-12.

8.2. Numerical Constants


A shell script interprets a number as decimal (base 10), unless that number has a special prefix or notation. A number preceded by a 0is o c t a l(base 8). A number preceded by 0 xis h e x a d e c i m a l(base 16). A number with an embedded # evaluates as B A S E # N U M B E R(with range and notational restrictions). Example 8-4. Representation of numerical constants
# ! / b i n / b a s h #n u m b e r s . s h :R e p r e s e n t a t i o no fn u m b e r si nd i f f e r e n tb a s e s .

#D e c i m a l :t h ed e f a u l t l e t" d e c=3 2 " e c h o" d e c i m a ln u m b e r=$ d e c " #N o t h i n go u to ft h eo r d i n a r yh e r e .

#3 2

#O c t a l :n u m b e r sp r e c e d e db y' 0 '( z e r o ) l e t" o c t=0 3 2 " e c h o" o c t a ln u m b e r=$ o c t " #2 6 #E x p r e s s e sr e s u l ti nd e c i m a l . #----

#H e x a d e c i m a l :n u m b e r sp r e c e d e db y' 0 x 'o r' 0 X ' l e t" h e x=0 x 3 2 " e c h o" h e x a d e c i m a ln u m b e r=$ h e x " #5 0 e c h o$ ( ( 0 x 9 a b c ) ) #3 9 6 1 2 # ^ ^ ^ ^ d o u b l e p a r e n t h e s e sa r i t h m e t i ce x p a n s i o n / e v a l u a t i o n #E x p r e s s e sr e s u l ti nd e c i m a l .

#O t h e rb a s e s :B A S E # N U M B E R #B A S Eb e t w e e n2a n d6 4 . #N U M B E Rm u s tu s es y m b o l sw i t h i nt h eB A S Er a n g e ,s e eb e l o w .

l e t" b i n=2 # 1 1 1 1 0 0 1 1 1 0 0 1 1 0 1 " e c h o" b i n a r yn u m b e r=$ b i n " l e t" b 3 2=3 2 # 7 7 " e c h o" b a s e 3 2n u m b e r=$ b 3 2 "

#3 1 1 8 1

#2 3 1

l e t" b 6 4=6 4 # @ _ " e c h o" b a s e 6 4n u m b e r=$ b 6 4 " #4 0 3 1 #T h i sn o t a t i o no n l yw o r k sf o ral i m i t e dr a n g e( 2-6 4 )o fA S C I Ic h a r a c t e r s . #1 0d i g i t s+2 6l o w e r c a s ec h a r a c t e r s+2 6u p p e r c a s ec h a r a c t e r s+@+_

e c h o e c h o$ ( ( 3 6 # z z ) )$ ( ( 2 # 1 0 1 0 1 0 1 0 ) )$ ( ( 1 6 # A F 1 6 ) )$ ( ( 5 3 # 1 a A ) ) #1 2 9 51 7 04 4 8 2 23 3 7 5

# I m p o r t a n tn o t e : # # U s i n gad i g i to u to fr a n g eo ft h es p e c i f i e db a s en o t a t i o n # +g i v e sa ne r r o rm e s s a g e . l e t" b a d _ o c t=0 8 1 " #( P a r t i a l )e r r o rm e s s a g eo u t p u t : # b a d _ o c t=0 8 1 :v a l u et o og r e a tf o rb a s e( e r r o rt o k e ni s" 0 8 1 " ) # O c t a ln u m b e r su s eo n l yd i g i t si nt h er a n g e0-7 . e x i t$ ? #E x i tv a l u e=1( e r r o r )

#T h a n k s ,R i c hB a r t e l la n dS t e p h a n eC h a z e l a s ,f o rc l a r i f i c a t i o n .

8.3. The Double-Parentheses Construct


Similar to the let command, the (( ... )) construct permits arithmetic expansion and evaluation. In its simplest form, a = $ ( (5 +3) )would set ato 5 + 3 , or 8 . However, this double-parentheses construct is also a mechanism for allowing C-style manipulation of variables in Bash, for example, ( (v a r + +) ) .

Example 8-5. C-style manipulation of variables


# ! / b i n / b a s h #c v a r s . s h #M a n i p u l a t i n gav a r i a b l e ,C s t y l e ,u s i n gt h e( (. . .) )c o n s t r u c t .

e c h o ( (a=2 3) ) # S e t t i n gav a l u e ,C s t y l e , # +w i t hs p a c e so nb o t hs i d e so ft h e" = " . e c h o" a( i n i t i a lv a l u e )=$ a " #2 3 ( (a + +) ) # P o s t i n c r e m e n t' a ' ,C s t y l e . e c h o" a( a f t e ra + + )=$ a " #2 4 ( (a -) ) # P o s t d e c r e m e n t' a ' ,C s t y l e . e c h o" a( a f t e ra )=$ a " #2 3

( (+ + a) ) # P r e i n c r e m e n t' a ' ,C s t y l e . e c h o" a( a f t e r+ + a )=$ a " #2 4 ( (a) ) # P r e d e c r e m e n t' a ' ,C s t y l e . e c h o" a( a f t e ra )=$ a " #2 3 e c h o # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # N o t et h a t ,a si nC ,p r e -a n dp o s t d e c r e m e n to p e r a t o r s # +h a v ed i f f e r e n ts i d e e f f e c t s . n = 1 ;l e tn& &e c h o" T r u e "| |e c h o" F a l s e " #F a l s e n = 1 ;l e tn -& &e c h o" T r u e "| |e c h o" F a l s e " #T r u e # T h a n k s ,J e r o e nD o m b u r g . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # e c h o ( (t=a < 4 5 ? 7 : 1 1) ) #C s t y l et r i n a r yo p e r a t o r . # ^ ^^ e c h o" I fa<4 5 ,t h e nt=7 ,e l s et=1 1 . " #a=2 3 e c h o" t=$ t" #t=7 e c h o

##E a s t e rE g ga l e r t ! ## C h e tR a m e ys e e m st oh a v es n u c kab u n c ho fu n d o c u m e n t e dC s t y l e # +c o n s t r u c t si n t oB a s h( a c t u a l l ya d a p t e df r o mk s h ,p r e t t ym u c h ) . # I nt h eB a s hd o c s ,R a m e yc a l l s( (. . .) )s h e l la r i t h m e t i c , # +b u ti tg o e sf a rb e y o n dt h a t . # S o r r y ,C h e t ,t h es e c r e ti so u t . #S e ea l s o" f o r "a n d" w h i l e "l o o p su s i n gt h e( (. . .) )c o n s t r u c t . #T h e s ew o r ko n l yw i t hv e r s i o n2 . 0 4o rl a t e ro fB a s h . e x i t

See also Example 11-12 and Example 8-4.

8.4. Operator Precedence


In a script, operations execute in order of precedence: the higher precedence operations execute before the lower precedence ones. [40] Table 8-1. Operator Precedence Operator
v a r + +v a r + + v a rv a r

Meaning

Comments HIGHEST PRECEDENCE

post-increment, post-decrement C-style operators pre-increment, pre-decrement negation exponentiation addition, subtraction left, right shift unary comparison unary comparison comparison compound comparison equality / inequality AND XOR OR AND OR trinary operator assignment logical / bitwise, inverts sense of following operator arithmetic operation arithmetic operation bitwise string is/is-not null file-test string and integer file-test test operators, string and integer bitwise exclusive OR, bitwise bitwise logical, compound comparison logical, compound comparison C-style (do not confuse with equality test ) times-equal, divide-equal, mod-equal, etc. links a sequence of operations LOWEST PRECEDENCE

!~

* * */% +-

multiplication, division, modulo arithmetic operation

< <> >

zn eftx ,e t c .

<l t>g t< =l e> =g e compound n to te f = =e q! =n e

& ^ |

& &a | |o

? : =

* =/ =% =+ ==< < => > =& = combination assignment

comma

In practice, all you really need to remember is the following: The "My Dear Aunt Sally" mantra (multiply, divide, add, subtract ) for the familiar arithmetic operations. The compound logical operators, &&, ||, -a, and -o have low precedence.

The order of evaluation of equal-precedence operators is usually left-to-right . Now, let's utilize our knowledge of operator precedence to analyze a couple of lines from the / e t c / i n i t . d / f u n c t i o n s f i l e , as found in the Fedora Core Linux distro.
w h i l e[n" $ r e m a i n i n g "a" $ r e t r y "g t0] ;d o #T h i sl o o k sr a t h e rd a u n t i n ga tf i r s tg l a n c e .

#S e p a r a t et h ec o n d i t i o n s : w h i l e[n" $ r e m a i n i n g "a" $ r e t r y "g t0] ;d o # c o n d i t i o n1 -^ ^c o n d i t i o n2 # I fv a r i a b l e" $ r e m a i n i n g "i sn o tz e r ol e n g t h # + A N D( a ) # +v a r i a b l e" $ r e t r y "i sg r e a t e r t h a nz e r o # +t h e n # +t h e[e x p r e s i o n w i t h i n c o n d i t i o n b r a c k e t s]r e t u r n ss u c c e s s( 0 ) # +a n dt h ew h i l e l o o pe x e c u t e sa ni t e r a t i o n . # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # E v a l u a t e" c o n d i t i o n1 "a n d" c o n d i t i o n2 "* * * b e f o r e * * * # +A N D i n gt h e m .W h y ?B e c a u s et h eA N D( a )h a sal o w e rp r e c e d e n c e # +t h a nt h ena n dg to p e r a t o r s , # +a n dt h e r e f o r eg e t se v a l u a t e d* l a s t * . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # i f[f/ e t c / s y s c o n f i g / i 1 8 naz" $ { N O L O C A L E : } "];t h e n

#A g a i n ,s e p a r a t et h ec o n d i t i o n s : i f[f/ e t c / s y s c o n f i g / i 1 8 naz" $ { N O L O C A L E : } "];t h e n # c o n d i t i o n1 -^ ^c o n d i t i o n2 # I ff i l e" / e t c / s y s c o n f i g / i 1 8 n "e x i s t s # + A N D( a ) # +v a r i a b l e$ N O L O C A L Ei sz e r ol e n g t h # +t h e n # +t h e[t e s t e x p r e s i o n w i t h i n c o n d i t i o n b r a c k e t s]r e t u r n ss u c c e s s( 0 ) # +a n dt h ec o m m a n d sf o l l o w i n ge x e c u t e . # # A sb e f o r e ,t h eA N D( a )g e t se v a l u a t e d* l a s t * # +b e c a u s ei th a st h el o w e s tp r e c e d e n c eo ft h eo p e r a t o r sw i t h i n # +t h et e s tb r a c k e t s . # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # N o t e : # $ { N O L O C A L E : }i sap a r a m e t e re x p a n s i o nt h a ts e e m sr e d u n d a n t . # B u t ,i f$ N O L O C A L Eh a sn o tb e e nd e c l a r e d ,i tg e t ss e tt o* n u l l * , # +i ne f f e c td e c l a r i n gi t . # T h i sm a k e sad i f f e r e n c ei ns o m ec o n t e x t s .

To avoid confusion or error in a complex sequence of test operators, break up the sequence into bracketed sections.
i f[" $ v 1 "g t" $ v 2 " o " $ v 1 "l t" $ v 2 " a e" $ f i l e n a m e "] #U n c l e a rw h a t ' sg o i n go nh e r e . . . i f[ [" $ v 1 "g t" $ v 2 "] ]| |[ [" $ v 1 "l t" $ v 2 "] ]& &[ [e" $ f i l e n a m e "] ] #M u c hb e t t e r-t h ec o n d i t i o nt e s t sa r eg r o u p e di nl o g i c a ls e c t i o n s .

Part 3. Beyond the Basics


Table of Contents 9. Another Look at Variables

9.1. Internal Variables 9.2. Typing variables: declare or typeset 9.3. $RANDOM: generate random integer 10. Manipulating Variables 10.1. Manipulating Strings 10.2. Parameter Substitution 11. Loops and Branches 11.1. Loops 11.2. Nested Loops 11.3. Loop Control 11.4. Testing and Branching 12. Command Substitution 13. Arithmetic Expansion 14. Recess Time

Chapter 9. Another Look at Variables


Used properly, variables can add power and flexibility to scripts. This requires learning their subtleties and nuances.

9.1. Internal Variables


B u i l t i nv a r i a b l e s :

variables affecting bash script behavior


$ B A S H

The path to the Bash binary itself


b a s h $e c h o$ B A S H / b i n / b a s h $ B A S H _ E N V

An environmental variable pointing to a Bash startup file to be read when a script is invoked
$ B A S H _ S U B S H E L L

A variable indicating the subshell level. This is a new addition to Bash, version 3. See Example 21-1 for usage.
$ B A S H P I D

Process ID of the current instance of Bash. This is not the same as the $$ variable, but it often gives the same result.
b a s h 4 $e c h o$ $ 1 1 0 1 5

b a s h 4 $e c h o$ B A S H P I D 1 1 0 1 5

b a s h 4 $p sa x|g r e pb a s h 4 1 1 0 1 5p t s / 2 R 0 : 0 0b a s h 4

But ...
# ! / b i n / b a s h 4 e c h o" \ $ \ $o u t s i d eo fs u b s h e l l=$ $ " e c h o" \ $ B A S H _ S U B S H E L L o u t s i d eo fs u b s h e l l=$ B A S H _ S U B S H E L L " e c h o" \ $ B A S H P I Do u t s i d eo fs u b s h e l l=$ B A S H P I D " e c h o (e c h o" \ $ \ $i n s i d eo fs u b s h e l l=$ $ " e c h o" \ $ B A S H _ S U B S H E L Li n s i d eo fs u b s h e l l=$ B A S H _ S U B S H E L L " e c h o" \ $ B A S H P I Di n s i d eo fs u b s h e l l=$ B A S H P I D ") #N o t et h a t$ $r e t u r n sP I Do fp a r e n tp r o c e s s . $ B A S H _ V E R S I N F O [ n ] #9 6 0 2 #1 #9 6 0 3 #9 6 0 2 #0 #9 6 0 2

A 6-element array containing version information about the installed release of Bash. This is similar to $ B A S H _ V E R S I O N , below, but a bit more detailed.
#B a s hv e r s i o ni n f o : f o rni n012345 d o e c h o" B A S H _ V E R S I N F O [ $ n ]=$ { B A S H _ V E R S I N F O [ $ n ] } " d o n e #B A S H _ V E R S I N F O [ 0 ]=3 #B A S H _ V E R S I N F O [ 1 ]=0 0 #B A S H _ V E R S I N F O [ 2 ]=1 4 #B A S H _ V E R S I N F O [ 3 ]=1 #B A S H _ V E R S I N F O [ 4 ]=r e l e a s e #B A S H _ V E R S I N F O [ 5 ]=i 3 8 6 r e d h a t l i n u x g n u #M a j o rv e r s i o nn o . #M i n o rv e r s i o nn o . #P a t c hl e v e l . #B u i l dv e r s i o n . #R e l e a s es t a t u s . #A r c h i t e c t u r e #( s a m ea s$ M A C H T Y P E ) .

$ B A S H _ V E R S I O N

The version of Bash installed on the system


b a s h $e c h o$ B A S H _ V E R S I O N 3 . 2 . 2 5 ( 1 ) r e l e a s e

t c s h %e c h o$ B A S H _ V E R S I O N B A S H _ V E R S I O N :U n d e f i n e dv a r i a b l e .

Checking $BASH_VERSION is a good method of determining which shell is running. $SHELL does not necessarily give the correct answer.
$ C D P A T H

A colon-separated list of search paths available to the cd command, similar in function to the $PATH variable for binaries. The $ C D P A T Hvariable may be set in the local ~ / . b a s h r cfile.
b a s h $c db a s h d o c b a s h :c d :b a s h d o c :N os u c hf i l eo rd i r e c t o r y

b a s h $C D P A T H = / u s r / s h a r e / d o c b a s h $c db a s h d o c / u s r / s h a r e / d o c / b a s h d o c

b a s h $e c h o$ P W D / u s r / s h a r e / d o c / b a s h d o c

$ D I R S T A C K

The top value in the directory stack [41] (affected by pushd and popd) This builtin variable corresponds to the dirs command, however dirs shows the entire contents of the directory stack.
$ E D I T O R

The default editor invoked by a script, usually vi or emacs .


$ E U I D

"effective" user ID number Identification number of whatever identity the current user has assumed, perhaps by means of su. The $ E U I Dis not necessarily the same as the $UID.
$ F U N C N A M E

Name of the current function


x y z 2 3( ) { e c h o" $ F U N C N A M En o we x e c u t i n g . " #x y z 2 3n o we x e c u t i n g . } x y z 2 3 e c h o" F U N C N A M E=$ F U N C N A M E " #F U N C N A M E= #N u l lv a l u eo u t s i d eaf u n c t i o n .

See also Example A-50.


$ G L O B I G N O R E

A list of filename patterns to be excluded from matching in globbing.


$ G R O U P S

Groups current user belongs to This is a listing (array) of the group id numbers for current user, as recorded in / e t c / p a s s w dand / e t c / g r o u p .
r o o t #e c h o$ G R O U P S 0

r o o t #e c h o$ { G R O U P S [ 1 ] } 1

r o o t #e c h o$ { G R O U P S [ 5 ] } 6

$ H O M E

Home directory of the user, usually / h o m e / u s e r n a m e(see Example 10-7)


$ H O S T N A M E

The hostname command assigns the system host name at bootup in an init script. However, the g e t h o s t n a m e ( ) function sets the Bash internal variable $ H O S T N A M E . See also Example 10-7.
$ H O S T T Y P E

host type Like $MACHTYPE, identifies the system hardware.


b a s h $e c h o$ H O S T T Y P E i 6 8 6 $ I F S

internal field separator This variable determines how Bash recognizes fields, or word boundaries, when it interprets character strings. $IFS defaults to whitespace (space, tab, and newline), but may be changed, for example, to parse a commaseparated data file. Note that $* uses the first character held in $ I F S . See Example 5-1.
b a s h $e c h o" $ I F S " ( W i t h$ I F Ss e tt od e f a u l t ,ab l a n kl i n ed i s p l a y s . )

b a s h $e c h o" $ I F S "|c a tv t e ^ I $ $ ( S h o ww h i t e s p a c e :h e r eas i n g l es p a c e ,^ I[ h o r i z o n t a lt a b ] , a n dn e w l i n e ,a n dd i s p l a y" $ "a te n d o f l i n e . )

b a s h $b a s hc' s e twxyz ;I F S = " : ; " ;e c h o" $ * " ' w : x : y : z ( R e a dc o m m a n d sf r o ms t r i n ga n da s s i g na n ya r g u m e n t st op o sp a r a m s . )

Set $ I F Sto eliminate whitespace in pathnames.


I F S = " $ ( p r i n t f' \ n \ t ' ) " #P e rD a v i dW h e e l e r .

$ I F Sdoes not handle whitespace the same as it does other characters.

Example 9-1. $IFS and whitespace


# ! / b i n / b a s h #i f s . s h

v a r 1 = " a + b + c " v a r 2 = " d e f " v a r 3 = " g , h , i " I F S = + #T h ep l u ss i g nw i l lb ei n t e r p r e t e da sas e p a r a t o r . e c h o$ v a r 1 #abc e c h o$ v a r 2 #d e f

e c h o$ v a r 3 e c h o

#g , h , i

I F S = " " #T h ep l u ss i g nr e v e r t st od e f a u l ti n t e r p r e t a t i o n . #T h em i n u ss i g nw i l lb ei n t e r p r e t e da sas e p a r a t o r . e c h o$ v a r 1 #a + b + c e c h o$ v a r 2 #def e c h o$ v a r 3 #g , h , i e c h o I F S = " , " #T h ec o m m aw i l lb ei n t e r p r e t e da sas e p a r a t o r . #T h em i n u ss i g nr e v e r t st od e f a u l ti n t e r p r e t a t i o n . e c h o$ v a r 1 #a + b + c e c h o$ v a r 2 #d e f e c h o$ v a r 3 #ghi e c h o I F S = "" #T h es p a c ec h a r a c t e rw i l lb ei n t e r p r e t e da sas e p a r a t o r . #T h ec o m m ar e v e r t st od e f a u l ti n t e r p r e t a t i o n . e c h o$ v a r 1 #a + b + c e c h o$ v a r 2 #d e f e c h o$ v a r 3 #g , h , i #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #H o w e v e r. . . #$ I F St r e a t sw h i t e s p a c ed i f f e r e n t l yt h a no t h e rc h a r a c t e r s . o u t p u t _ a r g s _ o n e _ p e r _ l i n e ( ) { f o ra r g d o e c h o" [ $ a r g ] " d o n e# ^ ^ E m b e dw i t h i nb r a c k e t s ,f o ry o u rv i e w i n gp l e a s u r e . } e c h o ;e c h o" I F S = \ "\ " " e c h o" " I F S = "" v a r = "a bc " # ^^ ^ ^ ^ ^ o u t p u t _ a r g s _ o n e _ p e r _ l i n e$ v a r #o u t p u t _ a r g s _ o n e _ p e r _ l i n e` e c h o"a bc #[ a ] #[ b ] #[ c ]

" `

e c h o ;e c h o" I F S = : " e c h o" " I F S = : v a r = " : a : : b : c : : : " #S a m ep a t t e r na sa b o v e , # ^^ ^ ^ ^ ^ # +b u ts u b s t i t u t i n g" : "f o r"" . . . o u t p u t _ a r g s _ o n e _ p e r _ l i n e$ v a r #[ ] #[ a ] #[ ] #[ b ] #[ c ] #[ ] #[ ]

#N o t e" e m p t y "b r a c k e t s . #T h es a m et h i n gh a p p e n sw i t ht h e" F S "f i e l ds e p a r a t o ri na w k .

e c h o e x i t

(Many thanks, Stphane Chazelas, for clarification and above examples.) See also Example 16-41, Example 11-7, and Example 19-14 for instructive examples of using $ I F S .
$ I G N O R E E O F

Ignore EOF: how many end-of-files (control-D) the shell will ignore before logging out.
$ L C _ C O L L A T E

Often set in the . b a s h r cor / e t c / p r o f i l efiles, this variable controls collation order in filename expansion and pattern matching. If mishandled, L C _ C O L L A T Ecan cause unexpected results in filename globbing. As of version 2.05 of Bash, filename globbing no longer distinguishes between lowercase and uppercase letters in a character range between brackets. For example, ls [A-M]* would match both F i l e 1 . t x tand f i l e 1 . t x t . To revert to the customary behavior of bracket matching, set L C _ C O L L A T Eto Cby an e x p o r tL C _ C O L L A T E = Cin / e t c / p r o f i l eand/or ~ / . b a s h r c .
$ L C _ C T Y P E

This internal variable controls character interpretation in globbing and pattern matching.
$ L I N E N O

This variable is the line number of the shell script in which this variable appears. It has significance only within the script in which it appears, and is chiefly useful for debugging purposes.
#* * *B E G I ND E B U GB L O C K* * * l a s t _ c m d _ a r g = $ _ #S a v ei t . e c h o" A tl i n en u m b e r$ L I N E N O ,v a r i a b l e\ " v 1 \ "=$ v 1 " e c h o" L a s tc o m m a n da r g u m e n tp r o c e s s e d=$ l a s t _ c m d _ a r g " #* * *E N DD E B U GB L O C K* * * $ M A C H T Y P E

machine type Identifies the system hardware.


b a s h $e c h o$ M A C H T Y P E i 6 8 6 $ O L D P W D

Old working directory ("OLD-Print-Working-Directory", previous directory you were in).


$ O S T Y P E

operating system type


b a s h $e c h o$ O S T Y P E l i n u x $ P A T H

Path to binaries, usually / u s r / b i n / ,/ u s r / X 1 1 R 6 / b i n / ,/ u s r / l o c a l / b i n , etc. When given a command, the shell automatically does a hash table search on the directories listed in the path for the executable. The path is stored in the environmental variable, $ P A T H , a list of directories, separated by colons. Normally, the system stores the $ P A T Hdefinition in / e t c / p r o f i l eand/or ~ / . b a s h r c(see Appendix H).
b a s h $e c h o$ P A T H / b i n : / u s r / b i n : / u s r / l o c a l / b i n : / u s r / X 1 1 R 6 / b i n : / s b i n : / u s r / s b i n P A T H = $ { P A T H } : / o p t / b i nappends the / o p t / b i ndirectory to

the current path. In a script, it may be expedient to temporarily add a directory to the path in this way. When the script exits, this restores the original $ P A T H(a child process, such as a script, may not change the environment of the parent process, the shell). The current "working directory", . / , is usually omitted from the $ P A T Has a security measure.
$ P I P E S T A T U S

Array variable holding exit status(es) of last executed foreground pipe.


b a s h $e c h o$ P I P E S T A T U S 0 b a s h $l sa l|b o g u s _ c o m m a n d b a s h :b o g u s _ c o m m a n d :c o m m a n dn o tf o u n d b a s h $e c h o$ { P I P E S T A T U S [ 1 ] } 1 2 7 b a s h $l sa l|b o g u s _ c o m m a n d b a s h :b o g u s _ c o m m a n d :c o m m a n dn o tf o u n d b a s h $e c h o$ ? 1 2 7

The members of the $ P I P E S T A T U Sarray hold the exit status of each respective command executed in a pipe. $ P I P E S T A T U S [ 0 ]holds the exit status of the first command in the pipe, $ P I P E S T A T U S [ 1 ]the exit status of the second command, and so on. The $ P I P E S T A T U Svariable may contain an erroneous 0 value in a login shell (in releases prior to 3.0 of Bash).
t c s h %b a s h b a s h $w h o|g r e pn o b o d y|s o r t b a s h $e c h o$ { P I P E S T A T U S [ * ] } 0

The above lines contained in a script would produce the expected 0 1 0output. Thank you, Wayne Pollock for pointing this out and supplying the above example. The $ P I P E S T A T U Svariable gives unexpected results in some contexts.
b a s h $e c h o$ B A S H _ V E R S I O N 3 . 0 0 . 1 4 ( 1 ) r e l e a s e b a s h $$l s|b o g u s _ c o m m a n d|w c b a s h :b o g u s _ c o m m a n d :c o m m a n dn o tf o u n d 0 0 0 b a s h $e c h o$ { P I P E S T A T U S [ @ ] } 1 4 11 2 70

Chet Ramey attributes the above output to the behavior of ls. If ls writes to a pipe whose output is not read, then S I G P I P Ekills it, and its exit status is 141. Otherwise its exit status is 0, as expected. This likewise is the case for tr.
$ P I P E S T A T U Sis a "volatile" variable.

It needs to be captured immediately after the pipe in question, before any other command intervenes.
b a s h $$l s|b o g u s _ c o m m a n d|w c b a s h :b o g u s _ c o m m a n d :c o m m a n dn o tf o u n d 0 0 0 b a s h $e c h o$ { P I P E S T A T U S [ @ ] } 01 2 70 b a s h $e c h o$ { P I P E S T A T U S [ @ ] } 0

The pipefail option may be useful in cases where $ P I P E S T A T U Sdoes not give the desired information.
$ P P I D

The $ P P I Dof a process is the process ID (p i d ) of its parent process. [42] Compare this with the pidof command.
$ P R O M P T _ C O M M A N D

A variable holding a command to be executed just before the primary prompt, $ P S 1is to be displayed.
$ P S 1

This is the main prompt, seen at the command-line.


$ P S 2

The secondary prompt, seen when additional input is expected. It displays as ">".
$ P S 3

The tertiary prompt, displayed in a select loop (see Example 11-29).


$ P S 4

The quartenary prompt, shown at the beginning of each line of output when invoking a script with the -x option. It displays as "+".
$ P W D

Working directory (directory you are in at the time) This is the analog to the pwd builtin command.
# ! / b i n / b a s h E _ W R O N G _ D I R E C T O R Y = 8 5 c l e a r#C l e a rt h es c r e e n . T a r g e t D i r e c t o r y = / h o m e / b o z o / p r o j e c t s / G r e a t A m e r i c a n N o v e l

c d$ T a r g e t D i r e c t o r y e c h o" D e l e t i n gs t a l ef i l e si n$ T a r g e t D i r e c t o r y . " i f[" $ P W D "! =" $ T a r g e t D i r e c t o r y "] t h e n #K e e pf r o mw i p i n go u tw r o n gd i r e c t o r yb ya c c i d e n t . e c h o" W r o n gd i r e c t o r y ! " e c h o" I n$ P W D ,r a t h e rt h a n$ T a r g e t D i r e c t o r y ! " e c h o" B a i l i n go u t ! " e x i t$ E _ W R O N G _ D I R E C T O R Y f i r mr f* r m. [ A Z a z 0 9 ] * #D e l e t ed o t f i l e s . #r mf. [ ^ . ] *. . ? * t or e m o v ef i l e n a m e sb e g i n n i n gw i t hm u l t i p l ed o t s . #( s h o p tsd o t g l o b ;r mf* ) w i l la l s ow o r k . #T h a n k s ,S . C .f o rp o i n t i n gt h i so u t . # Af i l e n a m e( ` b a s e n a m e ` )m a yc o n t a i na l lc h a r a c t e r si nt h e0-2 5 5r a n g e , # +e x c e p t" / " . # D e l e t i n gf i l e sb e g i n n i n gw i t hw e i r dc h a r a c t e r s ,s u c ha s# +i sl e f ta sa ne x e r c i s e .( H i n t :r m. / w e i r d n a m eo rr m-w e i r d n a m e ) r e s u l t = $ ? #R e s u l to fd e l e t eo p e r a t i o n s .I fs u c c e s s f u l=0 . e c h o l sa l #A n yf i l e sl e f t ? e c h o" D o n e . " e c h o" O l df i l e sd e l e t e di n$ T a r g e t D i r e c t o r y . " e c h o #V a r i o u so t h e ro p e r a t i o n sh e r e ,a sn e c e s s a r y . e x i t$ r e s u l t $ R E P L Y

The default value when a variable is not supplied to read. Also applicable to select menus, but only supplies the item number of the variable chosen, not the value of the variable itself.
# ! / b i n / b a s h #r e p l y . s h #R E P L Yi st h ed e f a u l tv a l u ef o ra' r e a d 'c o m m a n d . e c h o e c h on" W h a ti sy o u rf a v o r i t ev e g e t a b l e ?" r e a d e c h o" Y o u rf a v o r i t ev e g e t a b l ei s$ R E P L Y . " # R E P L Yh o l d st h ev a l u eo fl a s t" r e a d "i fa n do n l yi f # +n ov a r i a b l es u p p l i e d . e c h o e c h on" W h a ti sy o u rf a v o r i t ef r u i t ?" r e a df r u i t e c h o" Y o u rf a v o r i t ef r u i ti s$ f r u i t . " e c h o" b u t . . . " e c h o" V a l u eo f\ $ R E P L Yi ss t i l l$ R E P L Y . " # $ R E P L Yi ss t i l ls e tt oi t sp r e v i o u sv a l u eb e c a u s e # +t h ev a r i a b l e$ f r u i ta b s o r b e dt h en e w" r e a d "v a l u e . e c h o e x i t0 $ S E C O N D S

The number of seconds the script has been running.

# ! / b i n / b a s h T I M E _ L I M I T = 1 0 I N T E R V A L = 1 e c h o e c h o" H i tC o n t r o l Ct oe x i tb e f o r e$ T I M E _ L I M I Ts e c o n d s . " e c h o w h i l e[" $ S E C O N D S "l e" $ T I M E _ L I M I T "] d o # $ S E C O N D Si sa ni n t e r n a ls h e l lv a r i a b l e . i f[" $ S E C O N D S "e q1] t h e n u n i t s = s e c o n d e l s e u n i t s = s e c o n d s f i e c h o" T h i ss c r i p th a sb e e nr u n n i n g$ S E C O N D S$ u n i t s . " # O nas l o wo ro v e r b u r d e n e dm a c h i n e ,t h es c r i p tm a ys k i pac o u n t # +e v e r yo n c ei naw h i l e . s l e e p$ I N T E R V A L d o n e e c h oe" \ a " #B e e p ! e x i t0 $ S H E L L O P T S

The list of enabled shell options, a readonly variable.


b a s h $e c h o$ S H E L L O P T S b r a c e e x p a n d : h a s h a l l : h i s t e x p a n d : m o n i t o r : h i s t o r y : i n t e r a c t i v e c o m m e n t s : e m a c s

$ S H L V L

Shell level, how deeply Bash is nested. [43] If, at the command-line, $SHLVL is 1, then in a script it will increment to 2. This variable is not affected by subshells. Use $BASH_SUBSHELL when you need an indication of subshell nesting.
$ T M O U T

If the $ T M O U Tenvironmental variable is set to a non-zero value t i m e , then the shell prompt will time out after $ t i m e seconds. This will cause a logout. As of version 2.05b of Bash, it is now possible to use $ T M O U Tin a script in combination with read.
#W o r k si ns c r i p t sf o rB a s h ,v e r s i o n s2 . 0 5 ba n dl a t e r . T M O U T = 3 #P r o m p tt i m e so u ta tt h r e es e c o n d s .

e c h o" W h a ti sy o u rf a v o r i t es o n g ? " e c h o" Q u i c k l yn o w ,y o uo n l yh a v e$ T M O U Ts e c o n d st oa n s w e r ! " r e a ds o n g i f[z" $ s o n g "] t h e n s o n g = " ( n oa n s w e r ) " #D e f a u l tr e s p o n s e . f i e c h o" Y o u rf a v o r i t es o n gi s$ s o n g . "

There are other, more complex, ways of implementing timed input in a script. One alternative is to set up a timing loop to signal the script when it times out. This also requires a signal handling routine to trap (see Example 32-5) the interrupt generated by the timing loop (whew!). Example 9-2. Timed Input
# ! / b i n / b a s h #t i m e d i n p u t . s h #T M O U T = 3 A l s ow o r k s ,a so fn e w e rv e r s i o n so fB a s h .

T I M E R _ I N T E R R U P T = 1 4 T I M E L I M I T = 3 #T h r e es e c o n d si nt h i si n s t a n c e . #M a yb es e tt od i f f e r e n tv a l u e . P r i n t A n s w e r ( ) { i f[" $ a n s w e r "=T I M E O U T] t h e n e c h o$ a n s w e r e l s e #D o n ' tw a n tt om i xu pt h et w oi n s t a n c e s . e c h o" Y o u rf a v o r i t ev e g g i ei s$ a n s w e r " k i l l$ ! # K i l l sn o l o n g e r n e e d e dT i m e r O nf u n c t i o n # +r u n n i n gi nb a c k g r o u n d . # $ !i sP I Do fl a s tj o br u n n i n gi nb a c k g r o u n d . f i }

T i m e r O n ( ) { s l e e p$ T I M E L I M I T& &k i l ls1 4$ $& #W a i t s3s e c o n d s ,t h e ns e n d ss i g a l a r mt os c r i p t . }

I n t 1 4 V e c t o r ( ) { a n s w e r = " T I M E O U T " P r i n t A n s w e r e x i t$ T I M E R _ I N T E R R U P T } t r a pI n t 1 4 V e c t o r$ T I M E R _ I N T E R R U P T #T i m e ri n t e r r u p t( 1 4 )s u b v e r t e df o ro u rp u r p o s e s . e c h o" W h a ti sy o u rf a v o r i t ev e g e t a b l e" T i m e r O n r e a da n s w e r P r i n t A n s w e r

# A d m i t t e d l y ,t h i si sak l u d g yi m p l e m e n t a t i o no ft i m e di n p u t . # H o w e v e r ,t h e" t "o p t i o nt o" r e a d "s i m p l i f i e st h i st a s k . # S e et h e" t o u t . s h "s c r i p t . # H o w e v e r ,w h a ta b o u tt i m i n gn o tj u s ts i n g l eu s e ri n p u t , # +b u ta ne n t i r es c r i p t ? # I fy o un e e ds o m e t h i n gr e a l l ye l e g a n t. . . # +c o n s i d e rw r i t i n gt h ea p p l i c a t i o ni nCo rC + + , # +u s i n ga p p r o p r i a t el i b r a r yf u n c t i o n s ,s u c ha s' a l a r m 'a n d' s e t i t i m e r . ' e x i t0

An alternative is using stty.

Example 9-3. Once more, timed input


# ! / b i n / b a s h #t i m e o u t . s h # W r i t t e nb yS t e p h a n eC h a z e l a s , # +a n dm o d i f i e db yt h ed o c u m e n ta u t h o r . I N T E R V A L = 5 #t i m e o u ti n t e r v a l

t i m e d o u t _ r e a d ( ){ t i m e o u t = $ 1 v a r n a m e = $ 2 o l d _ t t y _ s e t t i n g s = ` s t t yg ` s t t yi c a n o nm i n0t i m e$ { t i m e o u t } 0 e v a lr e a d$ v a r n a m e #o rj u s t r e a d$ v a r n a m e s t t y" $ o l d _ t t y _ s e t t i n g s " #S e em a np a g ef o r" s t t y . " } e c h o ;e c h on" W h a t ' sy o u rn a m e ?Q u i c k !" t i m e d o u t _ r e a d$ I N T E R V A Ly o u r _ n a m e # T h i sm a yn o tw o r ko ne v e r yt e r m i n a lt y p e . # T h em a x i m u mt i m e o u td e p e n d so nt h et e r m i n a l . # +( i ti so f t e n2 5 . 5s e c o n d s ) . e c h o i f[!z" $ y o u r _ n a m e "] #I fn a m ei n p u tb e f o r et i m e o u t. . . t h e n e c h o" Y o u rn a m ei s$ y o u r _ n a m e . " e l s e e c h o" T i m e do u t . " f i e c h o #T h eb e h a v i o ro ft h i ss c r i p td i f f e r ss o m e w h a tf r o m" t i m e d i n p u t . s h . " #A te a c hk e y s t r o k e ,t h ec o u n t e rr e s e t s . e x i t0

Perhaps the simplest method is using the toption to read. Example 9-4. Timed read
# ! / b i n / b a s h #t o u t . s h[ t i m e o u t ] #I n s p i r e db yas u g g e s t i o nf r o m" s y n g i ns e v e n "( t h a n k s ) .

T I M E L I M I T = 4

#4s e c o n d s

r e a dt$ T I M E L I M I Tv a r i a b l e< & 1 # ^ ^ ^ # I nt h i si n s t a n c e ," < & 1 "i sn e e d e df o rB a s h1 . xa n d2 . x , # b u tu n n e c e s s a r yf o rB a s h3 + . e c h o i f[z" $ v a r i a b l e "] #I sn u l l ? t h e n e c h o" T i m e do u t ,v a r i a b l es t i l lu n s e t . " e l s e e c h o" v a r i a b l e=$ v a r i a b l e " f i

e x i t0 $ U I D

User ID number Current user's user identification number, as recorded in / e t c / p a s s w d This is the current user's real id, even if she has temporarily assumed another identity through su. $ U I Dis a readonly variable, not subject to change from the command line or within a script, and is the counterpart to the id builtin. Example 9-5. Am I root?
# ! / b i n / b a s h #a m i r o o t . s h : R O O T _ U I D = 0 A mIr o o to rn o t ?

#R o o th a s$ U I D0 .

i f[" $ U I D "e q" $ R O O T _ U I D "] #W i l lt h er e a l" r o o t "p l e a s es t a n du p ? t h e n e c h o" Y o ua r er o o t . " e l s e e c h o" Y o ua r ej u s ta no r d i n a r yu s e r( b u tm o ml o v e sy o uj u s tt h es a m e ) . " f i e x i t0

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #C o d eb e l o ww i l ln o te x e c u t e ,b e c a u s et h es c r i p ta l r e a d ye x i t e d . #A na l t e r n a t em e t h o do fg e t t i n gt ot h er o o to fm a t t e r s : R O O T U S E R _ N A M E = r o o t u s e r n a m e = ` i dn u ` #O r . . . u s e r n a m e = ` w h o a m i ` i f[" $ u s e r n a m e "=" $ R O O T U S E R _ N A M E "] t h e n e c h o" R o o t y ,t o o t ,t o o t .Y o ua r er o o t . " e l s e e c h o" Y o ua r ej u s tar e g u l a rf e l l a . " f i

See also Example 2-3. The variables $ E N V ,$ L O G N A M E ,$ M A I L ,$ T E R M ,$ U S E R , and $ U S E R N A M Eare not Bash builtins. These are, however, often set as environmental variables in one of the Bash startup files. $ S H E L L , the name of the user's login shell, may be set from / e t c / p a s s w dor in an "init" script, and it is likewise not a Bash builtin.
t c s h %e c h o$ L O G N A M E b o z o t c s h %e c h o$ S H E L L / b i n / t c s h t c s h %e c h o$ T E R M r x v t b a s h $e c h o$ L O G N A M E b o z o b a s h $e c h o$ S H E L L / b i n / t c s h b a s h $e c h o$ T E R M r x v t

Positional Parameters
$ 0 ,$ 1 ,$ 2 , etc.

Positional parameters, passed from command line to script, passed to a function, or set to a variable (see Example 45 and Example 15-16)
$ #

Number of command-line arguments [44] or positional parameters (see Example 36-2)


$ *

All of the positional parameters, seen as a single word "$ * " must be quoted.
$ @

Same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word. Of course, "$ @ " should be quoted. Example 9-6. arglist : Listing arguments with $* and $@
# ! / b i n / b a s h #a r g l i s t . s h #I n v o k et h i ss c r i p tw i t hs e v e r a la r g u m e n t s ,s u c ha s" o n et w ot h r e e ". . . E _ B A D A R G S = 8 5 i f[!n" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `a r g u m e n t 1a r g u m e n t 2e t c . " e x i t$ E _ B A D A R G S f i e c h o i n d e x = 1 #I n i t i a l i z ec o u n t .

e c h o" L i s t i n ga r g sw i t h\ " \ $ * \ " : " f o ra r gi n" $ * " #D o e s n ' tw o r kp r o p e r l yi f" $ * "i s n ' tq u o t e d . d o e c h o" A r g# $ i n d e x=$ a r g " l e t" i n d e x + = 1 " d o n e #$ *s e e sa l la r g u m e n t sa ss i n g l ew o r d . e c h o" E n t i r ea r gl i s ts e e na ss i n g l ew o r d . " e c h o i n d e x = 1 #R e s e tc o u n t . #W h a th a p p e n si fy o uf o r g e tt od ot h i s ?

e c h o" L i s t i n ga r g sw i t h\ " \ $ @ \ " : " f o ra r gi n" $ @ " d o e c h o" A r g# $ i n d e x=$ a r g " l e t" i n d e x + = 1 " d o n e #$ @s e e sa r g u m e n t sa ss e p a r a t ew o r d s . e c h o" A r gl i s ts e e na ss e p a r a t ew o r d s . " e c h o i n d e x = 1 #R e s e tc o u n t .

e c h o" L i s t i n ga r g sw i t h\ $ *( u n q u o t e d ) : " f o ra r gi n$ * d o e c h o" A r g# $ i n d e x=$ a r g " l e t" i n d e x + = 1 " d o n e #U n q u o t e d$ *s e e sa r g u m e n t sa ss e p a r a t ew o r d s . e c h o" A r gl i s ts e e na ss e p a r a t ew o r d s . " e x i t0

Following a shift, the $ @holds the remaining command-line parameters, lacking the previous $ 1 , which was lost.
# ! / b i n / b a s h #I n v o k ew i t h. / s c r i p t n a m e12345 e c h o" $ @ " s h i f t e c h o" $ @ " s h i f t e c h o" $ @ " #12345 #2345 #345

#E a c h" s h i f t "l o s e sp a r a m e t e r$ 1 . #" $ @ "t h e nc o n t a i n st h er e m a i n i n gp a r a m e t e r s .

The $ @special parameter finds use as a tool for filtering input into shell scripts. The cat "$@" construction accepts input to a script either from s t d i nor from files given as parameters to the script. See Example 16-24 and Example 16-25. The $ *and $ @parameters sometimes display inconsistent and puzzling behavior, depending on the setting of $IFS. Example 9-7. Inconsistent $ *and $ @behavior
# ! / b i n / b a s h # E r r a t i cb e h a v i o ro ft h e" $ * "a n d" $ @ "i n t e r n a lB a s hv a r i a b l e s , # +d e p e n d i n go nw h e t h e ro rn o tt h e ya r eq u o t e d . # D e m o n s t r a t e si n c o n s i s t e n th a n d l i n go fw o r ds p l i t t i n ga n dl i n e f e e d s .

s e t-" F i r s to n e "" s e c o n d "" t h i r d : o n e "" "" F i f t h :: o n e " #S e t t i n gt h es c r i p ta r g u m e n t s ,$ 1 ,$ 2 ,$ 3 ,e t c . e c h o e c h o' I F Su n c h a n g e d ,u s i n g" $ * " ' c = 0 f o rii n" $ * " #q u o t e d d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " #T h i sl i n er e m a i n st h es a m ei ne v e r yi n s t a n c e . #E c h oa r g s . d o n e e c h oe c h o' I F Su n c h a n g e d ,u s i n g$ * ' c = 0 f o rii n$ * #u n q u o t e d d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F Su n c h a n g e d ,u s i n g" $ @ " ' c = 0 f o rii n" $ @ " d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h o-

e c h o' I F Su n c h a n g e d ,u s i n g$ @ ' c = 0 f o rii n$ @ d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oI F S = : e c h o' I F S = " : " ,u s i n g" $ * " ' c = 0 f o rii n" $ * " d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F S = " : " ,u s i n g$ * ' c = 0 f o rii n$ * d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h ov a r = $ * e c h o' I F S = " : " ,u s i n g" $ v a r "( v a r = $ * ) ' c = 0 f o rii n" $ v a r " d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F S = " : " ,u s i n g$ v a r( v a r = $ * ) ' c = 0 f o rii n$ v a r d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h ov a r = " $ * " e c h o' I F S = " : " ,u s i n g$ v a r( v a r = " $ * " ) ' c = 0 f o rii n$ v a r d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F S = " : " ,u s i n g" $ v a r "( v a r = " $ * " ) ' c = 0 f o rii n" $ v a r " d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F S = " : " ,u s i n g" $ @ " ' c = 0 f o rii n" $ @ " d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F S = " : " ,u s i n g$ @ ' c = 0 f o rii n$ @ d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h ov a r = $ @ e c h o' I F S = " : " ,u s i n g$ v a r( v a r = $ @ ) '

c = 0 f o rii n$ v a r d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F S = " : " ,u s i n g" $ v a r "( v a r = $ @ ) ' c = 0 f o rii n" $ v a r " d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h ov a r = " $ @ " e c h o' I F S = " : " ,u s i n g" $ v a r "( v a r = " $ @ " ) ' c = 0 f o rii n" $ v a r " d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h oe c h o' I F S = " : " ,u s i n g$ v a r( v a r = " $ @ " ) ' c = 0 f o rii n$ v a r d oe c h o" $ ( ( c + = 1 ) ) :[ $ i ] " d o n e e c h o #T r yt h i ss c r i p tw i t hk s ho rz s hy . e x i t0 # T h i se x a m p l es c r i p tw r i t t e nb yS t e p h a n eC h a z e l a s , # +a n ds l i g h t l ym o d i f i e db yt h ed o c u m e n ta u t h o r .

The $@ and $* parameters differ only when between double quotes. Example 9-8. $ *and $ @when $ I F Sis empty
# ! / b i n / b a s h # I f$ I F Ss e t ,b u te m p t y , # +t h e n" $ * "a n d" $ @ "d on o te c h op o s i t i o n a lp a r a m sa se x p e c t e d . m e c h o( ) #E c h op o s i t i o n a lp a r a m e t e r s . { e c h o" $ 1 , $ 2 , $ 3 " ; }

I F S = " " s e tabc m e c h o" $ * " # m e c h o$ * m e c h o$ @ m e c h o" $ @ "

#S e t ,b u te m p t y . #P o s i t i o n a lp a r a m e t e r s . #a b c , , ^ ^ #a , b , c #a , b , c #a , b , c

# T h eb e h a v i o ro f$ *a n d$ @w h e n$ I F Si se m p t yd e p e n d s # +o nw h i c hB a s ho rs hv e r s i o nb e i n gr u n . # I ti st h e r e f o r ei n a d v i s a b l et od e p e n do nt h i s" f e a t u r e "i nas c r i p t .

#T h a n k s ,S t e p h a n eC h a z e l a s .

e x i t

Other Special Parameters


$ -

Flags passed to script (using set). See Example 15-16. This was originally a ksh construct adopted into Bash, and unfortunately it does not seem to work reliably in Bash scripts. One possible use for it is to have a script self-test whether it is interactive.
$ !

PID (process ID) of last job run in background


L O G = $ 0 . l o g C O M M A N D 1 = " s l e e p1 0 0 " e c h o" L o g g i n gP I D sb a c k g r o u n dc o m m a n d sf o rs c r i p t :$ 0 "> >" $ L O G " #S ot h e yc a nb em o n i t o r e d ,a n dk i l l e da sn e c e s s a r y . e c h o> >" $ L O G " #L o g g i n gc o m m a n d s . e c h on" P I Do f\ " $ C O M M A N D 1 \ " : "> >" $ L O G " $ { C O M M A N D 1 }& e c h o$ !> >" $ L O G " #P I Do f" s l e e p1 0 0 " : 1 5 0 6 #T h a n ky o u ,J a c q u e sL e d e r e r ,f o rs u g g e s t i n gt h i s .

Using $ !for job control:


p o s s i b l y _ h a n g i n g _ j o b&{s l e e p$ { T I M E O U T } ;e v a l' k i l l9$ ! '& >/ d e v / n u l l ;} #F o r c e sc o m p l e t i o no fa ni l l b e h a v e dp r o g r a m . #U s e f u l ,f o re x a m p l e ,i ni n i ts c r i p t s . #T h a n ky o u ,S y l v a i nF o u r m a n o i t ,f o rt h i sc r e a t i v eu s eo ft h e" ! "v a r i a b l e .

Or, alternately:
#T h i se x a m p l eb yM a t t h e wS a g e . #U s e dw i t hp e r m i s s i o n . T I M E O U T = 3 0 c o u n t = 0 #T i m e o u tv a l u ei ns e c o n d s

p o s s i b l y _ h a n g i n g _ j o b&{ w h i l e( ( c o u n t<T I M E O U T) ) ;d o e v a l' [!d" / p r o c / $ ! "]& &( ( c o u n t=T I M E O U T ) ) ' #/ p r o ci sw h e r ei n f o r m a t i o na b o u tr u n n i n gp r o c e s s e si sf o u n d . #" d "t e s t sw h e t h e ri te x i s t s( w h e t h e rd i r e c t o r ye x i s t s ) . #S o ,w e ' r ew a i t i n gf o rt h ej o bi nq u e s t i o nt os h o wu p . ( ( c o u n t + + ) ) s l e e p1 d o n e e v a l' [d" / p r o c / $ ! "]& &k i l l1 5$ ! ' #I ft h eh a n g i n gj o bi sr u n n i n g ,k i l li t . } # -# # H o w e v e r ,t h i sm a yn o tn o tw o r ka ss p e c i f i e di fa n o t h e rp r o c e s s # +b e g i n st or u na f t e rt h e" h a n g i n g _ j o b "... # I ns u c hac a s e ,t h ew r o n gj o bm a yb ek i l l e d .

# A r i e lM e r a g e l m a ns u g g e s t st h ef o l l o w i n gf i x . T I M E O U T = 3 0 c o u n t = 0 #T i m e o u tv a l u ei ns e c o n d s p o s s i b l y _ h a n g i n g _ j o b&{ w h i l e( ( c o u n t<T I M E O U T) ) ;d o e v a l' [!d" / p r o c / $ l a s t j o b "]& &( ( c o u n t=T I M E O U T ) ) ' l a s t j o b = $ ! ( ( c o u n t + + ) ) s l e e p1 d o n e e v a l' [d" / p r o c / $ l a s t j o b "]& &k i l l1 5$ l a s t j o b ' } e x i t $ _

Special variable set to final argument of previous command executed. Example 9-9. Underscore variable
# ! / b i n / b a s h e c h o$ _ # / b i n / b a s h # J u s tc a l l e d/ b i n / b a s ht or u nt h es c r i p t . # N o t et h a tt h i sw i l lv a r ya c c o r d i n gt o # +h o wt h es c r i p ti si n v o k e d . # S on oo u t p u tf r o mc o m m a n d . # d u # S on oo u t p u tf r o mc o m m a n d . # a l ( l a s ta r g u m e n t )

d u> / d e v / n u l l e c h o$ _ l sa l> / d e v / n u l l e c h o$ _ : e c h o$ _ $ ?

# :

Exit status of a command, function, or the script itself (see Example 24-7)
$ $

Process ID (PID) of the script itself. [45] The $ $variable often finds use in scripts to construct "unique" temp file names (see Example 32-6, Example 16-31, and Example 15-27). This is usually simpler than invoking mktemp.

9.2. Typing variables: declare or typeset


The declare or typeset builtins, which are exact synonyms, permit modifying the properties of variables. This is a very weak form of the typing [46] available in certain programming languages. The declare command is specific to version 2 or later of Bash. The typeset command also works in ksh scripts. declare/typeset options -r r e a d o n l y (d e c l a r erv a r 1works the same as r e a d o n l yv a r 1 ) This is the rough equivalent of the C const type qualifier. An attempt to change the value of a readonly variable fails

with an error message.


d e c l a r erv a r 1 = 1 e c h o" v a r 1=$ v a r 1 " ( (v a r 1 + +) ) #v a r 1=1 #x . s h :l i n e4 :v a r 1 :r e a d o n l yv a r i a b l e

-i i n t e g e r
d e c l a r ein u m b e r #T h es c r i p tw i l lt r e a ts u b s e q u e n to c c u r r e n c e so f" n u m b e r "a sa ni n t e g e r . n u m b e r = 3 e c h o" N u m b e r=$ n u m b e r "

#N u m b e r=3

n u m b e r = t h r e e e c h o" N u m b e r=$ n u m b e r " #N u m b e r=0 #T r i e st oe v a l u a t et h es t r i n g" t h r e e "a sa ni n t e g e r .

Certain arithmetic operations are permitted for declared integer variables without the need for expr or let.
n = 6 / 3 e c h o" n=$ n " d e c l a r ein n = 6 / 3 e c h o" n=$ n " #n=6 / 3

#n=2

-a a r r a y
d e c l a r eai n d i c e s

The variable i n d i c e swill be treated as an array. -f f u n c t i o n ( s )


d e c l a r ef

Ad e c l a r efline with no arguments in a script causes a listing of all the functions previously defined in that script.
d e c l a r eff u n c t i o n _ n a m e

Ad e c l a r eff u n c t i o n _ n a m ein a script lists just the function named. -x export


d e c l a r exv a r 3

This declares a variable as available for exporting outside the environment of the script itself. -x var=$value
d e c l a r exv a r 3 = 3 7 3

The declare command permits assigning a value to a variable in the same statement as setting its properties. Example 9-10. Using declare to type variables
# ! / b i n / b a s h f u n c 1( ) { e c h oT h i si saf u n c t i o n .

} d e c l a r ef e c h o d e c l a r eiv a r 1 #v a r 1i sa ni n t e g e r . v a r 1 = 2 3 6 7 e c h o" v a r 1d e c l a r e da s$ v a r 1 " v a r 1 = v a r 1 + 1 #I n t e g e rd e c l a r a t i o ne l i m i n a t e st h en e e df o r' l e t ' . e c h o" v a r 1i n c r e m e n t e db y1i s$ v a r 1 . " #A t t e m p tt oc h a n g ev a r i a b l ed e c l a r e da si n t e g e r . e c h o" A t t e m p t i n gt oc h a n g ev a r 1t of l o a t i n gp o i n tv a l u e ,2 3 6 7 . 1 . " v a r 1 = 2 3 6 7 . 1 #R e s u l t si ne r r o rm e s s a g e ,w i t hn oc h a n g et ov a r i a b l e . e c h o" v a r 1i ss t i l l$ v a r 1 " e c h o d e c l a r erv a r 2 = 1 3 . 3 6 #' d e c l a r e 'p e r m i t ss e t t i n gav a r i a b l ep r o p e r t y # +a n ds i m u l t a n e o u s l ya s s i g n i n gi tav a l u e . e c h o" v a r 2d e c l a r e da s$ v a r 2 "#A t t e m p tt oc h a n g er e a d o n l yv a r i a b l e . v a r 2 = 1 3 . 3 7 #G e n e r a t e se r r o rm e s s a g e ,a n de x i tf r o ms c r i p t . e c h o" v a r 2i ss t i l l$ v a r 2 " e x i t0 #T h i sl i n ew i l ln o te x e c u t e . #S c r i p tw i l ln o te x i th e r e . #L i s t st h ef u n c t i o na b o v e .

Using the declare builtin restricts the scope of a variable.


f o o( ) { F O O = " b a r " } b a r( ) { f o o e c h o$ F O O } b a r #P r i n t sb a r .

However . . .
f o o( ) { d e c l a r eF O O = " b a r " } b a r( ) { f o o e c h o$ F O O } b a r #P r i n t sn o t h i n g .

#T h a n ky o u ,M i c h a e lI a t r o u ,f o rp o i n t i n gt h i so u t .

9.2.1. Another use for declare


The declare command can be helpful in identifying variables, environmental or otherwise. This can be especially useful with arrays.
b a s h $d e c l a r e|g r e pH O M E

H O M E = / h o m e / b o z o

b a s h $z z y = 6 8 b a s h $d e c l a r e|g r e pz z y z z y = 6 8

b a s h $C o l o r s = ( [ 0 ] = " p u r p l e "[ 1 ] = " r e d d i s h o r a n g e "[ 2 ] = " l i g h tg r e e n " ) b a s h $e c h o$ { C o l o r s [ @ ] } p u r p l er e d d i s h o r a n g el i g h tg r e e n b a s h $d e c l a r e|g r e pC o l o r s C o l o r s = ( [ 0 ] = " p u r p l e "[ 1 ] = " r e d d i s h o r a n g e "[ 2 ] = " l i g h tg r e e n " )

9.3. $RANDOM: generate random integer


Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin. --John von Neumann
$ R A N D O Mis an internal Bash function (not a constant) that returns a pseudorandom

[47] integer in the range 0 - 32767. It

should n o tbe used to generate an encryption key. Example 9-11. Generating random numbers
# ! / b i n / b a s h #$ R A N D O Mr e t u r n sad i f f e r e n tr a n d o mi n t e g e ra te a c hi n v o c a t i o n . #N o m i n a lr a n g e :0-3 2 7 6 7( s i g n e d1 6 b i ti n t e g e r ) . M A X C O U N T = 1 0 c o u n t = 1 e c h o e c h o" $ M A X C O U N Tr a n d o mn u m b e r s : " e c h o" " w h i l e[" $ c o u n t "l e$ M A X C O U N T] #G e n e r a t e1 0( $ M A X C O U N T )r a n d o mi n t e g e r s . d o n u m b e r = $ R A N D O M e c h o$ n u m b e r l e t" c o u n t+ =1 " #I n c r e m e n tc o u n t . d o n e e c h o" " #I fy o un e e dar a n d o mi n tw i t h i nac e r t a i nr a n g e ,u s et h e' m o d u l o 'o p e r a t o r . #T h i sr e t u r n st h er e m a i n d e ro fad i v i s i o no p e r a t i o n . R A N G E = 5 0 0 e c h o n u m b e r = $ R A N D O M l e t" n u m b e r% =$ R A N G E " # ^ ^ e c h o" R a n d o mn u m b e rl e s st h a n$ R A N G E - $ n u m b e r " e c h o

# I fy o un e e dar a n d o mi n t e g e rg r e a t e rt h a nal o w e rb o u n d , # +t h e ns e tu pat e s tt od i s c a r da l ln u m b e r sb e l o wt h a t .

F L O O R = 2 0 0 n u m b e r = 0 # i n i t i a l i z e w h i l e[" $ n u m b e r "l e$ F L O O R] d o n u m b e r = $ R A N D O M d o n e e c h o" R a n d o mn u m b e rg r e a t e rt h a n$ F L O O R- $ n u m b e r " e c h o #L e t ' se x a m i n eas i m p l ea l t e r n a t i v et ot h ea b o v el o o p ,n a m e l y # l e t" n u m b e r=$ R A N D O M+$ F L O O R " #T h a tw o u l de l i m i n a t et h ew h i l e l o o pa n dr u nf a s t e r . #B u t ,t h e r em i g h tb eap r o b l e mw i t ht h a t .W h a ti si t ?

#C o m b i n ea b o v et w ot e c h n i q u e st or e t r i e v er a n d o mn u m b e rb e t w e e nt w ol i m i t s . n u m b e r = 0 # i n i t i a l i z e w h i l e[" $ n u m b e r "l e$ F L O O R] d o n u m b e r = $ R A N D O M l e t" n u m b e r% =$ R A N G E " #S c a l e s$ n u m b e rd o w nw i t h i n$ R A N G E . d o n e e c h o" R a n d o mn u m b e rb e t w e e n$ F L O O Ra n d$ R A N G E- $ n u m b e r " e c h o

#G e n e r a t eb i n a r yc h o i c e ,t h a ti s ," t r u e "o r" f a l s e "v a l u e . B I N A R Y = 2 T = 1 n u m b e r = $ R A N D O M l e t" n u m b e r% =$ B I N A R Y " # N o t et h a t l e t" n u m b e r> > =1 4 " g i v e sab e t t e rr a n d o md i s t r i b u t i o n # +( r i g h ts h i f t so u te v e r y t h i n ge x c e p tl a s tb i n a r yd i g i t ) . i f[" $ n u m b e r "e q$ T] t h e n e c h o" T R U E " e l s e e c h o" F A L S E " f i e c h o

#G e n e r a t eat o s so ft h ed i c e . S P O T S = 6 #M o d u l o6g i v e sr a n g e0-5 . #I n c r e m e n t i n gb y1g i v e sd e s i r e dr a n g eo f1-6 . #T h a n k s ,P a u l oM a r c e lC o e l h oA r a g a o ,f o rt h es i m p l i f i c a t i o n . d i e 1 = 0 d i e 2 = 0 #W o u l di tb eb e t t e rt oj u s ts e tS P O T S = 7a n dn o ta d d1 ?W h yo rw h yn o t ? #T o s s e se a c hd i es e p a r a t e l y ,a n ds og i v e sc o r r e c to d d s . l e t" d i e 1=$ R A N D O M%$ S P O T S+ 1 "#R o l lf i r s to n e . l e t" d i e 2=$ R A N D O M%$ S P O T S+ 1 "#R o l ls e c o n do n e . # W h i c ha r i t h m e t i co p e r a t i o n ,a b o v e ,h a sg r e a t e rp r e c e d e n c e# +m o d u l o( % )o ra d d i t i o n( + ) ?

l e t" t h r o w=$ d i e 1+$ d i e 2 " e c h o" T h r o wo ft h ed i c e=$ t h r o w " e c h o

e x i t0

Example 9-12. Picking a random card from a deck


# ! / b i n / b a s h #p i c k c a r d . s h #T h i si sa ne x a m p l eo fc h o o s i n gr a n d o me l e m e n t so fa na r r a y .

#P i c kac a r d ,a n yc a r d . S u i t e s = " C l u b s D i a m o n d s H e a r t s S p a d e s " D e n o m i n a t i o n s = " 2 3 4 5 6 7 8 9 1 0 J a c k Q u e e n K i n g A c e " #N o t ev a r i a b l e ss p r e a do v e rm u l t i p l el i n e s .

s u i t e = ( $ S u i t e s ) #R e a di n t oa r r a yv a r i a b l e . d e n o m i n a t i o n = ( $ D e n o m i n a t i o n s ) n u m _ s u i t e s = $ { # s u i t e [ * ] } #C o u n th o wm a n ye l e m e n t s . n u m _ d e n o m i n a t i o n s = $ { # d e n o m i n a t i o n [ * ] } e c h on" $ { d e n o m i n a t i o n [ $ ( ( R A N D O M % n u m _ d e n o m i n a t i o n s ) ) ] }o f" e c h o$ { s u i t e [ $ ( ( R A N D O M % n u m _ s u i t e s ) ) ] }

#$ b o z os hp i c k c a r d s . s h #J a c ko fC l u b s

#T h a n ky o u ," j i p e , "f o rp o i n t i n go u tt h i su s eo f$ R A N D O M . e x i t0

Example 9-13. Brownian Motion Simulation


# ! / b i n / b a s h #b r o w n i a n . s h #A u t h o r :M e n d e lC o o p e r #R e l d a t e :1 0 / 2 6 / 0 7 #L i c e n s e :G P L 3 # # T h i ss c r i p tm o d e l sB r o w n i a nm o t i o n : # +t h er a n d o mw a n d e r i n g so ft i n yp a r t i c l e si naf l u i d , # +a st h e ya r eb u f f e t e db yr a n d o mc u r r e n t sa n dc o l l i s i o n s . # +T h i si sc o l l o q u i a l l yk n o w na st h e" D r u n k a r d ' sW a l k . " # I tc a na l s ob ec o n s i d e r e da sas t r i p p e d d o w ns i m u l a t i o no fa # +G a l t o nB o a r d ,as l a n t e db o a r dw i t hap a t t e r no fp e g s , # +d o w nw h i c hr o l l sas u c c e s s i o no fm a r b l e s ,o n ea tat i m e .

# +A tt h eb o t t o mi sar o wo fs l o t so rc a t c hb a s i n si nw h i c h # +t h em a r b l e sc o m et or e s ta tt h ee n do ft h e i rj o u r n e y . # T h i n ko fi ta sak i n do fb a r e b o n e sP a c h i n k og a m e . # A sy o us e eb yr u n n i n gt h es c r i p t , # +m o s to ft h em a r b l e sc l u s t e ra r o u n dt h ec e n t e rs l o t . # +T h i si sc o n s i s t e n tw i t ht h ee x p e c t e db i n o m i a ld i s t r i b u t i o n . # A saG a l t o nB o a r ds i m u l a t i o n ,t h es c r i p t # +d i s r e g a r d ss u c hp a r a m e t e r sa s # +b o a r dt i l t a n g l e ,r o l l i n gf r i c t i o no ft h em a r b l e s , # +a n g l e so fi m p a c t ,a n de l a s t i c i t yo ft h ep e g s . # T ow h a te x t e n td o e st h i sa f f e c tt h ea c c u r a c yo ft h es i m u l a t i o n ? # P A S S E S = 5 0 0 R O W S = 1 0 R A N G E = 3 P O S = 0 R A N D O M = $ $ # N u m b e ro fp a r t i c l ei n t e r a c t i o n s/m a r b l e s . # N u m b e ro f" c o l l i s i o n s "( o rh o r i z .p e gr o w s ) . # 0-2o u t p u tr a n g ef r o m$ R A N D O M . # L e f t / r i g h tp o s i t i o n . # S e e d st h er a n d o mn u m b e rg e n e r a t o rf r o mP I D # +o fs c r i p t . #A r r a yh o l d i n gc u m u l a t i v er e s u l t so fp a s s e s . #N u m b e ro fs l o t sa tb o t t o mo fb o a r d .

d e c l a r eaS l o t s N U M S L O T S = 2 1

I n i t i a l i z e _ S l o t s( ){#Z e r oo u ta l le l e m e n t so ft h ea r r a y . f o rii n$ (s e q$ N U M S L O T S) d o S l o t s [ $ i ] = 0 d o n e e c h o } #B l a n kl i n ea tb e g i n n i n go fr u n .

S h o w _ S l o t s( ){ e c h o ;e c h o e c h on"" f o rii n$ (s e q$ N U M S L O T S) d o p r i n t f" % 3 d "$ { S l o t s [ $ i ] } d o n e

#P r e t t y p r i n ta r r a ye l e m e n t s . #A l l o tt h r e es p a c e sp e rr e s u l t .

e c h o#R o wo fs l o t s : e c h o"| _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | _ _ | " e c h o" | | " e c h o# N o t et h a ti ft h ec o u n tw i t h i na n yp a r t i c u l a rs l o te x c e e d s9 9 , # +i tm e s s e su pt h ed i s p l a y . # R u n n i n go n l y ( ! )5 0 0p a s s e su s u a l l ya v o i d st h i s . }

M o v e( ){ #M o v eo n eu n i tr i g h t/l e f t ,o rs t a yp u t . M o v e = $ R A N D O M #H o wr a n d o mi s$ R A N D O M ?W e l l ,l e t ' ss e e. . . l e t" M o v e% =R A N G E " #N o r m a l i z ei n t or a n g eo f0-2 . c a s e" $ M o v e "i n 0); ; #D on o t h i n g ,i . e . ,s t a yi np l a c e . 1)( ( P O S ) ) ; ; #L e f t . 2)( ( P O S + + ) ) ; ; #R i g h t . *)e c h on" E r r o r" ; ; #A n o m a l y !( S h o u l dn e v e ro c c u r . ) e s a c }

P l a y( ){ i = 0 w h i l e[" $ i "l t" $ R O W S "] d o M o v e ( ( i + + ) ) ;

#S i n g l ep a s s( i n n e rl o o p ) . #O n ee v e n tp e rr o w .

d o n e S H I F T = 1 1 l e t" P O S+ =$ S H I F T " ( (S l o t s [ $ P O S ] + +) ) #e c h on" $ P O S" } #W h y1 1 ,a n dn o t1 0 ? #S h i f t" z e r op o s i t i o n "t oc e n t e r . #D E B U G :e c h o$ P O S

R u n( ){ #O u t e rl o o p . p = 0 w h i l e[" $ p "l t" $ P A S S E S "] d o P l a y ( (p + +) ) P O S = 0 #R e s e tt oz e r o .W h y ? d o n e }

##m a i n( ) I n i t i a l i z e _ S l o t s R u n S h o w _ S l o t s #e x i t$ ? # E x e r c i s e s : # # 1 )S h o wt h er e s u l t si nav e r t i c a lb a rg r a p h ,o ra sa na l t e r n a t i v e , # + as c a t t e r g r a m . # 2 )A l t e rt h es c r i p tt ou s e/ d e v / u r a n d o mi n s t e a do f$ R A N D O M . # W i l lt h i sm a k et h er e s u l t sm o r er a n d o m ? # 3 )P r o v i d es o m es o r to f" a n i m a t i o n "o rg r a p h i co u t p u t # f o re a c hm a r b l ep l a y e d .

Jipe points out a set of techniques for generating random numbers within a range.
# G e n e r a t er a n d o mn u m b e rb e t w e e n6a n d3 0 . r n u m b e r = $ ( ( R A N D O M % 2 5 + 6 ) ) # G e n e r a t er a n d o mn u m b e ri nt h es a m e6-3 0r a n g e , # +b u tt h en u m b e rm u s tb ee v e n l yd i v i s i b l eb y3 . r n u m b e r = $ ( ( ( R A N D O M % 3 0 / 3 + 1 ) * 3 ) ) # N o t et h a tt h i sw i l ln o tw o r ka l lt h et i m e . # I tf a i l si f$ R A N D O M % 3 0r e t u r n s0 . # F r a n kW a n gs u g g e s t st h ef o l l o w i n ga l t e r n a t i v e : r n u m b e r = $ ( (R A N D O M % 2 7 / 3 * 3 + 6) )

Bill Gradwohl came up with an improved formula that works for positive numbers.
r n u m b e r = $ ( ( ( R A N D O M % ( m a x m i n + d i v i s i b l e B y ) ) / d i v i s i b l e B y * d i v i s i b l e B y + m i n ) )

Here Bill presents a versatile function that returns a random number between two specified values. Example 9-14. Random between values
# ! / b i n / b a s h #r a n d o m b e t w e e n . s h #R a n d o mn u m b e rb e t w e e nt w os p e c i f i e dv a l u e s . #S c r i p tb yB i l lG r a d w o h l ,w i t hm i n o rm o d i f i c a t i o n sb yt h ed o c u m e n ta u t h o r . #C o r r e c t i o n si nl i n e s1 8 7a n d1 8 9b yA n t h o n yL eC l e z i o . #U s e dw i t hp e r m i s s i o n .

r a n d o m B e t w e e n ( ){ # G e n e r a t e sap o s i t i v eo rn e g a t i v er a n d o mn u m b e r # +b e t w e e n$ m i na n d$ m a x # +a n dd i v i s i b l eb y$ d i v i s i b l e B y . # G i v e sa" r e a s o n a b l yr a n d o m "d i s t r i b u t i o no fr e t u r nv a l u e s . # # B i l lG r a d w o h l-O c t1 ,2 0 0 3 s y n t a x ( ){ #F u n c t i o ne m b e d d e dw i t h i nf u n c t i o n . e c h o e c h o " S y n t a x :r a n d o m B e t w e e n[ m i n ][ m a x ][ m u l t i p l e ] " e c h o e c h on" E x p e c t su pt o3p a s s e dp a r a m e t e r s ," e c h o " b u ta l la r ec o m p l e t e l yo p t i o n a l . " e c h o " m i ni st h em i n i m u mv a l u e " e c h o " m a xi st h em a x i m u mv a l u e " e c h on" m u l t i p l es p e c i f i e st h a tt h ea n s w e rm u s tb e" e c h o " am u l t i p l eo ft h i sv a l u e . " e c h o " i . e .a n s w e rm u s tb ee v e n l yd i v i s i b l eb yt h i sn u m b e r . " e c h o e c h o " I fa n yv a l u ei sm i s s i n g ,d e f a u l t sa r e as u p p l i e da s :03 2 7 6 71 " e c h on" S u c c e s s f u lc o m p l e t i o nr e t u r n s0 ," e c h o " u n s u c c e s s f u lc o m p l e t i o nr e t u r n s " e c h o " f u n c t i o ns y n t a xa n d1 . " e c h on" T h ea n s w e ri sr e t u r n e di nt h eg l o b a lv a r i a b l e" e c h o " r a n d o m B e t w e e n A n s w e r " e c h on" N e g a t i v ev a l u e sf o ra n yp a s s e dp a r a m e t e ra r e" e c h o " h a n d l e dc o r r e c t l y . " } l o c a lm i n = $ { 1 : 0 } l o c a lm a x = $ { 2 : 3 2 7 6 7 } l o c a ld i v i s i b l e B y = $ { 3 : 1 } #D e f a u l tv a l u e sa s s i g n e d ,i nc a s ep a r a m e t e r sn o tp a s s e dt of u n c t i o n . l o c a lx l o c a ls p r e a d #L e t ' sm a k es u r et h ed i v i s i b l e B yv a l u ei sp o s i t i v e . [$ { d i v i s i b l e B y }l t0]& &d i v i s i b l e B y = $ ( ( 0 d i v i s i b l e B y ) ) #S a n i t yc h e c k . i f[$ #g t3o$ { d i v i s i b l e B y }e q0o $ { m i n }e q$ { m a x }] ;t h e n s y n t a x r e t u r n1 f i #S e ei ft h em i na n dm a xa r er e v e r s e d . i f[$ { m i n }g t$ { m a x }] ;t h e n #S w a pt h e m . x = $ { m i n } m i n = $ { m a x } m a x = $ { x } f i # I fm i ni si t s e l fn o te v e n l yd i v i s i b l eb y$ d i v i s i b l e B y , # +t h e nf i xt h em i nt ob ew i t h i nr a n g e . i f[$ ( ( m i n / d i v i s i b l e B y * d i v i s i b l e B y ) )n e$ { m i n }] ;t h e n i f[$ { m i n }l t0] ;t h e n m i n = $ ( ( m i n / d i v i s i b l e B y * d i v i s i b l e B y ) ) e l s e m i n = $ ( ( ( ( m i n / d i v i s i b l e B y ) + 1 ) * d i v i s i b l e B y ) ) f i f i # I fm a xi si t s e l fn o te v e n l yd i v i s i b l eb y$ d i v i s i b l e B y ,

# +t h e nf i xt h em a xt ob ew i t h i nr a n g e . i f[$ ( ( m a x / d i v i s i b l e B y * d i v i s i b l e B y ) )n e$ { m a x }] ;t h e n i f[$ { m a x }l t0] ;t h e n m a x = $ ( ( ( ( m a x / d i v i s i b l e B y ) 1 ) * d i v i s i b l e B y ) ) e l s e m a x = $ ( ( m a x / d i v i s i b l e B y * d i v i s i b l e B y ) ) f i f i # # N o w ,t od ot h er e a lw o r k . # N o t et h a tt og e tap r o p e rd i s t r i b u t i o nf o rt h ee n dp o i n t s , # +t h er a n g eo fr a n d o mv a l u e sh a st ob ea l l o w e dt og ob e t w e e n # +0a n da b s ( m a x m i n ) + d i v i s i b l e B y ,n o tj u s ta b s ( m a x m i n ) + 1 . # T h es l i g h ti n c r e a s ew i l lp r o d u c et h ep r o p e rd i s t r i b u t i o nf o rt h e # +e n dp o i n t s . # C h a n g i n gt h ef o r m u l at ou s ea b s ( m a x m i n ) + 1w i l ls t i l lp r o d u c e # +c o r r e c ta n s w e r s ,b u tt h er a n d o m n e s so ft h o s ea n s w e r si sf a u l t yi n # +t h a tt h en u m b e ro ft i m e st h ee n dp o i n t s( $ m i na n d$ m a x )a r er e t u r n e d # +i sc o n s i d e r a b l yl o w e rt h a nw h e nt h ec o r r e c tf o r m u l ai su s e d . # s p r e a d = $ ( ( m a x m i n ) ) # O m a i rE s h k e n a z ip o i n t so u tt h a tt h i st e s ti su n n e c e s s a r y , # +s i n c em a xa n dm i nh a v ea l r e a d yb e e ns w i t c h e da r o u n d . [$ { s p r e a d }l t0]& &s p r e a d = $ ( ( 0 s p r e a d ) ) l e ts p r e a d + = d i v i s i b l e B y r a n d o m B e t w e e n A n s w e r = $ ( ( ( R A N D O M % s p r e a d ) / d i v i s i b l e B y * d i v i s i b l e B y + m i n ) ) r e t u r n0 # H o w e v e r ,P a u l oM a r c e lC o e l h oA r a g a op o i n t so u tt h a t # +w h e n$ m a xa n d$ m i na r en o td i v i s i b l eb y$ d i v i s i b l e B y , # +t h ef o r m u l af a i l s . # # H es u g g e s t si n s t e a dt h ef o l l o w i n gf o r m u l a : # r n u m b e r=$ ( ( ( R A N D O M % ( m a x m i n + 1 ) + m i n ) / d i v i s i b l e B y * d i v i s i b l e B y ) ) } #L e t ' st e s tt h ef u n c t i o n . m i n = 1 4 m a x = 2 0 d i v i s i b l e B y = 3

# G e n e r a t ea na r r a yo fe x p e c t e da n s w e r sa n dc h e c kt om a k es u r ew eg e t # +a tl e a s to n eo fe a c ha n s w e ri fw el o o pl o n ge n o u g h . d e c l a r eaa n s w e r m i n i m u m = $ { m i n } m a x i m u m = $ { m a x } i f[$ ( ( m i n i m u m / d i v i s i b l e B y * d i v i s i b l e B y ) )n e$ { m i n i m u m }] ;t h e n i f[$ { m i n i m u m }l t0] ;t h e n m i n i m u m = $ ( ( m i n i m u m / d i v i s i b l e B y * d i v i s i b l e B y ) ) e l s e m i n i m u m = $ ( ( ( ( m i n i m u m / d i v i s i b l e B y ) + 1 ) * d i v i s i b l e B y ) ) f i f i

# I fm a xi si t s e l fn o te v e n l yd i v i s i b l eb y$ d i v i s i b l e B y , # +t h e nf i xt h em a xt ob ew i t h i nr a n g e . i f[$ ( ( m a x i m u m / d i v i s i b l e B y * d i v i s i b l e B y ) )n e$ { m a x i m u m }] ;t h e n i f[$ { m a x i m u m }l t0] ;t h e n

m a x i m u m = $ ( ( ( ( m a x i m u m / d i v i s i b l e B y ) 1 ) * d i v i s i b l e B y ) ) e l s e m a x i m u m = $ ( ( m a x i m u m / d i v i s i b l e B y * d i v i s i b l e B y ) ) f i f i

# W en e e dt og e n e r a t eo n l yp o s i t i v ea r r a ys u b s c r i p t s , # +s ow en e e dad i s p l a c e m e n tt h a tt h a tw i l lg u a r a n t e e # +p o s i t i v er e s u l t s . d i s p = $ ( ( 0 m i n i m u m ) ) f o r( ( i = $ { m i n i m u m } ;i < = $ { m a x i m u m } ;i + = d i v i s i b l e B y ) ) ;d o a n s w e r [ i + d i s p ] = 0 d o n e

#N o wl o o pal a r g en u m b e ro ft i m e st os e ew h a tw eg e t . l o o p I t = 1 0 0 0 # T h es c r i p ta u t h o rs u g g e s t s1 0 0 0 0 0 , # +b u tt h a tt a k e sag o o dl o n gw h i l e . f o r( ( i = 0 ;i < $ { l o o p I t } ;+ + i ) ) ;d o # N o t et h a tw ea r es p e c i f y i n gm i na n dm a xi nr e v e r s e do r d e rh e r et o # +m a k et h ef u n c t i o nc o r r e c tf o rt h i sc a s e . r a n d o m B e t w e e n$ { m a x }$ { m i n }$ { d i v i s i b l e B y } #R e p o r ta ne r r o ri fa na n s w e ri su n e x p e c t e d . [$ { r a n d o m B e t w e e n A n s w e r }l t$ { m i n }o$ { r a n d o m B e t w e e n A n s w e r }g t$ { m a x }]\ & &e c h oM I No rM A Xe r r o r-$ { r a n d o m B e t w e e n A n s w e r } ! [$ ( ( r a n d o m B e t w e e n A n s w e r % $ { d i v i s i b l e B y } ) )n e0]\ & &e c h oD I V I S I B L EB Ye r r o r-$ { r a n d o m B e t w e e n A n s w e r } ! #S t o r et h ea n s w e ra w a ys t a t i s t i c a l l y . a n s w e r [ r a n d o m B e t w e e n A n s w e r + d i s p ] = $ ( ( a n s w e r [ r a n d o m B e t w e e n A n s w e r + d i s p ] + 1 ) ) d o n e

#L e t ' sc h e c kt h er e s u l t s f o r( ( i = $ { m i n i m u m } ;i < = $ { m a x i m u m } ;i + = d i v i s i b l e B y ) ) ;d o [$ { a n s w e r [ i + d i s p ] }e q0]\ & &e c h o" W en e v e rg o ta na n s w e ro f$ i . "\ | |e c h o" $ { i }o c c u r r e d$ { a n s w e r [ i + d i s p ] }t i m e s . " d o n e

e x i t0

Just how random is $ R A N D O M ? The best way to test this is to write a script that tracks the distribution of "random" numbers generated by $ R A N D O M . Let's roll a $ R A N D O Mdie a few times . . . Example 9-15. Rolling a single die with RANDOM
# ! / b i n / b a s h #H o wr a n d o mi sR A N D O M ? R A N D O M = $ $ P I P S = 6 M A X T H R O W S = 6 0 0 t h r o w = 0 o n e s = 0 t w o s = 0 t h r e e s = 0 #R e s e e dt h er a n d o mn u m b e rg e n e r a t o ru s i n gs c r i p tp r o c e s sI D . #Ad i eh a s6p i p s . #I n c r e a s et h i si fy o uh a v en o t h i n gb e t t e rt od ow i t hy o u rt i m e . #N u m b e ro ft i m e st h ed i c eh a v eb e e nc a s t . # M u s ti n i t i a l i z ec o u n t st oz e r o , # +s i n c ea nu n i n i t i a l i z e dv a r i a b l ei sn u l l ,N O Tz e r o .

f o u r s = 0 f i v e s = 0 s i x e s = 0 p r i n t _ r e s u l t( ) { e c h o e c h o" o n e s= $ o n e s " e c h o" t w o s= $ t w o s " e c h o" t h r e e s=$ t h r e e s " e c h o" f o u r s= $ f o u r s " e c h o" f i v e s= $ f i v e s " e c h o" s i x e s= $ s i x e s " e c h o } u p d a t e _ c o u n t ( ) { c a s e" $ 1 "i n 0 )( ( o n e s + + ) ) ; ; #S i n c ead i eh a sn o" z e r o " ,t h i sc o r r e s p o n d st o1 . 1 )( ( t w o s + + ) ) ; ; #A n dt h i st o2 . 2 )( ( t h r e e s + + ) ) ; ;#A n ds of o r t h . 3 )( ( f o u r s + + ) ) ; ; 4 )( ( f i v e s + + ) ) ; ; 5 )( ( s i x e s + + ) ) ; ; e s a c } e c h o

w h i l e[" $ t h r o w "l t" $ M A X T H R O W S "] d o l e t" d i e 1=R A N D O M%$ P I P S " u p d a t e _ c o u n t$ d i e 1 l e t" t h r o w+ =1 " d o n e p r i n t _ r e s u l t e x i t$ ? # T h es c o r e ss h o u l dd i s t r i b u t ee v e n l y ,a s s u m i n gR A N D O Mi sr a n d o m . # W i t h$ M A X T H R O W Sa t6 0 0 ,a l ls h o u l dc l u s t e ra r o u n d1 0 0 , # +p l u s o r m i n u s2 0o rs o . # # K e e pi nm i n dt h a tR A N D O Mi sa* * * p s e u d o r a n d o m * * *g e n e r a t o r , # +a n dn o tas p e c t a c u l a r l yg o o do n ea tt h a t . # R a n d o m n e s si sad e e pa n dc o m p l e xs u b j e c t . # S u f f i c i e n t l yl o n g" r a n d o m "s e q u e n c e sm a ye x h i b i t # +c h a o t i ca n do t h e r" n o n r a n d o m "b e h a v i o r . #E x e r c i s e( e a s y ) : ##R e w r i t et h i ss c r i p tt of l i pac o i n1 0 0 0t i m e s . #C h o i c e sa r e" H E A D S "a n d" T A I L S . "

As we have seen in the last example, it is best to reseed the R A N D O Mgenerator each time it is invoked. Using the same seed for R A N D O Mrepeats the same series of numbers. [48] (This mirrors the behavior of the r a n d o m ( )function in C.) Example 9-16. Reseeding RANDOM
# ! / b i n / b a s h #s e e d i n g r a n d o m . s h :S e e d i n gt h eR A N D O Mv a r i a b l e . M A X C O U N T = 2 5 #H o wm a n yn u m b e r st og e n e r a t e .

r a n d o m _ n u m b e r s( ) { c o u n t = 0 w h i l e[" $ c o u n t "l t" $ M A X C O U N T "] d o n u m b e r = $ R A N D O M e c h on" $ n u m b e r" l e t" c o u n t+ =1 " d o n e } e c h o ;e c h o R A N D O M = 1 r a n d o m _ n u m b e r s #S e t t i n gR A N D O Ms e e d st h er a n d o mn u m b e rg e n e r a t o r .

e c h o ;e c h o" T r y i n ga g a i nw i t hs a m er a n d o ms e e d. . . " R A N D O M = 1 r a n d o m _ n u m b e r s #S a m es e e df o rR A N D O M... #...r e p r o d u c e st h ee x a c ts a m en u m b e rs e r i e s . # #W h e ni si tu s e f u lt od u p l i c a t ea" r a n d o m "s e r i e s ?

e c h o ;e c h o R A N D O M = 2 r a n d o m _ n u m b e r s e c h o ;e c h o #R A N D O M = $ $ s e e d sR A N D O Mf r o mp r o c e s si do fs c r i p t . #I ti sa l s op o s s i b l et os e e dR A N D O Mf r o m' t i m e 'o r' d a t e 'c o m m a n d s . #G e t t i n gf a n c y . . . S E E D = $ ( h e a d1/ d e v / u r a n d o m|o dN1|a w k' {p r i n t$ 2} ' ) # P s e u d o r a n d o mo u t p u tf e t c h e d # +f r o m/ d e v / u r a n d o m( s y s t e mp s e u d o r a n d o md e v i c e f i l e ) , # +t h e nc o n v e r t e dt ol i n eo fp r i n t a b l e( o c t a l )n u m b e r sb y" o d " , # +f i n a l l y" a w k "r e t r i e v e sj u s to n en u m b e rf o rS E E D . R A N D O M = $ S E E D r a n d o m _ n u m b e r s e c h o ;e c h o e x i t0 #T r y i n ga g a i n ,b u tw i t had i f f e r e n ts e e d... #...g i v e sad i f f e r e n tn u m b e rs e r i e s .

The / d e v / u r a n d o mpseudo-device file provides a method of generating much more "random" pseudorandom numbers than the $ R A N D O Mvariable. d di f = / d e v / u r a n d o mo f = t a r g e t f i l eb s = 1c o u n t = X Xcreates a file of well-scattered pseudorandom numbers. However, assigning these numbers to a variable in a script requires a workaround, such as filtering through od (as in above example, Example 16-14, and Example A-36), or even piping to md5sum (see Example 36-14). There are also other ways to generate pseudorandom numbers in a script. Awk provides a convenient means of doing this. Example 9-17. Pseudorandom numbers, using awk
# ! / b i n / b a s h # r a n d o m 2 . s h :R e t u r n sap s e u d o r a n d o mn u m b e ri nt h er a n g e0-1 , # +t o6d e c i m a lp l a c e s .F o re x a m p l e :0 . 8 2 2 7 2 5 # U s e st h ea w kr a n d ( )f u n c t i o n . A W K S C R I P T = '{s r a n d ( ) ;p r i n tr a n d ( )}' # C o m m a n d ( s ) / p a r a m e t e r sp a s s e dt oa w k #N o t et h a ts r a n d ( )r e s e e d sa w k ' sr a n d o mn u m b e rg e n e r a t o r .

e c h on" R a n d o mn u m b e rb e t w e e n0a n d1=" e c h o|a w k" $ A W K S C R I P T " #W h a th a p p e n si fy o ul e a v eo u tt h e' e c h o ' ? e x i t0

#E x e r c i s e s : ##1 )U s i n gal o o pc o n s t r u c t ,p r i n to u t1 0d i f f e r e n tr a n d o mn u m b e r s . # ( H i n t :y o um u s tr e s e e dt h es r a n d ( )f u n c t i o nw i t had i f f e r e n ts e e d # + i ne a c hp a s st h r o u g ht h el o o p .W h a th a p p e n si fy o uo m i tt h i s ? ) #2 )U s i n ga ni n t e g e rm u l t i p l i e ra sas c a l i n gf a c t o r ,g e n e r a t er a n d o mn u m b e r s # + i nt h er a n g eo f1 0t o1 0 0 . #3 )S a m ea se x e r c i s e# 2 ,a b o v e ,b u tg e n e r a t er a n d o mi n t e g e r st h i st i m e .

The date command also lends itself to generating pseudorandom integer sequences.

Chapter 10. Manipulating Variables 10.1. Manipulating Strings


Bash supports a surprising number of string manipulation operations. Unfortunately, these tools lack a unified focus. Some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr command. This results in inconsistent command syntax and overlap of functionality, not to mention confusion. String Length ${#string} expr length $string These are the equivalent of strlen() in C. expr "$string" : '.*'
s t r i n g Z = a b c A B C 1 2 3 A B C a b c e c h o$ { # s t r i n g Z } e c h o` e x p rl e n g t h$ s t r i n g Z ` e c h o` e x p r" $ s t r i n g Z ":' . * ' ` #1 5 #1 5 #1 5

Example 10-1. Inserting a blank line between paragraphs in a text file


# ! / b i n / b a s h #p a r a g r a p h s p a c e . s h #V e r .2 . 1 ,R e l d a t e2 9 J u l 1 2[ f i x u p ] #I n s e r t sab l a n kl i n eb e t w e e np a r a g r a p h so fas i n g l e s p a c e dt e x tf i l e . #U s a g e :$ 0< F I L E N A M E M I N L E N = 6 0 #C h a n g et h i sv a l u e ?I t ' saj u d g m e n tc a l l . # A s s u m el i n e ss h o r t e rt h a n$ M I N L E Nc h a r a c t e r se n d i n gi nap e r i o d # +t e r m i n a t eap a r a g r a p h .S e ee x e r c i s e sb e l o w . w h i l er e a dl i n e #F o ra sm a n yl i n e sa st h ei n p u tf i l eh a s. . .

d o e c h o" $ l i n e "

#O u t p u tt h el i n ei t s e l f .

l e n = $ { # l i n e } i f[ [" $ l e n "l t" $ M I N L E N "& &" $ l i n e "= ~[ * { \ . } ] $] ] #i f[ [" $ l e n "l t" $ M I N L E N "& &" $ l i n e "= ~\ [ * \ . \ ]] ] #A nu p d a t et oB a s hb r o k et h ep r e v i o u sv e r s i o no ft h i ss c r i p t .O u c h ! #T h a n ky o u ,H a l i mS r a m a ,f o rp o i n t i n gt h i so u ta n ds u g g e s t i n gaf i x . t h e ne c h o # A d dab l a n kl i n ei m m e d i a t e l y f i # +a f t e ras h o r tl i n et e r m i n a t e db yap e r i o d . d o n e e x i t #E x e r c i s e s : ## 1 )T h es c r i p tu s u a l l yi n s e r t sab l a n kl i n ea tt h ee n d # + o ft h et a r g e tf i l e .F i xt h i s . # 2 )L i n e1 7o n l yc o n s i d e r sp e r i o d sa ss e n t e n c et e r m i n a t o r s . # M o d i f yt h i st oi n c l u d eo t h e rc o m m o ne n d o f s e n t e n c ec h a r a c t e r s , # + s u c ha s? ,! ,a n d" .

Length of Matching Substring at Beginning of String expr match "$string" '$substring'


$ s u b s t r i n gis a regular expression.

expr "$string" : '$substring'


$ s u b s t r i n gis a regular expression. s t r i n g Z = a b c A B C 1 2 3 A B C a b c # | | # 1 2 3 4 5 6 7 8 e c h o` e x p rm a t c h" $ s t r i n g Z "' a b c [ A Z ] * . 2 ' ` e c h o` e x p r" $ s t r i n g Z ":' a b c [ A Z ] * . 2 ' ` #8 #8

Index expr index $string $substring Numerical position in $string of first character in $substring that matches.
s t r i n g Z = a b c A B C 1 2 3 A B C a b c # 1 2 3 4 5 6. . . e c h o` e x p ri n d e x" $ s t r i n g Z "C 1 2 `

#6 #Cp o s i t i o n . #3

e c h o` e x p ri n d e x" $ s t r i n g Z "1 c ` #' c '( i n# 3p o s i t i o n )m a t c h e sb e f o r e' 1 ' .

This is the near equivalent of strchr() in C. Substring Extraction ${string:position} Extracts substring from $ s t r i n gat $ p o s i t i o n . If the $ s t r i n gparameter is "*" or "@", then this extracts the positional parameters, [49] starting at $ p o s i t i o n . ${string:position:length}

Extracts $ l e n g t hcharacters of substring from $ s t r i n gat $ p o s i t i o n .


s t r i n g Z = a b c A B C 1 2 3 A B C a b c # 0 1 2 3 4 5 6 7 8 9 . . . . . # 0 b a s e di n d e x i n g . e c h o$ { s t r i n g Z : 0 } e c h o$ { s t r i n g Z : 1 } e c h o$ { s t r i n g Z : 7 } e c h o$ { s t r i n g Z : 7 : 3 } #a b c A B C 1 2 3 A B C a b c #b c A B C 1 2 3 A B C a b c #2 3 A B C a b c #2 3 A #T h r e ec h a r a c t e r so fs u b s t r i n g .

#I si tp o s s i b l et oi n d e xf r o mt h er i g h te n do ft h es t r i n g ? e c h o$ { s t r i n g Z : 4 } #a b c A B C 1 2 3 A B C a b c #D e f a u l t st of u l ls t r i n g ,a si n$ { p a r a m e t e r : d e f a u l t } . #H o w e v e r... e c h o$ { s t r i n g Z : ( 4 ) } #C a b c e c h o$ { s t r i n g Z :4 } #C a b c #N o w ,i tw o r k s . #P a r e n t h e s e so ra d d e ds p a c e" e s c a p e "t h ep o s i t i o np a r a m e t e r . #T h a n ky o u ,D a nJ a c o b s o n ,f o rp o i n t i n gt h i so u t .

The position and length arguments can be "parameterized," that is, represented as a variable, rather than as a numerical constant. Example 10-2. Generating an 8-character "random" string
# ! / b i n / b a s h #r a n d s t r i n g . s h #G e n e r a t i n ga n8 c h a r a c t e r" r a n d o m "s t r i n g . i f[n" $ 1 "] # I fc o m m a n d l i n ea r g u m e n tp r e s e n t , t h e n # +t h e ns e ts t a r t s t r i n gt oi t . s t r 0 = " $ 1 " e l s e # E l s eu s eP I Do fs c r i p ta ss t a r t s t r i n g . s t r 0 = " $ $ " f i P O S = 2 #S t a r t i n gf r o mp o s i t i o n2i nt h es t r i n g . L E N = 8 #E x t r a c te i g h tc h a r a c t e r s . s t r 1 = $ (e c h o" $ s t r 0 "|m d 5 s u m|m d 5 s u m) # D o u b l ys c r a m b l e ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # +b yp i p i n ga n dr e p i p i n gt om d 5 s u m . r a n d s t r i n g = " $ { s t r 1 : $ P O S : $ L E N } " #C a np a r a m e t e r i z e^ ^ ^ ^^ ^ ^ ^ e c h o" $ r a n d s t r i n g " e x i t$ ? #b o z o $. / r a n d s t r i n g . s hm y p a s s w o r d #1 b d d 8 8 c 4 # N o ,t h i si si sn o tr e c o m m e n d e d # +a sam e t h o do fg e n e r a t i n gh a c k p r o o fp a s s w o r d s .

If the $ s t r i n gparameter is "*" or "@", then this extracts a maximum of $ l e n g t hpositional parameters, starting at $ p o s i t i o n .

e c h o$ { * : 2 } e c h o$ { @ : 2 } e c h o$ { * : 2 : 3 }

#E c h o e ss e c o n da n df o l l o w i n gp o s i t i o n a lp a r a m e t e r s . #S a m ea sa b o v e . #E c h o e st h r e ep o s i t i o n a lp a r a m e t e r s ,s t a r t i n ga ts e c o n d .

expr substr $string $position $length Extracts $ l e n g t hcharacters from $ s t r i n gstarting at $ p o s i t i o n .


s t r i n g Z = a b c A B C 1 2 3 A B C a b c # 1 2 3 4 5 6 7 8 9 . . . . . . # 1 b a s e di n d e x i n g . e c h o` e x p rs u b s t r$ s t r i n g Z12 ` e c h o` e x p rs u b s t r$ s t r i n g Z43 ` #a b #A B C

expr match "$string" '\($substring\)' Extracts $ s u b s t r i n gat beginning of $ s t r i n g , where $ s u b s t r i n gis a regular expression. expr "$string" : '\($substring\)' Extracts $ s u b s t r i n gat beginning of $ s t r i n g , where $ s u b s t r i n gis a regular expression.
s t r i n g Z = a b c A B C 1 2 3 A B C a b c # = = = = = = = e c h o` e x p rm a t c h" $ s t r i n g Z "' \ ( . [ b c ] * [ A Z ] . . [ 0 9 ] \ ) ' ` e c h o` e x p r" $ s t r i n g Z ":' \ ( . [ b c ] * [ A Z ] . . [ 0 9 ] \ ) ' ` e c h o` e x p r" $ s t r i n g Z ":' \ ( . . . . . . . \ ) ' ` #A l lo ft h ea b o v ef o r m sg i v ea ni d e n t i c a lr e s u l t . #a b c A B C 1 #a b c A B C 1 #a b c A B C 1

expr match "$string" '.*\($substring\)' Extracts $ s u b s t r i n gat end of $ s t r i n g , where $ s u b s t r i n gis a regular expression. expr "$string" : '.*\($substring\)' Extracts $ s u b s t r i n gat end of $ s t r i n g , where $ s u b s t r i n gis a regular expression.
s t r i n g Z = a b c A B C 1 2 3 A B C a b c # = = = = = = e c h o` e x p rm a t c h" $ s t r i n g Z "' . * \ ( [ A C ] [ A C ] [ A C ] [ a c ] * \ ) ' ` e c h o` e x p r" $ s t r i n g Z ":' . * \ ( . . . . . . \ ) ' ` #A B C a b c #A B C a b c

Substring Removal ${string#substring} Deletes shortest match of $ s u b s t r i n gfrom front of $ s t r i n g . ${string##substring} Deletes longest match of $ s u b s t r i n gfrom front of $ s t r i n g .
s t r i n g Z = a b c A B C 1 2 3 A B C a b c # | | s h o r t e s t # | | l o n g e s t e c h o$ { s t r i n g Z # a * C } #1 2 3 A B C a b c #S t r i po u ts h o r t e s tm a t c hb e t w e e n' a 'a n d' C ' . e c h o$ { s t r i n g Z # # a * C } #a b c

#S t r i po u tl o n g e s tm a t c hb e t w e e n' a 'a n d' C ' .

#Y o uc a np a r a m e t e r i z et h es u b s t r i n g s . X = ' a * C ' e c h o$ { s t r i n g Z # $ X } e c h o$ { s t r i n g Z # # $ X } #1 2 3 A B C a b c #a b c #A sa b o v e .

${string%substring} Deletes shortest match of $ s u b s t r i n gfrom back of $ s t r i n g . For example:


#R e n a m ea l lf i l e n a m e si n$ P W Dw i t h" T X T "s u f f i xt oa" t x t "s u f f i x . #F o re x a m p l e ," f i l e 1 . T X T "b e c o m e s" f i l e 1 . t x t "... S U F F = T X T s u f f = t x t f o rii n$ ( l s* . $ S U F F ) d o m vf$ i$ { i % . $ S U F F } . $ s u f f # L e a v eu n c h a n g e de v e r y t h i n g* e x c e p t *t h es h o r t e s tp a t t e r nm a t c h # +s t a r t i n gf r o mt h er i g h t h a n d s i d eo ft h ev a r i a b l e$ i... d o n e# # #T h i sc o u l db ec o n d e n s e di n t oa" o n e l i n e r "i fd e s i r e d . #T h a n ky o u ,R o r yW i n s t o n .

${string%%substring} Deletes longest match of $ s u b s t r i n gfrom back of $ s t r i n g .


s t r i n g Z = a b c A B C 1 2 3 A B C a b c # | | # | | s h o r t e s t l o n g e s t

e c h o$ { s t r i n g Z % b * c } #a b c A B C 1 2 3 A B C a #S t r i po u ts h o r t e s tm a t c hb e t w e e n' b 'a n d' c ' ,f r o mb a c ko f$ s t r i n g Z . e c h o$ { s t r i n g Z % % b * c } #a #S t r i po u tl o n g e s tm a t c hb e t w e e n' b 'a n d' c ' ,f r o mb a c ko f$ s t r i n g Z .

This operator is useful for generating filenames. Example 10-3. Converting graphic file formats, with filename change
# ! / b i n / b a s h # c v t . s h : # C o n v e r t sa l lt h eM a c P a i n ti m a g ef i l e si nad i r e c t o r yt o" p b m "f o r m a t . # U s e st h e" m a c p t o p b m "b i n a r yf r o mt h e" n e t p b m "p a c k a g e , # +w h i c hi sm a i n t a i n e db yB r i a nH e n d e r s o n( b r y a n h @ g i r a f f e d a t a . c o m ) . # N e t p b mi sas t a n d a r dp a r to fm o s tL i n u xd i s t r o s . O P E R A T I O N = m a c p t o p b m S U F F I X = p b m #N e wf i l e n a m es u f f i x . i f[n" $ 1 "] t h e n d i r e c t o r y = $ 1 e l s e d i r e c t o r y = $ P W D

#I fd i r e c t o r yn a m eg i v e na sas c r i p ta r g u m e n t . . . #O t h e r w i s eu s ec u r r e n tw o r k i n gd i r e c t o r y .

f i # A s s u m e sa l lf i l e si nt h et a r g e td i r e c t o r ya r eM a c P a i n ti m a g ef i l e s , # +w i t ha" . m a c "f i l e n a m es u f f i x . f o rf i l ei n$ d i r e c t o r y / * d o f i l e n a m e = $ { f i l e % . * c } #F i l e n a m eg l o b b i n g .

# S t r i p" . m a c "s u f f i xo f ff i l e n a m e # +( ' . * c 'm a t c h e se v e r y t h i n g # +b e t w e e n' . 'a n d' c ' ,i n c l u s i v e ) . $ O P E R A T I O N$ f i l e>" $ f i l e n a m e . $ S U F F I X " #R e d i r e c tc o n v e r s i o nt on e wf i l e n a m e . r mf$ f i l e #D e l e t eo r i g i n a lf i l e sa f t e rc o n v e r t i n g . e c h o" $ f i l e n a m e . $ S U F F I X " #L o gw h a ti sh a p p e n i n gt os t d o u t . d o n e e x i t0 #E x e r c i s e : ## A si ts t a n d s ,t h i ss c r i p tc o n v e r t s* a l l *t h ef i l e si nt h ec u r r e n t # +w o r k i n gd i r e c t o r y . # M o d i f yi tt ow o r k* o n l y *o nf i l e sw i t ha" . m a c "s u f f i x .

Example 10-4. Converting streaming audio files to ogg


# ! / b i n / b a s h #r a 2 o g g . s h :C o n v e r ts t r e a m i n ga u d i of i l e s( * . r a )t oo g g . #U s e st h e" m p l a y e r "m e d i ap l a y e rp r o g r a m : # h t t p : / / w w w . m p l a y e r h q . h u / h o m e p a g e #U s e st h e" o g g "l i b r a r ya n d" o g g e n c " : # h t t p : / / w w w . x i p h . o r g / # #T h i ss c r i p tm a yn e e da p p r o p r i a t ec o d e c si n s t a l l e d ,s u c ha ss i p r . s o. . . #P o s s i b l ya l s ot h ec o m p a t l i b s t d c + +p a c k a g e .

O F I L E P R E F = $ { 1 % % r a } #S t r i po f ft h e" r a "s u f f i x . O F I L E S U F F = w a v #S u f f i xf o rw a vf i l e . O U T F I L E = " $ O F I L E P R E F " " $ O F I L E S U F F " E _ N O A R G S = 8 5 i f[z" $ 1 "] #M u s ts p e c i f yaf i l e n a m et oc o n v e r t . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `[ f i l e n a m e ] " e x i t$ E _ N O A R G S f i

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # m p l a y e r" $ 1 "a op c m : f i l e = $ O U T F I L E o g g e n c" $ O U T F I L E " #C o r r e c tf i l ee x t e n s i o na u t o m a t i c a l l ya d d e db yo g g e n c . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # r m" $ O U T F I L E " #D e l e t ei n t e r m e d i a t e* . w a vf i l e . #I fy o uw a n tt ok e e pi t ,c o m m e n to u ta b o v el i n e .

e x i t$ ? # N o t e : # # O naW e b s i t e ,s i m p l yc l i c k i n go na* . r a ms t r e a m i n ga u d i of i l e # +u s u a l l yo n l yd o w n l o a d st h eU R Lo ft h ea c t u a l* . r aa u d i of i l e . # Y o uc a nt h e nu s e" w g e t "o rs o m e t h i n gs i m i l a r # +t od o w n l o a dt h e* . r af i l ei t s e l f .

# E x e r c i s e s : # # A si s ,t h i ss c r i p tc o n v e r t so n l y* . r af i l e n a m e s . # A d df l e x i b i l i t yb yp e r m i t t i n gu s eo f* . r a ma n do t h e rf i l e n a m e s . # # I fy o u ' r er e a l l ya m b i t i o u s ,e x p a n dt h es c r i p t # +t od oa u t o m a t i cd o w n l o a d sa n dc o n v e r s i o n so fs t r e a m i n ga u d i of i l e s . # G i v e naU R L ,b a t c hd o w n l o a ds t r e a m i n ga u d i of i l e s( u s i n g" w g e t " ) # +a n dc o n v e r tt h e mo nt h ef l y .

A simple emulation of getopt using substring-extraction constructs. Example 10-5. Emulating getopt
# ! / b i n / b a s h #g e t o p t s i m p l e . s h #A u t h o r :C h r i sM o r g a n #U s e di nt h eA B SG u i d ew i t hp e r m i s s i o n .

g e t o p t _ s i m p l e ( ) { e c h o" g e t o p t _ s i m p l e ( ) " e c h o" P a r a m e t e r sa r e' $ * ' " u n t i l[z" $ 1 "] d o e c h o" P r o c e s s i n gp a r a m e t e ro f :' $ 1 ' " i f[$ { 1 : 0 : 1 }=' / '] t h e n t m p = $ { 1 : 1 } #S t r i po f fl e a d i n g' / '... p a r a m e t e r = $ { t m p % % = * } #E x t r a c tn a m e . v a l u e = $ { t m p # # * = } #E x t r a c tv a l u e . e c h o" P a r a m e t e r :' $ p a r a m e t e r ' ,v a l u e :' $ v a l u e ' " e v a l$ p a r a m e t e r = $ v a l u e f i s h i f t d o n e } #P a s sa l lo p t i o n st og e t o p t _ s i m p l e ( ) . g e t o p t _ s i m p l e$ * e c h o" t e s ti s' $ t e s t ' " e c h o" t e s t 2i s' $ t e s t 2 ' " e x i t0 #S e ea l s o ,U s e G e t O p t . s h ,am o d i f i e dv e r s i o no ft h i ss c r i p t . s hg e t o p t _ e x a m p l e . s h/ t e s t = v a l u e 1/ t e s t 2 = v a l u e 2 P a r a m e t e r sa r e' / t e s t = v a l u e 1/ t e s t 2 = v a l u e 2 ' P r o c e s s i n gp a r a m e t e ro f :' / t e s t = v a l u e 1 ' P a r a m e t e r :' t e s t ' ,v a l u e :' v a l u e 1 ' P r o c e s s i n gp a r a m e t e ro f :' / t e s t 2 = v a l u e 2 ' P a r a m e t e r :' t e s t 2 ' ,v a l u e :' v a l u e 2 ' t e s ti s' v a l u e 1 ' t e s t 2i s' v a l u e 2 '

Substring Replacement ${string/substring/replacement} Replace first match of $ s u b s t r i n gwith $ r e p l a c e m e n t . [50] ${string//substring/replacement}

Replace all matches of $ s u b s t r i n gwith $ r e p l a c e m e n t .


s t r i n g Z = a b c A B C 1 2 3 A B C a b c e c h o$ { s t r i n g Z / a b c / x y z } #x y z A B C 1 2 3 A B C a b c #R e p l a c e sf i r s tm a t c ho f' a b c 'w i t h' x y z ' . #x y z A B C 1 2 3 A B C x y z #R e p l a c e sa l lm a t c h e so f' a b c 'w i t h#' x y z ' .

e c h o$ { s t r i n g Z / / a b c / x y z }

e c h o e c h o" $ s t r i n g Z " e c h o -

#a b c A B C 1 2 3 A B C a b c #T h es t r i n gi t s e l fi sn o ta l t e r e d !

#C a nt h em a t c ha n dr e p l a c e m e n ts t r i n g sb ep a r a m e t e r i z e d ? m a t c h = a b c r e p l = 0 0 0 e c h o$ { s t r i n g Z / $ m a t c h / $ r e p l } #0 0 0 A B C 1 2 3 A B C a b c # ^ ^ ^ ^ ^ e c h o$ { s t r i n g Z / / $ m a t c h / $ r e p l }#0 0 0 A B C 1 2 3 A B C 0 0 0 #Y e s ! ^ ^ ^ ^ ^ ^ ^ ^ e c h o #W h a th a p p e n si fn o$ r e p l a c e m e n ts t r i n gi ss u p p l i e d ? e c h o$ { s t r i n g Z / a b c } #A B C 1 2 3 A B C a b c e c h o$ { s t r i n g Z / / a b c } #A B C 1 2 3 A B C #As i m p l ed e l e t i o nt a k e sp l a c e .

${string/#substring/replacement} If $ s u b s t r i n gmatches front end of $ s t r i n g , substitute $ r e p l a c e m e n tfor $ s u b s t r i n g . ${string/%substring/replacement} If $ s u b s t r i n gmatches back end of $ s t r i n g , substitute $ r e p l a c e m e n tfor $ s u b s t r i n g .
s t r i n g Z = a b c A B C 1 2 3 A B C a b c e c h o$ { s t r i n g Z / # a b c / X Y Z } #X Y Z A B C 1 2 3 A B C a b c #R e p l a c e sf r o n t e n dm a t c ho f' a b c 'w i t h' X Y Z ' . #a b c A B C 1 2 3 A B C X Y Z #R e p l a c e sb a c k e n dm a t c ho f' a b c 'w i t h' X Y Z ' .

e c h o$ { s t r i n g Z / % a b c / X Y Z }

10.1.1. Manipulating strings using awk


A Bash script may invoke the string manipulation facilities of awk as an alternative to using its built-in operations. Example 10-6. Alternate ways of extracting and locating substrings
# ! / b i n / b a s h #s u b s t r i n g e x t r a c t i o n . s h S t r i n g = 2 3 s k i d o o 1 # 0 1 2 3 4 5 6 7 8 B a s h # 1 2 3 4 5 6 7 8 9 a w k #N o t ed i f f e r e n ts t r i n gi n d e x i n gs y s t e m : #B a s hn u m b e r sf i r s tc h a r a c t e ro fs t r i n ga s0 . #A w k n u m b e r sf i r s tc h a r a c t e ro fs t r i n ga s1 . e c h o$ { S t r i n g : 2 : 4 }#p o s i t i o n3( 0 1 2 ) ,4c h a r a c t e r sl o n g #s k i d

#T h ea w ke q u i v a l e n to f$ { s t r i n g : p o s : l e n g t h }i ss u b s t r ( s t r i n g , p o s , l e n g t h ) . e c h o|a w k' {p r i n ts u b s t r ( " ' " $ { S t r i n g } " ' " , 3 , 4 ) #s k i d } ' # P i p i n ga ne m p t y" e c h o "t oa w kg i v e si td u m m yi n p u t , # +a n dt h u sm a k e si tu n n e c e s s a r yt os u p p l yaf i l e n a m e . e c h o" " #A n dl i k e w i s e : e c h o|a w k' {p r i n ti n d e x ( " ' " $ { S t r i n g } " ' " ," s k i d " ) #3 } #( s k i ds t a r t sa tp o s i t i o n3 ) ' #T h ea w ke q u i v a l e n to f" e x p ri n d e x ". . . e x i t0

10.1.2. Further Reference


For more on string manipulation in scripts, refer to Section 10.2 and the relevant section of the expr command listing. Script examples: 1. Example 16-9 2. Example 10-9 3. Example 10-10 4. Example 10-11 5. Example 10-13 6. Example A-36 7. Example A-41

10.2. Parameter Substitution


Manipulating and/or expanding variables
$ { p a r a m e t e r }

Same as $ p a r a m e t e r , i.e., value of the variable p a r a m e t e r . In certain contexts, only the less ambiguous $ { p a r a m e t e r }form works. May be used for concatenating variables with strings.
y o u r _ i d = $ { U S E R } o n $ { H O S T N A M E } e c h o" $ y o u r _ i d " # e c h o" O l d\ $ P A T H=$ P A T H " P A T H = $ { P A T H } : / o p t / b i n #A d d/ o p t / b i nt o$ P A T Hf o rd u r a t i o no fs c r i p t . e c h o" N e w\ $ P A T H=$ P A T H " $ { p a r a m e t e r d e f a u l t } ,$ { p a r a m e t e r : d e f a u l t }

If parameter not set, use default.


v a r 1 = 1 v a r 2 = 2 #v a r 3i su n s e t . e c h o$ { v a r 1 $ v a r 2 } e c h o$ { v a r 3 $ v a r 2 } # ^ #1 #2 N o t et h e$p r e f i x .

e c h o$ { u s e r n a m e ` w h o a m i ` } #E c h o e st h er e s u l to f` w h o a m i ` ,i fv a r i a b l e$ u s e r n a m ei ss t i l lu n s e t . $ { p a r a m e t e r d e f a u l t }and $ { p a r a m e t e r : d e f a u l t }are almost equivalent.

The extra :

makes a difference only when p a r a m e t e rhas been declared, but is null.


# ! / b i n / b a s h #p a r a m s u b . s h # W h e t h e rav a r i a b l eh a sb e e nd e c l a r e d # +a f f e c t st r i g g e r i n go ft h ed e f a u l to p t i o n # +e v e ni ft h ev a r i a b l ei sn u l l . u s e r n a m e 0 = e c h o" u s e r n a m e 0h a sb e e nd e c l a r e d ,b u ti ss e tt on u l l . " e c h o" u s e r n a m e 0=$ { u s e r n a m e 0 ` w h o a m i ` } " #W i l ln o te c h o . e c h o e c h ou s e r n a m e 1h a sn o tb e e nd e c l a r e d . e c h o" u s e r n a m e 1=$ { u s e r n a m e 1 ` w h o a m i ` } " #W i l le c h o . u s e r n a m e 2 = e c h o" u s e r n a m e 2h a sb e e nd e c l a r e d ,b u ti ss e tt on u l l . " e c h o" u s e r n a m e 2=$ { u s e r n a m e 2 : ` w h o a m i ` } " # ^ #W i l le c h ob e c a u s eo f: -r a t h e rt h a nj u s t-i nc o n d i t i o nt e s t . #C o m p a r et of i r s ti n s t a n c e ,a b o v e .

# #O n c ea g a i n : v a r i a b l e = #v a r i a b l eh a sb e e nd e c l a r e d ,b u ti ss e tt on u l l . e c h o" $ { v a r i a b l e 0 } " e c h o" $ { v a r i a b l e : 1 } " # ^ u n s e tv a r i a b l e e c h o" $ { v a r i a b l e 2 } " e c h o" $ { v a r i a b l e : 3 } " e x i t0 #2 #3 #( n oo u t p u t ) #1

The default parameter construct finds use in providing "missing" command-line arguments in scripts.
D E F A U L T _ F I L E N A M E = g e n e r i c . d a t a f i l e n a m e = $ { 1 : $ D E F A U L T _ F I L E N A M E } # I fn o to t h e r w i s es p e c i f i e d ,t h ef o l l o w i n gc o m m a n db l o c ko p e r a t e s

# +o nt h ef i l e" g e n e r i c . d a t a " . # B e g i n C o m m a n d B l o c k # . . . # . . . # . . . # E n d C o m m a n d B l o c k

# F r o m" h a n o i 2 . b a s h "e x a m p l e : D I S K S = $ { 1 : E _ N O P A R A M } #M u s ts p e c i f yh o wm a n yd i s k s . # S e t$ D I S K St o$ 1c o m m a n d l i n e p a r a m e t e r , # +o rt o$ E _ N O P A R A Mi ft h a ti su n s e t .

See also Example 3-4, Example 31-2, and Example A-6. Compare this method with using an and list to supply a default command-line argument.
$ { p a r a m e t e r = d e f a u l t } ,$ { p a r a m e t e r : = d e f a u l t }

If parameter not set, set it to default . Both forms nearly equivalent. The : makes a difference only when $ p a r a m e t e rhas been declared and is null, [51] as above.
e c h o$ { v a r = a b c } #a b c e c h o$ { v a r = x y z } #a b c #$ v a rh a da l r e a d yb e e ns e tt oa b c ,s oi td i dn o tc h a n g e . $ { p a r a m e t e r + a l t _ v a l u e } ,$ { p a r a m e t e r : + a l t _ v a l u e }

If parameter set, use a l t _ v a l u e , else use null string. Both forms nearly equivalent. The : makes a difference only when p a r a m e t e rhas been declared and is null, see below.
e c h o" # # # # # #\ $ { p a r a m e t e r + a l t _ v a l u e }# # # # # # # # " e c h o a = $ { p a r a m 1 + x y z } e c h o" a=$ a " p a r a m 2 = a = $ { p a r a m 2 + x y z } e c h o" a=$ a " p a r a m 3 = 1 2 3 a = $ { p a r a m 3 + x y z } e c h o" a=$ a "

#a=

#a=x y z

#a=x y z

e c h o e c h o" # # # # # #\ $ { p a r a m e t e r : + a l t _ v a l u e }# # # # # # # # " e c h o a = $ { p a r a m 4 : + x y z } e c h o" a=$ a "

#a=

p a r a m 5 = a = $ { p a r a m 5 : + x y z } e c h o" a=$ a " #a= #D i f f e r e n tr e s u l tf r o m a = $ { p a r a m 5 + x y z } p a r a m 6 = 1 2 3 a = $ { p a r a m 6 : + x y z } e c h o" a=$ a "

#a=x y z

$ { p a r a m e t e r ? e r r _ m s g } ,$ { p a r a m e t e r : ? e r r _ m s g }

If parameter set, use it, else print err_msg and abort the script with an exit status of 1. Both forms nearly equivalent. The : makes a difference only when p a r a m e t e rhas been declared and is null, as above. Example 10-7. Using parameter substitution and error messages
# ! / b i n / b a s h # C h e c ks o m eo ft h es y s t e m ' se n v i r o n m e n t a lv a r i a b l e s . # T h i si sg o o dp r e v e n t a t i v em a i n t e n a n c e . # I f ,f o re x a m p l e ,$ U S E R ,t h en a m eo ft h ep e r s o na tt h ec o n s o l e ,i sn o ts e t , # +t h em a c h i n ew i l ln o tr e c o g n i z ey o u . :$ { H O S T N A M E ? }$ { U S E R ? }$ { H O M E ? }$ { M A I L ? } e c h o e c h o" N a m eo ft h em a c h i n ei s$ H O S T N A M E . " e c h o" Y o ua r e$ U S E R . " e c h o" Y o u rh o m ed i r e c t o r yi s$ H O M E . " e c h o" Y o u rm a i lI N B O Xi sl o c a t e di n$ M A I L . " e c h o e c h o" I fy o ua r er e a d i n gt h i sm e s s a g e , " e c h o" c r i t i c a le n v i r o n m e n t a lv a r i a b l e sh a v eb e e ns e t . " e c h o e c h o ## T h e$ { v a r i a b l e n a m e ? }c o n s t r u c t i o nc a na l s oc h e c k # +f o rv a r i a b l e ss e tw i t h i nt h es c r i p t . T h i s V a r i a b l e = V a l u e o f T h i s V a r i a b l e # N o t e ,b yt h ew a y ,t h a ts t r i n gv a r i a b l e sm a yb es e t # +t oc h a r a c t e r sd i s a l l o w e di nt h e i rn a m e s . :$ { T h i s V a r i a b l e ? } e c h o" V a l u eo fT h i s V a r i a b l ei s$ T h i s V a r i a b l e " . e c h o ;e c h o

:$ { Z Z X y 2 3 A B ? " Z Z X y 2 3 A Bh a sn o tb e e ns e t . " } # S i n c eZ Z X y 2 3 A Bh a sn o tb e e ns e t , # +t h e nt h es c r i p tt e r m i n a t e sw i t ha ne r r o rm e s s a g e . #Y o uc a ns p e c i f yt h ee r r o rm e s s a g e . #:$ { v a r i a b l e n a m e ? " E R R O RM E S S A G E " }

#S a m er e s u l tw i t h : # # #

d u m m y _ v a r i a b l e = $ { Z Z X y 2 3 A B ? } d u m m y _ v a r i a b l e = $ { Z Z X y 2 3 A B ? " Z X y 2 3 A Bh a sn o tb e e ns e t . " } e c h o$ { Z Z X y 2 3 A B ? }> / d e v / n u l l

# C o m p a r et h e s em e t h o d so fc h e c k i n gw h e t h e rav a r i a b l eh a sb e e ns e t # +w i t h" s e tu "...

e c h o" Y o uw i l ln o ts e et h i sm e s s a g e ,b e c a u s es c r i p ta l r e a d yt e r m i n a t e d . " H E R E = 0 e x i t$ H E R E

#W i l lN O Te x i th e r e .

#I nf a c t ,t h i ss c r i p tw i l lr e t u r na ne x i ts t a t u s( e c h o$ ? )o f1 .

Example 10-8. Parameter substitution and "usage" messages


# ! / b i n / b a s h #u s a g e m e s s a g e . s h :$ { 1 ? " U s a g e :$ 0A R G U M E N T " } # S c r i p te x i t sh e r ei fc o m m a n d l i n ep a r a m e t e ra b s e n t , # +w i t hf o l l o w i n ge r r o rm e s s a g e . # u s a g e m e s s a g e . s h :1 :U s a g e :u s a g e m e s s a g e . s hA R G U M E N T e c h o" T h e s et w ol i n e se c h oo n l yi fc o m m a n d l i n ep a r a m e t e rg i v e n . " e c h o" c o m m a n d l i n ep a r a m e t e r=\ " $ 1 \ " " e x i t0 #W i l le x i th e r eo n l yi fc o m m a n d l i n ep a r a m e t e rp r e s e n t . #C h e c kt h ee x i ts t a t u s ,b o t hw i t ha n dw i t h o u tc o m m a n d l i n ep a r a m e t e r . #I fc o m m a n d l i n ep a r a m e t e rp r e s e n t ,t h e n" $ ? "i s0 . #I fn o t ,t h e n" $ ? "i s1 .

Parameter substitution and/or expansion. The following expressions are the complement to the match i nexpr string operations (see Example 16-9). These particular ones are used mostly in parsing file path names. Variable length / Substring removal
$ { # v a r } S t r i n gl e n g t h(number of characters in $ v a r ).

For an array, ${#array} is the length of the first element in the

array. Exceptions: ${#*} and ${#@} give the number of positional parameters. For an array, ${#array[*]} and ${#array[@]} give the number of elements in the array. Example 10-9. Length of a variable
# ! / b i n / b a s h #l e n g t h . s h E _ N O _ A R G S = 6 5 i f[$ #e q0] #M u s th a v ec o m m a n d l i n ea r g st od e m os c r i p t . t h e n e c h o" P l e a s ei n v o k et h i ss c r i p tw i t ho n eo rm o r ec o m m a n d l i n ea r g u m e n t s . " e x i t$ E _ N O _ A R G S f i v a r 0 1 = a b c d E F G H 2 8 i j e c h o" v a r 0 1=$ { v a r 0 1 } " e c h o" L e n g t ho fv a r 0 1=$ { # v a r 0 1 } " #N o w ,l e t ' st r ye m b e d d i n gas p a c e . v a r 0 2 = " a b c dE F G H 2 8 i j " e c h o" v a r 0 2=$ { v a r 0 2 } " e c h o" L e n g t ho fv a r 0 2=$ { # v a r 0 2 } " e c h o" N u m b e ro fc o m m a n d l i n ea r g u m e n t sp a s s e dt os c r i p t=$ { # @ } " e c h o" N u m b e ro fc o m m a n d l i n ea r g u m e n t sp a s s e dt os c r i p t=$ { # * } " e x i t0 $ { v a r # P a t t e r n } ,$ { v a r # # P a t t e r n }

${var#Pattern} Remove from $ v a rthe shortest part of $ P a t t e r nthat matches the f r o n te n dof $ v a r .

${var##Pattern} Remove from $ v a rthe longest part of $ P a t t e r nthat matches the f r o n te n dof $ v a r . A usage illustration from Example A-7:
#F u n c t i o nf r o m" d a y s b e t w e e n . s h "e x a m p l e . #S t r i p sl e a d i n gz e r o ( s )f r o ma r g u m e n tp a s s e d . s t r i p _ l e a d i n g _ z e r o( )# S t r i pp o s s i b l el e a d i n gz e r o ( s ) { # +f r o ma r g u m e n tp a s s e d . r e t u r n = $ { 1 # 0 } # T h e" 1 "r e f e r st o" $ 1 "-p a s s e da r g . } # T h e" 0 "i sw h a tt or e m o v ef r o m" $ 1 "-s t r i p sz e r o s .

Manfred Schwarb's more elaborate variation of the above:


s t r i p _ l e a d i n g _ z e r o 2( )#S t r i pp o s s i b l el e a d i n gz e r o ( s ) ,s i n c eo t h e r w i s e { #B a s hw i l li n t e r p r e ts u c hn u m b e r sa so c t a lv a l u e s . s h o p tse x t g l o b #T u r no ne x t e n d e dg l o b b i n g . l o c a lv a l = $ { 1 # # + ( 0 ) }#U s el o c a lv a r i a b l e ,l o n g e s tm a t c h i n gs e r i e so f0 ' s . s h o p tue x t g l o b #T u r no f fe x t e n d e dg l o b b i n g . _ s t r i p _ l e a d i n g _ z e r o 2 = $ { v a l : 0 } #I fi n p u tw a s0 ,r e t u r n0i n s t e a do f" " . }

Another usage illustration:


e c h o` b a s e n a m e$ P W D ` e c h o" $ { P W D # # * / } " e c h o e c h o` b a s e n a m e$ 0 ` e c h o$ 0 e c h o" $ { 0 # # * / } " e c h o f i l e n a m e = t e s t . d a t a e c h o" $ { f i l e n a m e # # * . } " #B a s e n a m eo fc u r r e n tw o r k i n gd i r e c t o r y . #B a s e n a m eo fc u r r e n tw o r k i n gd i r e c t o r y . #N a m eo fs c r i p t . #N a m eo fs c r i p t . #N a m eo fs c r i p t .

#d a t a #E x t e n s i o no ff i l e n a m e .

$ { v a r % P a t t e r n } ,$ { v a r % % P a t t e r n }

${var%Pattern} Remove from $ v a rthe shortest part of $ P a t t e r nthat matches the b a c ke n dof $ v a r . ${var%%Pattern} Remove from $ v a rthe longest part of $ P a t t e r nthat matches the b a c ke n dof $ v a r . Version 2 of Bash added additional options. Example 10-10. Pattern matching in parameter substitution
# ! / b i n / b a s h #p a t t m a t c h i n g . s h #P a t t e r nm a t c h i n g u s i n gt h e## #%% %p a r a m e t e rs u b s t i t u t i o no p e r a t o r s . v a r 1 = a b c d 1 2 3 4 5 a b c 6 7 8 9 p a t t e r n 1 = a * c #*( w i l dc a r d )m a t c h e se v e r y t h i n gb e t w e e na-c . e c h o e c h o" v a r 1=$ v a r 1 " e c h o" v a r 1=$ { v a r 1 } "

#a b c d 1 2 3 4 5 a b c 6 7 8 9 #a b c d 1 2 3 4 5 a b c 6 7 8 9 #( a l t e r n a t ef o r m ) e c h o" N u m b e ro fc h a r a c t e r si n$ { v a r 1 }=$ { # v a r 1 } " e c h o e c h o" p a t t e r n 1=$ p a t t e r n 1 " #a * c ( e v e r y t h i n gb e t w e e n' a 'a n d' c ' ) e c h o" " e c h o' $ { v a r 1 # $ p a t t e r n 1 } = '" $ { v a r 1 # $ p a t t e r n 1 } " # d 1 2 3 4 5 a b c 6 7 8 9 #S h o r t e s tp o s s i b l em a t c h ,s t r i p so u tf i r s t3c h a r a c t e r s a b c d 1 2 3 4 5 a b c 6 7 8 9 # ^ ^ ^ ^ ^ | |

e c h o' $ { v a r 1 # # $ p a t t e r n 1 }= '" $ { v a r 1 # # $ p a t t e r n 1 } " # 6 7 8 9 #L o n g e s tp o s s i b l em a t c h ,s t r i p so u tf i r s t1 2c h a r a c t e r s a b c d 1 2 3 4 5 a b c 6 7 8 9 # ^ ^ ^ ^ ^ | | e c h o ;e c h o ;e c h o p a t t e r n 2 = b * 9 #e v e r y t h i n gb e t w e e n' b 'a n d' 9 ' e c h o" v a r 1=$ v a r 1 " #S t i l l a b c d 1 2 3 4 5 a b c 6 7 8 9 e c h o e c h o" p a t t e r n 2=$ p a t t e r n 2 " e c h o" " e c h o' $ { v a r 1 % p a t t e r n 2 } = '" $ { v a r 1 % $ p a t t e r n 2 } " # a b c d 1 2 3 4 5 a #S h o r t e s tp o s s i b l em a t c h ,s t r i p so u tl a s t6c h a r a c t e r s a b c d 1 2 3 4 5 a b c 6 7 8 9 # ^ ^ ^ ^ | | e c h o' $ { v a r 1 % % p a t t e r n 2 }= '" $ { v a r 1 % % $ p a t t e r n 2 } " # a #L o n g e s tp o s s i b l em a t c h ,s t r i p so u tl a s t1 2c h a r a c t e r s a b c d 1 2 3 4 5 a b c 6 7 8 9 # ^ ^ ^ ^ | | #R e m e m b e r ,#a n d# #w o r kf r o mt h el e f te n d( b e g i n n i n g )o fs t r i n g , # %a n d% %w o r kf r o mt h er i g h te n d . e c h o e x i t0

Example 10-11. Renaming file extensions:


# ! / b i n / b a s h #r f e . s h :R e n a m i n gf i l ee x t e n s i o n s . # # r f eo l d _ e x t e n s i o nn e w _ e x t e n s i o n # #E x a m p l e : #T or e n a m ea l l* . g i ff i l e si nw o r k i n gd i r e c t o r yt o* . j p g , # r f eg i fj p g

E _ B A D A R G S = 6 5 c a s e$ #i n 0 | 1 ) #T h ev e r t i c a lb a rm e a n s" o r "i nt h i sc o n t e x t . e c h o" U s a g e :` b a s e n a m e$ 0 `o l d _ f i l e _ s u f f i xn e w _ f i l e _ s u f f i x " e x i t$ E _ B A D A R G S #I f0o r1a r g ,t h e nb a i lo u t . ; ; e s a c

f o rf i l e n a m ei n* . $ 1 #T r a v e r s el i s to ff i l e se n d i n gw i t h1 s ta r g u m e n t . d o m v$ f i l e n a m e$ { f i l e n a m e % $ 1 } $ 2 # S t r i po f fp a r to ff i l e n a m em a t c h i n g1 s ta r g u m e n t , # +t h e na p p e n d2 n da r g u m e n t . d o n e e x i t0

Variable expansion / Substring replacement These constructs have been adopted from ksh.
$ { v a r : p o s }

Variable v a rexpanded, starting from offset p o s .


$ { v a r : p o s : l e n }

Expansion to a max of l e ncharacters of variable v a r , from offset p o s . See Example A-13 for an example of the creative use of this operator.
$ { v a r / P a t t e r n / R e p l a c e m e n t }

First match of P a t t e r n , within v a rreplaced with R e p l a c e m e n t . If R e p l a c e m e n tis omitted, then the first match of P a t t e r nis replaced by nothing, that is, deleted.
$ { v a r / / P a t t e r n / R e p l a c e m e n t }

Global replacement. All matches of P a t t e r n , within v a rreplaced with R e p l a c e m e n t . As above, if R e p l a c e m e n tis omitted, then all occurrences of P a t t e r nare replaced by nothing, that is, deleted. Example 10-12. Using pattern matching to parse arbitrary strings
# ! / b i n / b a s h v a r 1 = a b c d 1 2 3 4 d e f g e c h o" v a r 1=$ v a r 1 " t = $ { v a r 1 # * * } e c h o" v a r 1( w i t he v e r y t h i n g ,u pt oa n di n c l u d i n gf i r s t-s t r i p p e do u t )=$ t " # t = $ { v a r 1 # * } w o r k sj u s tt h es a m e , # +s i n c e#m a t c h e st h es h o r t e s ts t r i n g , # +a n d*m a t c h e se v e r y t h i n gp r e c e d i n g ,i n c l u d i n ga ne m p t ys t r i n g . #( T h a n k s ,S t e p h a n eC h a z e l a s ,f o rp o i n t i n gt h i so u t . ) t = $ { v a r 1 # # * * } e c h o" I fv a r 1c o n t a i n sa\ " \ " ,r e t u r n se m p t ys t r i n g . . .

v a r 1=$ t "

t = $ { v a r 1 % * * } e c h o" v a r 1( w i t he v e r y t h i n gf r o mt h el a s t-o ns t r i p p e do u t )=$ t " e c h o #p a t h _ n a m e = / h o m e / b o z o / i d e a s / t h o u g h t s . f o r . t o d a y #e c h o" p a t h _ n a m e=$ p a t h _ n a m e " t = $ { p a t h _ n a m e # # / * / } e c h o" p a t h _ n a m e ,s t r i p p e do fp r e f i x e s=$ t " #S a m ee f f e c ta s t = ` b a s e n a m e$ p a t h _ n a m e `i nt h i sp a r t i c u l a rc a s e . # t = $ { p a t h _ n a m e % / } ;t = $ { t # # * / } i sam o r eg e n e r a ls o l u t i o n , # +b u ts t i l lf a i l ss o m e t i m e s . # I f$ p a t h _ n a m ee n d sw i t han e w l i n e ,t h e n` b a s e n a m e$ p a t h _ n a m e `w i l ln o tw o r k , # +b u tt h ea b o v ee x p r e s s i o nw i l l . #( T h a n k s ,S . C . ) t = $ { p a t h _ n a m e % / * . * } #S a m ee f f e c ta s t = ` d i r n a m e$ p a t h _ n a m e ` e c h o" p a t h _ n a m e ,s t r i p p e do fs u f f i x e s=$ t " #T h e s ew i l lf a i li ns o m ec a s e s ,s u c ha s" . . / " ," / f o o / / / / " ,#" f o o / " ," / " . # R e m o v i n gs u f f i x e s ,e s p e c i a l l yw h e nt h eb a s e n a m eh a sn os u f f i x , # +b u tt h ed i r n a m ed o e s ,a l s oc o m p l i c a t e sm a t t e r s . #( T h a n k s ,S . C . ) e c h o t = $ { p a t h _ n a m e : 1 1 } e c h o" $ p a t h _ n a m e ,w i t hf i r s t1 1c h a r ss t r i p p e do f f=$ t " t = $ { p a t h _ n a m e : 1 1 : 5 } e c h o" $ p a t h _ n a m e ,w i t hf i r s t1 1c h a r ss t r i p p e do f f ,l e n g t h5=$ t " e c h o

t = $ { p a t h _ n a m e / b o z o / c l o w n } e c h o" $ p a t h _ n a m ew i t h\ " b o z o \ "r e p l a c e d b y\ " c l o w n \ "=$ t " t = $ { p a t h _ n a m e / t o d a y / } e c h o" $ p a t h _ n a m ew i t h\ " t o d a y \ "d e l e t e d=$ t " t = $ { p a t h _ n a m e / / o / O } e c h o" $ p a t h _ n a m ew i t ha l lo ' sc a p i t a l i z e d=$ t " t = $ { p a t h _ n a m e / / o / } e c h o" $ p a t h _ n a m ew i t ha l lo ' sd e l e t e d=$ t " e x i t0 $ { v a r / # P a t t e r n / R e p l a c e m e n t }

If prefix of v a rmatches P a t t e r n , then substitute R e p l a c e m e n tfor P a t t e r n .


$ { v a r / % P a t t e r n / R e p l a c e m e n t }

If suffix of v a rmatches P a t t e r n , then substitute R e p l a c e m e n tfor P a t t e r n . Example 10-13. Matching patterns at prefix or suffix of string
# ! / b i n / b a s h #v a r m a t c h . s h : #D e m oo fp a t t e r nr e p l a c e m e n ta tp r e f i x/s u f f i xo fs t r i n g . v 0 = a b c 1 2 3 4 z i p 1 2 3 4 a b c e c h o" v 0=$ v 0 " e c h o #O r i g i n a lv a r i a b l e . #a b c 1 2 3 4 z i p 1 2 3 4 a b c

#M a t c ha tp r e f i x( b e g i n n i n g )o fs t r i n g . v 1 = $ { v 0 / # a b c / A B C D E F } #a b c 1 2 3 4 z i p 1 2 3 4 a b c #| | e c h o" v 1=$ v 1 " #A B C D E F 1 2 3 4 z i p 1 2 3 4 a b c #| | #M a t c ha ts u f f i x( e n d )o fs t r i n g . v 2 = $ { v 0 / % a b c / A B C D E F } #a b c 1 2 3 4 z i p 1 2 3 a b c # | | e c h o" v 2=$ v 2 " #a b c 1 2 3 4 z i p 1 2 3 4 A B C D E F # | | e c h o # # M u s tm a t c ha tb e g i n n i n g/e n do fs t r i n g , # +o t h e r w i s en or e p l a c e m e n tr e s u l t s . # v 3 = $ { v 0 / # 1 2 3 / 0 0 0 } #M a t c h e s ,b u tn o ta tb e g i n n i n g . e c h o" v 3=$ v 3 " #a b c 1 2 3 4 z i p 1 2 3 4 a b c #N OR E P L A C E M E N T . v 4 = $ { v 0 / % 1 2 3 / 0 0 0 } #M a t c h e s ,b u tn o ta te n d . e c h o" v 4=$ v 4 " #a b c 1 2 3 4 z i p 1 2 3 4 a b c #N OR E P L A C E M E N T . e x i t0 $ { ! v a r p r e f i x * } ,$ { ! v a r p r e f i x @ }

Matches names of all previously declared variables beginning with v a r p r e f i x .


#T h i si sav a r i a t i o no ni n d i r e c tr e f e r e n c e ,b u tw i t ha*o r@ . #B a s h ,v e r s i o n2 . 0 4 ,a d d st h i sf e a t u r e . x y z 2 3 = w h a t e v e r x y z 2 4 = a = $ { ! x y z * } #^^ ^ e c h o" a=$ a " # E x p a n d st o* n a m e s *o fd e c l a r e dv a r i a b l e s +b e g i n n i n gw i t h" x y z " . # a=x y z 2 3x y z 2 4

a = $ { ! x y z @ } e c h o" a=$ a " e c h o" "

# S a m ea sa b o v e . # a=x y z 2 3x y z 2 4

a b c 2 3 = s o m e t h i n g _ e l s e b = $ { ! a b c * } e c h o" b=$ b " # b=a b c 2 3 c = $ { ! b } # N o w ,t h em o r ef a m i l i a rt y p eo fi n d i r e c tr e f e r e n c e . e c h o$ c # s o m e t h i n g _ e l s e

Chapter 11. Loops and Branches


What needs this iteration, woman? --Shakespeare, O t h e l l o Operations on code blocks are the key to structured and organized shell scripts. Looping and branching constructs provide the tools for accomplishing this.

11.1. Loops
A loop is a block of code that iterates [52] a list of commands as long as the loop control condition is true. for loops for a r gin [ l i s t ] This is the basic looping construct. It differs significantly from its C counterpart. for a r gin [l i s t ] do c o m m a n d ( s ) ... done During each pass through the loop, a r gtakes on the value of each successive variable in the l i s t .
f o ra r gi n" $ v a r 1 "" $ v a r 2 "" $ v a r 3 ". . ." $ v a r N " #I np a s s1o ft h el o o p ,a r g=$ v a r 1 #I np a s s2o ft h el o o p ,a r g=$ v a r 2 #I np a s s3o ft h el o o p ,a r g=$ v a r 3 #. . . #I np a s sNo ft h el o o p ,a r g=$ v a r N #A r g u m e n t si n[ l i s t ]q u o t e dt op r e v e n tp o s s i b l ew o r ds p l i t t i n g .

The argument l i s tmay contain wild cards. If do is on same line as for, there needs to be a semicolon after list. for a r gin [l i s t ] ; do Example 11-1. Simple for loops
# ! / b i n / b a s h #L i s t i n gt h ep l a n e t s .

f o rp l a n e ti nM e r c u r yV e n u sE a r t hM a r sJ u p i t e rS a t u r nU r a n u sN e p t u n eP l u t o d o e c h o$ p l a n e t #E a c hp l a n e to nas e p a r a t el i n e . d o n e e c h o ;e c h o f o rp l a n e ti n" M e r c u r yV e n u sE a r t hM a r sJ u p i t e rS a t u r nU r a n u sN e p t u n eP l u t o " #A l lp l a n e t so ns a m el i n e . #E n t i r e' l i s t 'e n c l o s e di nq u o t e sc r e a t e sas i n g l ev a r i a b l e . #W h y ?W h i t e s p a c ei n c o r p o r a t e di n t ot h ev a r i a b l e . d o e c h o$ p l a n e t d o n e e c h o ;e c h o" W h o o p s !P l u t oi sn ol o n g e rap l a n e t ! " e x i t0

Each [ l i s t ]element may contain multiple parameters. This is useful when processing parameters in groups. In such cases, use the set command (see Example 15-16) to force parsing of each [ l i s t ]element and assignment of each component to the positional parameters. Example 11-2. for loop with two parameters in each [list] element
# ! / b i n / b a s h #P l a n e t sr e v i s i t e d . #A s s o c i a t et h en a m eo fe a c hp l a n e tw i t hi t sd i s t a n c ef r o mt h es u n . f o rp l a n e ti n" M e r c u r y3 6 "" V e n u s6 7 "" E a r t h9 3 " " M a r s1 4 2 "" J u p i t e r4 8 3 " d o s e t-$ p l a n e t # P a r s e sv a r i a b l e" p l a n e t " # +a n ds e t sp o s i t i o n a lp a r a m e t e r s . # T h e" "p r e v e n t sn a s t ys u r p r i s e si f$ p l a n e ti sn u l lo r # +b e g i n sw i t had a s h . # M a yn e e dt os a v eo r i g i n a lp o s i t i o n a lp a r a m e t e r s , # +s i n c et h e yg e to v e r w r i t t e n . # O n ew a yo fd o i n gt h i si st ou s ea na r r a y , # o r i g i n a l _ p a r a m s = ( " $ @ " ) e c h o" $ 1 $ 2 , 0 0 0 , 0 0 0m i l e sf r o mt h es u n " # t w o t a b s c o n c a t e n a t ez e r o e so n t op a r a m e t e r$ 2 d o n e #( T h a n k s ,S . C . ,f o ra d d i t i o n a lc l a r i f i c a t i o n . ) e x i t0

A variable may supply the [ l i s t ]in a for loop. Example 11-3. Fileinfo: operating on a file list contained in a variable
# ! / b i n / b a s h #f i l e i n f o . s h F I L E S = " / u s r / s b i n / a c c e p t / u s r / s b i n / p w c k / u s r / s b i n / c h r o o t / u s r / b i n / f a k e f i l e / s b i n / b a d b l o c k s / s b i n / y p b i n d " #L i s to ff i l e sy o ua r ec u r i o u sa b o u t . #T h r e wi nad u m m yf i l e ,/ u s r / b i n / f a k e f i l e . e c h o

f o rf i l ei n$ F I L E S d o i f[!e" $ f i l e "] #C h e c ki ff i l ee x i s t s . t h e n e c h o" $ f i l ed o e sn o te x i s t . " ;e c h o c o n t i n u e #O nt on e x t . f i l sl$ f i l e|a w k' {p r i n t$ 8" f i l es i z e :"$ 5} ' #P r i n t2f i e l d s . w h a t i s` b a s e n a m e$ f i l e ` #F i l ei n f o . #N o t et h a tt h ew h a t i sd a t a b a s en e e d st oh a v eb e e ns e tu pf o rt h i st ow o r k . #T od ot h i s ,a sr o o tr u n/ u s r / b i n / m a k e w h a t i s . e c h o d o n e e x i t0

If the [ l i s t ]in a for loop contains wild cards (* and ?) used in filename expansion, then globbing takes place. Example 11-4. Operating on files with a for loop
# ! / b i n / b a s h #l i s t g l o b . s h :G e n e r a t i n g[ l i s t ]i naf o r l o o p ,u s i n g" g l o b b i n g ". . . #G l o b b i n g=f i l e n a m ee x p a n s i o n . e c h o f o rf i l ei n* # ^ B a s hp e r f o r m sf i l e n a m ee x p a n s i o n # + o ne x p r e s s i o n st h a tg l o b b i n gr e c o g n i z e s . d o l sl" $ f i l e " #L i s t sa l lf i l e si n$ P W D( c u r r e n td i r e c t o r y ) . # R e c a l lt h a tt h ew i l dc a r dc h a r a c t e r" * "m a t c h e se v e r yf i l e n a m e , # +h o w e v e r ,i n" g l o b b i n g , "i td o e s n ' tm a t c hd o t f i l e s . # I ft h ep a t t e r nm a t c h e sn of i l e ,i ti se x p a n d e dt oi t s e l f . # T op r e v e n tt h i s ,s e tt h en u l l g l o bo p t i o n # + ( s h o p tsn u l l g l o b ) . # T h a n k s ,S . C . d o n e e c h o ;e c h o f o rf i l ei n[ j x ] * d o r mf$ f i l e #R e m o v e so n l yf i l e sb e g i n n i n gw i t h" j "o r" x "i n$ P W D . e c h o" R e m o v e df i l e\ " $ f i l e \ " " . d o n e e c h o e x i t0

Omitting the i n[ l i s t ]part of a for loop causes the loop to operate on $@ -- the positional parameters. A particularly clever illustration of this is Example A-15. See also Example 15-17. Example 11-5. Missing i n[ l i s t ]in a for loop
# ! / b i n / b a s h # I n v o k et h i ss c r i p tb o t hw i t ha n dw i t h o u ta r g u m e n t s , # +a n ds e ew h a th a p p e n s . f o ra d o e c h on" $ a"

d o n e # T h e' i nl i s t 'm i s s i n g ,t h e r e f o r et h el o o po p e r a t e so n' $ @ ' # +( c o m m a n d l i n ea r g u m e n tl i s t ,i n c l u d i n gw h i t e s p a c e ) . e c h o e x i t0

It is possible to use command substitution to generate the [ l i s t ]in a for loop. See also Example 16-54, Example 11-10 and Example 16-48. Example 11-6. Generating the [ l i s t ]in a for loop with command substitution
# ! / b i n / b a s h # f o r l o o p c m d . s h :f o r l o o pw i t h[ l i s t ] # +g e n e r a t e db yc o m m a n ds u b s t i t u t i o n . N U M B E R S = " 97383 7 . 5 3 " f o rn u m b e ri n` e c h o$ N U M B E R S ` #f o rn u m b e ri n97383 7 . 5 3 d o e c h on" $ n u m b e r" d o n e e c h o e x i t0

Here is a somewhat more complex example of using command substitution to create the [ l i s t ] . Example 11-7. A grep replacement for binary files
# ! / b i n / b a s h #b i n g r e p . s h :L o c a t e sm a t c h i n gs t r i n g si nab i n a r yf i l e . #A" g r e p "r e p l a c e m e n tf o rb i n a r yf i l e s . #S i m i l a re f f e c tt o" g r e pa " E _ B A D A R G S = 6 5 E _ N O F I L E = 6 6 i f[$ #n e2] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `s e a r c h _ s t r i n gf i l e n a m e " e x i t$ E _ B A D A R G S f i i f[!f" $ 2 "] t h e n e c h o" F i l e\ " $ 2 \ "d o e sn o te x i s t . " e x i t$ E _ N O F I L E f i

I F S = $ ' \ 0 1 2 '

#P e rs u g g e s t i o no fA n t o nF i l i p p o v . #w a s : I F S = " \ n " f o rw o r di n$ (s t r i n g s" $ 2 "|g r e p" $ 1 ") #T h e" s t r i n g s "c o m m a n dl i s t ss t r i n g si nb i n a r yf i l e s . #O u t p u tt h e np i p e dt o" g r e p " ,w h i c ht e s t sf o rd e s i r e ds t r i n g . d o e c h o$ w o r d d o n e #A sS . C .p o i n t so u t ,l i n e s2 3-3 0c o u l db er e p l a c e dw i t ht h es i m p l e r # s t r i n g s" $ 2 "|g r e p" $ 1 "|t rs" $ I F S "' [ \ n * ] '

# T r ys o m e t h i n gl i k e " . / b i n g r e p . s hm e m/ b i n / l s " # +t oe x e r c i s et h i ss c r i p t . e x i t0

More of the same. Example 11-8. Listing all users on the system
# ! / b i n / b a s h #u s e r l i s t . s h P A S S W O R D _ F I L E = / e t c / p a s s w d n = 1 #U s e rn u m b e r f o rn a m ei n$ ( a w k' B E G I N { F S = " : " } { p r i n t$ 1 } '<" $ P A S S W O R D _ F I L E ") #F i e l ds e p a r a t o r=: ^ ^ ^ ^ ^ ^ #P r i n tf i r s tf i e l d ^ ^ ^ ^ ^ ^ ^ ^ #G e ti n p u tf r o mp a s s w o r df i l e / e t c / p a s s w d ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ d o e c h o" U S E R# $ n=$ n a m e " l e t" n+ =1 " d o n e

#U S E R# 1=r o o t #U S E R# 2=b i n #U S E R# 3=d a e m o n #. . . #U S E R# 3 3=b o z o e x i t$ ? # D i s c u s s i o n : # # H o wi si tt h a ta no r d i n a r yu s e r ,o ras c r i p tr u nb ys a m e , # +c a nr e a d/ e t c / p a s s w d ?( H i n t :C h e c kt h e/ e t c / p a s s w df i l ep e r m i s s i o n s . ) # I st h i sas e c u r i t yh o l e ?W h yo rw h yn o t ?

Yet another example of the [ l i s t ]resulting from command substitution. Example 11-9. Checking all the binaries in a directory for authorship
# ! / b i n / b a s h #f i n d s t r i n g . s h : #F i n dap a r t i c u l a rs t r i n gi nt h eb i n a r i e si nas p e c i f i e dd i r e c t o r y . d i r e c t o r y = / u s r / b i n / f s t r i n g = " F r e eS o f t w a r eF o u n d a t i o n " #S e ew h i c hf i l e sc o m ef r o mt h eF S F . f o rf i l ei n$ (f i n d$ d i r e c t o r yt y p efn a m e' * '|s o r t) d o s t r i n g sf$ f i l e|g r e p" $ f s t r i n g "|s e de" s % $ d i r e c t o r y % % " # I nt h e" s e d "e x p r e s s i o n , # +i ti sn e c e s s a r yt os u b s t i t u t ef o rt h en o r m a l" / "d e l i m i t e r # +b e c a u s e" / "h a p p e n st ob eo n eo ft h ec h a r a c t e r sf i l t e r e do u t . # F a i l u r et od os og i v e sa ne r r o rm e s s a g e .( T r yi t . ) d o n e e x i t$ ? # E x e r c i s e( e a s y ) : # # C o n v e r tt h i ss c r i p tt ot a k ec o m m a n d l i n ep a r a m e t e r s # +f o r$ d i r e c t o r ya n d$ f s t r i n g .

A final example of [ l i s t ]/ command substitution, but this time the "command" is a function.

g e n e r a t e _ l i s t( ) { e c h o" o n et w ot h r e e " } f o rw o r di n$ ( g e n e r a t e _ l i s t ) #L e t" w o r d "g r a bo u t p u to ff u n c t i o n . d o e c h o" $ w o r d " d o n e #o n e #t w o #t h r e e

The output of a for loop may be piped to a command or commands. Example 11-10. Listing the symbolic links in a directory
# ! / b i n / b a s h #s y m l i n k s . s h :L i s t ss y m b o l i cl i n k si nad i r e c t o r y .

d i r e c t o r y = $ { 1 ` p w d ` } # D e f a u l t st oc u r r e n tw o r k i n gd i r e c t o r y , # +i fn o to t h e r w i s es p e c i f i e d . # E q u i v a l e n tt oc o d eb l o c kb e l o w . ##A R G S = 1 #E x p e c to n ec o m m a n d l i n ea r g u m e n t . # #i f[$ #n e" $ A R G S "] #I fn o t1a r g . . . #t h e n # d i r e c t o r y = ` p w d ` #c u r r e n tw o r k i n gd i r e c t o r y #e l s e # d i r e c t o r y = $ 1 #f i #e c h o" s y m b o l i cl i n k si nd i r e c t o r y\ " $ d i r e c t o r y \ " " f o rf i l ei n" $ (f i n d$ d i r e c t o r yt y p el) " #t y p el=s y m b o l i cl i n k s d o e c h o" $ f i l e " d o n e|s o r t #O t h e r w i s ef i l el i s ti su n s o r t e d . # S t r i c t l ys p e a k i n g ,al o o pi s n ' tr e a l l yn e c e s s a r yh e r e , # +s i n c et h eo u t p u to ft h e" f i n d "c o m m a n di se x p a n d e di n t oas i n g l ew o r d . # H o w e v e r ,i t ' se a s yt ou n d e r s t a n da n di l l u s t r a t i v et h i sw a y . # A sD o m i n i k' A e n e a s 'S c h n i t z e rp o i n t so u t , # +f a i l i n gt oq u o t e $ (f i n d$ d i r e c t o r yt y p el) # +w i l lc h o k eo nf i l e n a m e sw i t he m b e d d e dw h i t e s p a c e . # c o n t a i n i n gw h i t e s p a c e . e x i t0

##J e a nH e l o up r o p o s e st h ef o l l o w i n ga l t e r n a t i v e : e c h o" s y m b o l i cl i n k si nd i r e c t o r y\ " $ d i r e c t o r y \ " " #B a c k u po ft h ec u r r e n tI F S .O n ec a nn e v e rb et o oc a u t i o u s . O L D I F S = $ I F S I F S = : f o rf i l ei n$ ( f i n d$ d i r e c t o r yt y p elp r i n t f" % p $ I F S " ) d o # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ e c h o" $ f i l e " d o n e | s o r t

#A n d ,J a m e s" M i k e "C o n l e ys u g g e s t sm o d i f y i n gH e l o u ' sc o d et h u s l y : O L D I F S = $ I F S I F S = ' '#N u l lI F Sm e a n sn ow o r db r e a k s f o rf i l ei n$ (f i n d$ d i r e c t o r yt y p el) d o e c h o$ f i l e d o n e|s o r t # T h i sw o r k si nt h e" p a t h o l o g i c a l "c a s eo fad i r e c t o r yn a m eh a v i n g # +a ne m b e d d e dc o l o n . # " T h i sa l s of i x e st h ep a t h o l o g i c a lc a s eo ft h ed i r e c t o r yn a m eh a v i n g # + ac o l o n( o rs p a c ei ne a r l i e re x a m p l e )a sw e l l . "

The s t d o u tof a loop may be redirected to a file, as this slight modification to the previous example shows. Example 11-11. Symbolic links in a directory, saved to a file
# ! / b i n / b a s h #s y m l i n k s . s h :L i s t ss y m b o l i cl i n k si nad i r e c t o r y . O U T F I L E = s y m l i n k s . l i s t d i r e c t o r y = $ { 1 ` p w d ` } # D e f a u l t st oc u r r e n tw o r k i n gd i r e c t o r y , # +i fn o to t h e r w i s es p e c i f i e d . #s a v e f i l e

e c h o" s y m b o l i cl i n k si nd i r e c t o r y\ " $ d i r e c t o r y \ " ">" $ O U T F I L E " e c h o" "> >" $ O U T F I L E " f o rf i l ei n" $ (f i n d$ d i r e c t o r yt y p el) " d o e c h o" $ f i l e " d o n e|s o r t> >" $ O U T F I L E " # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ #e c h o" O u t p u tf i l e=$ O U T F I L E " e x i t$ ? #t y p el=s y m b o l i cl i n k s

#s t d o u to fl o o p r e d i r e c t e dt os a v ef i l e .

There is an alternative syntax to a for loop that will look very familiar to C programmers. This requires double parentheses. Example 11-12. A C-style for loop
# ! / b i n / b a s h #M u l t i p l ew a y st oc o u n tu pt o1 0 . e c h o #S t a n d a r ds y n t a x . f o rai n1234567891 0 d o e c h on" $ a" d o n e e c h o ;e c h o #+ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + #U s i n g" s e q ". . . f o rai n` s e q1 0 ` d o e c h on" $ a" d o n e

e c h o ;e c h o #+ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + #U s i n gb r a c ee x p a n s i o n. . . #B a s h ,v e r s i o n3 + . f o rai n{ 1 . . 1 0 } d o e c h on" $ a" d o n e e c h o ;e c h o #+ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + #N o w ,l e t ' sd ot h es a m e ,u s i n gC l i k es y n t a x . L I M I T = 1 0 f o r( ( a = 1 ;a< =L I M I T;a + + ) ) #D o u b l ep a r e n t h e s e s ,a n dn a k e d" L I M I T " d o e c h on" $ a" d o n e #Ac o n s t r u c tb o r r o w e df r o mk s h 9 3 . e c h o ;e c h o #+ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + #L e t ' su s et h eC" c o m m ao p e r a t o r "t oi n c r e m e n tt w ov a r i a b l e ss i m u l t a n e o u s l y . f o r( ( a = 1 ,b = 1 ;a< =L I M I T;a + + ,b + + ) ) d o #T h ec o m m ac o n c a t e n a t e so p e r a t i o n s . e c h on" $ a $ b" d o n e e c h o ;e c h o e x i t0

See also Example 27-16, Example 27-17, and Example A-6. --Now, a for loop used in a "real-life" context. Example 11-13. Using efax in batch mode
# ! / b i n / b a s h #F a x i n g( m u s th a v e' e f a x 'p a c k a g ei n s t a l l e d ) . E X P E C T E D _ A R G S = 2 E _ B A D A R G S = 8 5 M O D E M _ P O R T = " / d e v / t t y S 2 " # ^ ^ ^ ^ ^

#M a yb ed i f f e r e n to ny o u rm a c h i n e . P C M C I Am o d e mc a r dd e f a u l tp o r t .

i f[$ #n e$ E X P E C T E D _ A R G S] #C h e c kf o rp r o p e rn u m b e ro fc o m m a n d l i n ea r g s . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `p h o n e #t e x t f i l e " e x i t$ E _ B A D A R G S f i

i f[!f" $ 2 "] t h e n e c h o" F i l e$ 2i sn o tat e x tf i l e . " # F i l ei sn o tar e g u l a rf i l e ,o rd o e sn o te x i s t . e x i t$ E _ B A D A R G S

f i

f a xm a k e$ 2

# C r e a t ef a x f o r m a t t e df i l e sf r o mt e x tf i l e s .

f o rf i l ei n$ ( l s$ 2 . 0 * ) # C o n c a t e n a t et h ec o n v e r t e df i l e s . # U s e sw i l dc a r d( f i l e n a m e" g l o b b i n g " ) # +i nv a r i a b l el i s t . d o f i l = " $ f i l$ f i l e " d o n e e f a xd" $ M O D E M _ P O R T " t" T $ 1 "$ f i l #F i n a l l y ,d ot h ew o r k . #T r y i n ga d d i n g o 1 i fa b o v el i n ef a i l s .

# A sS . C .p o i n t so u t ,t h ef o r l o o pc a nb ee l i m i n a t e dw i t h # e f a xd/ d e v / t t y S 2o 1t" T $ 1 "$ 2 . 0 * # +b u ti t ' sn o tq u i t ea si n s t r u c t i v e[ g r i n ] . e x i t$ ? #A l s o ,e f a xs e n d sd i a g n o s t i cm e s s a g e st os t d o u t .

while This construct tests for a condition at the top of a loop, and keeps looping as long as that condition is true (returns a 0 exit status). In contrast to a for loop, a while loop finds use in situations where the number of loop repetitions is not known beforehand. while [ c o n d i t i o n] do c o m m a n d ( s ) ... done The bracket construct in a while loop is nothing more than our old friend, the test brackets used in an if/then test. In fact, a while loop can legally use the more versatile double-brackets construct (while [[ condition ]]). As is the case with for loops, placing the do on the same line as the condition test requires a semicolon. while [ c o n d i t i o n ] ; do Note that the test brackets are not mandatory in a while loop. See, for example, the getopts construct. Example 11-14. Simple while loop
# ! / b i n / b a s h v a r 0 = 0 L I M I T = 1 0 w h i l e[" $ v a r 0 "l t" $ L I M I T "] # ^ ^ #S p a c e s ,b e c a u s et h e s ea r e" t e s t b r a c k e t s "... d o e c h on" $ v a r 0" #ns u p p r e s s e sn e w l i n e . # ^ S p a c e ,t os e p a r a t ep r i n t e do u tn u m b e r s . v a r 0 = ` e x p r$ v a r 0+1 ` #v a r 0 = $ ( ( $ v a r 0 + 1 ) ) a l s ow o r k s . #v a r 0 = $ ( ( v a r 0+1 ) )a l s ow o r k s . #l e t" v a r 0+ =1 " a l s ow o r k s . #V a r i o u so t h e rm e t h o d sa l s ow o r k .

d o n e e c h o e x i t0

Example 11-15. Another while loop

# ! / b i n / b a s h e c h o #E q u i v a l e n tt o : w h i l e[" $ v a r 1 "! =" e n d "] #w h i l et e s t" $ v a r 1 "! =" e n d " d o e c h o" I n p u tv a r i a b l e# 1( e n dt oe x i t )" r e a dv a r 1 #N o t' r e a d$ v a r 1 '( w h y ? ) . e c h o" v a r i a b l e# 1=$ v a r 1 " #N e e dq u o t e sb e c a u s eo f" # "... #I fi n p u ti s' e n d ' ,e c h o e si th e r e . #D o e sn o tt e s tf o rt e r m i n a t i o nc o n d i t i o nu n t i lt o po fl o o p . e c h o d o n e e x i t0

A while loop may have multiple conditions. Only the final condition determines when the loop terminates. This necessitates a slightly different loop syntax, however. Example 11-16. while loop with multiple conditions
# ! / b i n / b a s h v a r 1 = u n s e t p r e v i o u s = $ v a r 1 w h i l ee c h o" p r e v i o u s v a r i a b l e=$ p r e v i o u s " e c h o p r e v i o u s = $ v a r 1 [" $ v a r 1 "! =e n d]#K e e p st r a c ko fw h a t$ v a r 1w a sp r e v i o u s l y . #F o u rc o n d i t i o n so n* w h i l e * ,b u to n l yt h ef i n a lo n ec o n t r o l sl o o p . #T h e* l a s t *e x i ts t a t u si st h eo n et h a tc o u n t s . d o e c h o" I n p u tv a r i a b l e# 1( e n dt oe x i t )" r e a dv a r 1 e c h o" v a r i a b l e# 1=$ v a r 1 " d o n e #T r yt of i g u r eo u th o wt h i sa l lw o r k s . #I t ' saw e eb i tt r i c k y . e x i t0

As with a for loop, a while loop may employ C-style syntax by using the double-parentheses construct (see also Example 8-5). Example 11-17. C-style syntax in a while loop
# ! / b i n / b a s h #w h l o o p c . s h :C o u n tt o1 0i na" w h i l e "l o o p . L I M I T = 1 0 a = 1 #1 0i t e r a t i o n s .

w h i l e[" $ a "l e$ L I M I T] d o e c h on" $ a" l e t" a + = 1 " d o n e #N os u r p r i s e s ,s of a r . e c h o ;e c h o #+ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + #N o w ,w e ' l lr e p e a tw i t hC l i k es y n t a x . ( ( a=1 ) ) #a = 1

#D o u b l ep a r e n t h e s e sp e r m i ts p a c ew h e ns e t t i n gav a r i a b l e ,a si nC . w h i l e( (a< =L I M I T) ) # D o u b l ep a r e n t h e s e s , d o # +a n dn o" $ "p r e c e d i n gv a r i a b l e s . e c h on" $ a" ( ( a+ =1 ) ) #l e t" a + = 1 " #Y e s ,i n d e e d . #D o u b l ep a r e n t h e s e sp e r m i ti n c r e m e n t i n gav a r i a b l ew i t hC l i k es y n t a x . d o n e e c h o #Ca n dJ a v ap r o g r a m m e r sc a nf e e lr i g h ta th o m ei nB a s h . e x i t0

Inside its test brackets, a while loop can call a function.


t = 0 c o n d i t i o n( ) { ( ( t + + ) ) i f[$ tl t5] t h e n r e t u r n0 #t r u e e l s e r e t u r n1 #f a l s e f i } w h i l ec o n d i t i o n # ^ ^ ^ ^ ^ ^ ^ ^ ^ # F u n c t i o nc a l l-f o u rl o o pi t e r a t i o n s . d o e c h o" S t i l lg o i n g :t=$ t " d o n e #S t i l lg o i n g :t=1 #S t i l lg o i n g :t=2 #S t i l lg o i n g :t=3 #S t i l lg o i n g :t=4

Similar to the if-test construct, a while loop can omit the test brackets.
w h i l ec o n d i t i o n d o c o m m a n d ( s ). . . d o n e

By coupling the power of the read command with a while loop, we get the handy while read construct, useful for reading and parsing files.
c a t$ f i l e n a m e| w h i l er e a dl i n e d o . . . d o n e #S u p p l yi n p u tf r o maf i l e . #A sl o n ga st h e r ei sa n o t h e rl i n et or e a d. . .

#= = = = = = = = = = =S n i p p e tf r o m" s d . s h "e x a m p l es c r i p t= = = = = = = = = =# w h i l er e a dv a l u e #R e a do n ed a t ap o i n ta tat i m e . d o r t = $ ( e c h o" s c a l e = $ S C ;$ r t+$ v a l u e "|b c ) ( (c t + +) ) d o n e

a m = $ ( e c h o" s c a l e = $ S C ;$ r t/$ c t "|b c ) e c h o$ a m ;r e t u r n$ c t #T h i sf u n c t i o n" r e t u r n s "T W Ov a l u e s ! # C a u t i o n :T h i sl i t t l et r i c kw i l ln o tw o r ki f$ c t>2 5 5 ! # T oh a n d l eal a r g e rn u m b e ro fd a t ap o i n t s , # +s i m p l yc o m m e n to u tt h e" r e t u r n$ c t "a b o v e . }< " $ d a t a f i l e " #F e e di nd a t af i l e .

A while loop may have its s t d i nredirected to a file by a < at its end. A while loop may have its s t d i nsupplied by a pipe. until This construct tests for a condition at the top of a loop, and keeps looping as long as that condition is false (opposite of while loop). until [ c o n d i t i o n i s t r u e] do c o m m a n d ( s ) ... done Note that an until loop tests for the terminating condition at the top of the loop, differing from a similar construct in some programming languages. As is the case with for loops, placing the do on the same line as the condition test requires a semicolon. until [ c o n d i t i o n i s t r u e ] ; do Example 11-18. until loop
# ! / b i n / b a s h E N D _ C O N D I T I O N = e n d u n t i l[" $ v a r 1 "=" $ E N D _ C O N D I T I O N "] #T e s t sc o n d i t i o nh e r e ,a tt o po fl o o p . d o e c h o" I n p u tv a r i a b l e# 1" e c h o" ( $ E N D _ C O N D I T I O Nt oe x i t ) " r e a dv a r 1 e c h o" v a r i a b l e# 1=$ v a r 1 " e c h o d o n e # #

# A sw i t h" f o r "a n d" w h i l e "l o o p s , # +a n" u n t i l "l o o pp e r m i t sC l i k et e s tc o n s t r u c t s . L I M I T = 1 0 v a r = 0 u n t i l( (v a r>L I M I T) ) d o #^ ^^ ^ ^ ^ N ob r a c k e t s ,n o$p r e f i x i n gv a r i a b l e s . e c h on" $ v a r" ( (v a r + +) ) d o n e #01234567891 0

e x i t0

How to choose between a for loop or a while loop or until loop? In C, you would typically use a for loop when the number of loop iterations is known beforehand. With Bash, however, the situation is fuzzier. The Bash for loop is more

loosely structured and more flexible than its equivalent in other languages. Therefore, feel free to use whatever type of loop gets the job done in the simplest way.

11.2. Nested Loops


A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. Of course, a break within either the inner or outer loop would interrupt this process. Example 11-19. Nested Loop
# ! / b i n / b a s h #n e s t e d l o o p . s h :N e s t e d" f o r "l o o p s . o u t e r = 1 #S e to u t e rl o o pc o u n t e r .

#B e g i n n i n go fo u t e rl o o p . f o rai n12345 d o e c h o" P a s s$ o u t e ri no u t e rl o o p . " e c h o" " i n n e r = 1 #R e s e ti n n e rl o o pc o u n t e r . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #B e g i n n i n go fi n n e rl o o p . f o rbi n12345 d o e c h o" P a s s$ i n n e ri ni n n e rl o o p . " l e t" i n n e r + = 1 " #I n c r e m e n ti n n e rl o o pc o u n t e r . d o n e #E n do fi n n e rl o o p . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = l e t" o u t e r + = 1 " #I n c r e m e n to u t e rl o o pc o u n t e r . e c h o #S p a c eb e t w e e no u t p u tb l o c k si np a s so fo u t e rl o o p . d o n e #E n do fo u t e rl o o p . e x i t0

See Example 27-11 for an illustration of nested while loops, and Example 27-13 to see a while loop nested inside an until loop.

11.3. Loop Control


Tournez cent tours, tournez mille tours, Tournez souvent et tournez toujours . . . --Verlaine, "Chevaux de bois" Commands affecting loop behavior break, continue The break and continue loop control commands [53] correspond exactly to their counterparts in other programming languages. The break command terminates the loop (breaks out of it), while continue causes a jump to the next

iteration of the loop, skipping all the remaining commands in that particular loop cycle. Example 11-20. Effects of break and continue in a loop
# ! / b i n / b a s h L I M I T = 1 9 #U p p e rl i m i t e c h o e c h o" P r i n t i n gN u m b e r s1t h r o u g h2 0( b u tn o t3a n d1 1 ) . " a = 0 w h i l e[$ al e" $ L I M I T "] d o a = $ ( ( $ a + 1 ) ) i f[" $ a "e q3]| |[" $ a "e q1 1] #E x c l u d e s3a n d1 1 . t h e n c o n t i n u e #S k i pr e s to ft h i sp a r t i c u l a rl o o pi t e r a t i o n . f i e c h on" $ a" d o n e #T h i sw i l ln o te x e c u t ef o r3a n d1 1 .

#E x e r c i s e : #W h yd o e st h el o o pp r i n tu pt o2 0 ? e c h o ;e c h o e c h oP r i n t i n gN u m b e r s1t h r o u g h2 0 ,b u ts o m e t h i n gh a p p e n sa f t e r2 . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #S a m el o o p ,b u ts u b s t i t u t i n g' b r e a k 'f o r' c o n t i n u e ' . a = 0 w h i l e[" $ a "l e" $ L I M I T "] d o a = $ ( ( $ a + 1 ) ) i f[" $ a "g t2] t h e n b r e a k #S k i pe n t i r er e s to fl o o p . f i e c h on" $ a" d o n e e c h o ;e c h o ;e c h o e x i t0

The break command may optionally take a parameter. A plain break terminates only the innermost loop in which it is embedded, but a break N breaks out of Nlevels of loop. Example 11-21. Breaking out of multiple loop levels
# ! / b i n / b a s h #b r e a k l e v e l s . s h :B r e a k i n go u to fl o o p s . #" b r e a kN "b r e a k so u to fNl e v e ll o o p s . f o ro u t e r l o o pi n12345 d o e c h on" G r o u p$ o u t e r l o o p :

"

#f o ri n n e r l o o pi n12345 d o e c h on" $ i n n e r l o o p" i f[" $ i n n e r l o o p "e q3] t h e n b r e a k #T r y b r e a k2 t os e ew h a th a p p e n s . #( " B r e a k s "o u to fb o t hi n n e ra n do u t e rl o o p s . ) f i d o n e #e c h o d o n e e c h o e x i t0

The continue command, similar to break, optionally takes a parameter. A plain continue cuts short the current iteration within its loop and begins the next. A continue N terminates all remaining iterations at its loop level and continues with the next iteration at the loop, Nlevels above. Example 11-22. Continuing at a higher loop level
# ! / b i n / b a s h #T h e" c o n t i n u eN "c o m m a n d ,c o n t i n u i n ga tt h eN t hl e v e ll o o p . f o ro u t e ri nII II I II VV d o e c h o ;e c h on" G r o u p$ o u t e r :" #o u t e rl o o p

#f o ri n n e ri n1234567891 0 #i n n e rl o o p d o i f[ [" $ i n n e r "e q7& &" $ o u t e r "=" I I I "] ] t h e n c o n t i n u e2 #C o n t i n u ea tl o o po n2 n dl e v e l ,t h a ti s" o u t e rl o o p " . #R e p l a c ea b o v el i n ew i t has i m p l e" c o n t i n u e " #t os e en o r m a ll o o pb e h a v i o r . f i e c h on" $ i n n e r" #7891 0w i l ln o te c h oo n" G r o u pI I I . " d o n e #d o n e e c h o ;e c h o #E x e r c i s e : #C o m eu pw i t ham e a n i n g f u lu s ef o r" c o n t i n u eN "i nas c r i p t . e x i t0

Example 11-23. Using continue N in an actual task


#A l b e r tR e i n e rg i v e sa ne x a m p l eo fh o wt ou s e" c o n t i n u eN " : ## S u p p o s eIh a v eal a r g en u m b e ro fj o b st h a tn e e dt ob er u n ,w i t h # +a n yd a t at h a ti st ob et r e a t e di nf i l e so fag i v e nn a m ep a t t e r n # +i nad i r e c t o r y .T h e r ea r es e v e r a lm a c h i n e st h a ta c c e s s # +t h i sd i r e c t o r y ,a n dIw a n tt od i s t r i b u t et h ew o r ko v e rt h e s e

# +d i f f e r e n tb o x e n . # T h e nIu s u a l l yn o h u ps o m e t h i n gl i k et h ef o l l o w i n go ne v e r yb o x : w h i l et r u e d o f o rni n. i s o . * d o [" $ n "=" . i s o . o p t s "]& &c o n t i n u e b e t a = $ { n # . i s o . } [r. I s o . $ b e t a]& &c o n t i n u e [r. l o c k . $ b e t a]& &s l e e p1 0& &c o n t i n u e l o c k f i l er 0. l o c k . $ b e t a| |c o n t i n u e e c h on" $ b e t a :"` d a t e ` r u n i s o t h e r m$ b e t a d a t e l sa l F. I s o . $ b e t a [r. I s o . $ b e t a]& &r mf. l o c k . $ b e t a c o n t i n u e2 d o n e b r e a k d o n e e x i t0 # T h ed e t a i l s ,i np a r t i c u l a rt h es l e e pN ,a r ep a r t i c u l a rt om y # +a p p l i c a t i o n ,b u tt h eg e n e r a lp a t t e r ni s : w h i l et r u e d o f o rj o bi n{ p a t t e r n } d o { j o ba l r e a d yd o n eo rr u n n i n g }& &c o n t i n u e { m a r kj o ba sr u n n i n g ,d oj o b ,m a r kj o ba sd o n e } c o n t i n u e2 d o n e b r e a k #O rs o m e t h i n gl i k e` s l e e p6 0 0 't oa v o i dt e r m i n a t i o n . d o n e # T h i sw a yt h es c r i p tw i l ls t o po n l yw h e nt h e r ea r en om o r ej o b st od o # +( i n c l u d i n gj o b st h a tw e r ea d d e dd u r i n gr u n t i m e ) .T h r o u g ht h eu s e # +o fa p p r o p r i a t el o c k f i l e si tc a nb er u no ns e v e r a lm a c h i n e s # +c o n c u r r e n t l yw i t h o u td u p l i c a t i o no fc a l c u l a t i o n s[ w h i c hr u nac o u p l e # +o fh o u r si nm yc a s e ,s oIr e a l l yw a n tt oa v o i dt h i s ] .A l s o ,a ss e a r c h # +a l w a y ss t a r t sa g a i nf r o mt h eb e g i n n i n g ,o n ec a ne n c o d ep r i o r i t i e si n # +t h ef i l en a m e s .O fc o u r s e ,o n ec o u l da l s od ot h i sw i t h o u t` c o n t i n u e2 ' , # +b u tt h e no n ew o u l dh a v et oa c t u a l l yc h e c kw h e t h e ro rn o ts o m ej o b # +w a sd o n e( s ot h a tw es h o u l di m m e d i a t e l yl o o kf o rt h en e x tj o b )o rn o t # +( i nw h i c hc a s ew et e r m i n a t eo rs l e e pf o ral o n gt i m eb e f o r ec h e c k i n g # +f o ran e wj o b ) .

The continue N construct is difficult to understand and tricky to use in any meaningful context. It is probably best avoided.

11.4. Testing and Branching


The case and select constructs are technically not loops, since they do not iterate the execution of a code block. Like loops, however, they direct program flow according to conditions at the top or bottom of the block. Controlling program flow in a code block case (in) / esac The case construct is the shell scripting analog to s w i t c hin C/C++. It permits branching to one of a number of code

blocks, depending on condition tests. It serves as a kind of shorthand for multiple if/then/else statements and is an appropriate tool for creating menus. case "$v a r i a b l e " in "$c o n d i t i o n 1 ") c o m m a n d ... ;; "$c o n d i t i o n 2 ") c o m m a n d ... ;;

esac Quoting the variables is not mandatory, since word splitting does not take place. Each test line ends with a right paren ). [54] Each condition block ends with a double semicolon ;;. If a condition tests true, then the associated commands execute and the case block terminates. The entire case block ends with an esac (case spelled backwards). Example 11-24. Using case
# ! / b i n / b a s h #T e s t i n gr a n g e so fc h a r a c t e r s . e c h o ;e c h o" H i tak e y ,t h e nh i tr e t u r n . " r e a dK e y p r e s s c a s e" $ K e y p r e s s "i n [ [ : l o w e r : ] ] )e c h o" L o w e r c a s el e t t e r " ; ; [ [ : u p p e r : ] ] )e c h o" U p p e r c a s el e t t e r " ; ; [ 0 9 ] )e c h o" D i g i t " ; ; * )e c h o" P u n c t u a t i o n ,w h i t e s p a c e ,o ro t h e r " ; ; e s a c # A l l o w sr a n g e so fc h a r a c t e r si n[ s q u a r eb r a c k e t s ] , # +o rP O S I Xr a n g e si n[ [ d o u b l es q u a r eb r a c k e t s . # I nt h ef i r s tv e r s i o no ft h i se x a m p l e , # +t h et e s t sf o rl o w e r c a s ea n du p p e r c a s ec h a r a c t e r sw e r e # +[ a z ]a n d[ A Z ] . # T h i sn ol o n g e rw o r k si nc e r t a i nl o c a l e sa n d / o rL i n u xd i s t r o s . # P O S I Xi sm o r ep o r t a b l e . # T h a n k st oF r a n kW a n gf o rp o i n t i n gt h i so u t . # E x e r c i s e : # # A st h es c r i p ts t a n d s ,i ta c c e p t sas i n g l ek e y s t r o k e ,t h e nt e r m i n a t e s . # C h a n g et h es c r i p ts oi ta c c e p t sr e p e a t e di n p u t , # +r e p o r t so ne a c hk e y s t r o k e ,a n dt e r m i n a t e so n l yw h e n" X "i sh i t . # H i n t :e n c l o s ee v e r y t h i n gi na" w h i l e "l o o p . e x i t0

Example 11-25. Creating menus using case


# ! / b i n / b a s h

#C r u d ea d d r e s sd a t a b a s e c l e a r#C l e a rt h es c r e e n . e c h o" C o n t a c tL i s t " e c h o" -" e c h o" C h o o s eo n eo ft h ef o l l o w i n gp e r s o n s : " e c h o e c h o" [ E ] v a n s ,R o l a n d " e c h o" [ J ] o n e s ,M i l d r e d " e c h o" [ S ] m i t h ,J u l i e " e c h o" [ Z ] a n e ,M o r r i s " e c h o r e a dp e r s o n c a s e" $ p e r s o n "i n #N o t ev a r i a b l ei sq u o t e d . " E "|" e ") #A c c e p tu p p e ro rl o w e r c a s ei n p u t . e c h o e c h o" R o l a n dE v a n s " e c h o" 4 3 2 1F l a s hD r . " e c h o" H a r d s c r a b b l e ,C O8 0 7 5 3 " e c h o" ( 3 0 3 )7 3 4 9 8 7 4 " e c h o" ( 3 0 3 )7 3 4 9 8 9 2f a x " e c h o" r e v a n s @ z z y . n e t " e c h o" B u s i n e s sp a r t n e r&o l df r i e n d " ; ; #N o t ed o u b l es e m i c o l o nt ot e r m i n a t ee a c ho p t i o n . " J "|" j ") e c h o e c h o" M i l d r e dJ o n e s " e c h o" 2 4 9E .7 t hS t . ,A p t .1 9 " e c h o" N e wY o r k ,N Y1 0 0 0 9 " e c h o" ( 2 1 2 )5 3 3 2 8 1 4 " e c h o" ( 2 1 2 )5 3 3 9 9 7 2f a x " e c h o" m i l l i e j @ l o i s a i d a . c o m " e c h o" E x g i r l f r i e n d " e c h o" B i r t h d a y :F e b .1 1 " ; ; #A d di n f of o rS m i t h&Z a n el a t e r . *) #D e f a u l to p t i o n . #E m p t yi n p u t( h i t t i n gR E T U R N )f i t sh e r e ,t o o . e c h o e c h o" N o ty e ti nd a t a b a s e . " ; ; e s a c e c h o # E x e r c i s e : # # C h a n g et h es c r i p ts oi ta c c e p t sm u l t i p l ei n p u t s , # +i n s t e a do ft e r m i n a t i n ga f t e rd i s p l a y i n gj u s to n ea d d r e s s . e x i t0

An exceptionally clever use of case involves testing for command-line parameters.


# !/ b i n / b a s h

c a s e" $ 1 "i n " " )e c h o" U s a g e :$ { 0 # # * / }< f i l e n a m e > " ;e x i t$ E _ P A R A M ; ; #N oc o m m a n d l i n ep a r a m e t e r s , #o rf i r s tp a r a m e t e re m p t y . #N o t et h a t$ { 0 # # * / }i s$ { v a r # # p a t t e r n }p a r a ms u b s t i t u t i o n . #N e tr e s u l ti s$ 0 . * )F I L E N A M E = . / $ 1 ; ; # I ff i l e n a m ep a s s e da sa r g u m e n t( $ 1 ) # +s t a r t sw i t had a s h , # +r e p l a c ei tw i t h. / $ 1 # +s of u r t h e rc o m m a n d sd o n ' ti n t e r p r e ti t # +a sa no p t i o n . #O t h e r w i s e ,$ 1 .

*)F I L E N A M E = $ 1 ; ; e s a c

Here is a more straightforward example of command-line parameter handling:


# !/ b i n / b a s h

w h i l e[$ #g t0] ;d o #U n t i ly o ur u no u to fp a r a m e t e r s... c a s e" $ 1 "i n d | d e b u g ) #" d "o r" d e b u g "p a r a m e t e r ? D E B U G = 1 ; ; c | c o n f ) C O N F F I L E = " $ 2 " s h i f t i f[!f$ C O N F F I L E] ;t h e n e c h o" E r r o r :S u p p l i e df i l ed o e s n ' te x i s t ! " e x i t$ E _ C O N F F I L E #F i l en o tf o u n de r r o r . f i ; ; e s a c s h i f t #C h e c kn e x ts e to fp a r a m e t e r s . d o n e # F r o mS t e f a n oF a l s e t t o ' s" L o g 2 R o t "s c r i p t , # +p a r to fh i s" r o t t l o g "p a c k a g e . # U s e dw i t hp e r m i s s i o n .

Example 11-26. Using command substitution to generate the case variable


# ! / b i n / b a s h #c a s e c m d . s h :U s i n gc o m m a n ds u b s t i t u t i o nt og e n e r a t ea" c a s e "v a r i a b l e . c a s e$ (a r c h)i n #$ (a r c h)r e t u r n sm a c h i n ea r c h i t e c t u r e . #E q u i v a l e n tt o' u n a m em '. . . i 3 8 6)e c h o" 8 0 3 8 6 b a s e dm a c h i n e " ; ; i 4 8 6)e c h o" 8 0 4 8 6 b a s e dm a c h i n e " ; ; i 5 8 6)e c h o" P e n t i u m b a s e dm a c h i n e " ; ; i 6 8 6)e c h o" P e n t i u m 2 + b a s e dm a c h i n e " ; ; * )e c h o" O t h e rt y p eo fm a c h i n e " ; ; e s a c e x i t0

A case construct can filter strings for globbing patterns. Example 11-27. Simple string matching
# ! / b i n / b a s h #m a t c h s t r i n g . s h :S i m p l es t r i n gm a t c h i n g # u s i n ga' c a s e 'c o n s t r u c t . m a t c h _ s t r i n g( )

{#E x a c ts t r i n gm a t c h . M A T C H = 0 E _ N O M A T C H = 9 0 P A R A M S = 2 #F u n c t i o nr e q u i r e s2a r g u m e n t s . E _ B A D _ P A R A M S = 9 1 [$ #e q$ P A R A M S]| |r e t u r n$ E _ B A D _ P A R A M S c a s e" $ 1 "i n " $ 2 " )r e t u r n$ M A T C H ; ; * )r e t u r n$ E _ N O M A T C H ; ; e s a c }

a = o n e b = t w o c = t h r e e d = t w o

m a t c h _ s t r i n g$ a e c h o$ ?

#w r o n gn u m b e ro fp a r a m e t e r s #9 1

m a t c h _ s t r i n g$ a$ b #n om a t c h e c h o$ ? #9 0 m a t c h _ s t r i n g$ b$ d #m a t c h e c h o$ ? #0

e x i t0

Example 11-28. Checking for alphabetic input


# ! / b i n / b a s h #i s a l p h a . s h :U s i n ga" c a s e "s t r u c t u r et of i l t e ras t r i n g . S U C C E S S = 0 F A I L U R E = 1

# W a sF A I L U R E = 1 , # +b u tB a s hn ol o n g e ra l l o w sn e g a t i v er e t u r nv a l u e .

i s a l p h a( ) #T e s t sw h e t h e r* f i r s tc h a r a c t e r *o fi n p u ts t r i n gi sa l p h a b e t i c . { i f[z" $ 1 "] #N oa r g u m e n tp a s s e d ? t h e n r e t u r n$ F A I L U R E f i c a s e" $ 1 "i n [ a z A Z ] * )r e t u r n$ S U C C E S S ; ; #B e g i n sw i t hal e t t e r ? * )r e t u r n$ F A I L U R E ; ; e s a c } #C o m p a r et h i sw i t h" i s a l p h a( ) "f u n c t i o ni nC .

i s a l p h a 2( ) #T e s t sw h e t h e r* e n t i r es t r i n g *i sa l p h a b e t i c . { [$ #e q1]| |r e t u r n$ F A I L U R E c a s e$ 1i n * [ ! a z A Z ] * | " " )r e t u r n$ F A I L U R E ; ; * )r e t u r n$ S U C C E S S ; ; e s a c } i s d i g i t( ) #T e s t sw h e t h e r* e n t i r es t r i n g *i sn u m e r i c a l .

#I no t h e rw o r d s ,t e s t sf o ri n t e g e rv a r i a b l e . [$ #e q1]| |r e t u r n$ F A I L U R E c a s e$ 1i n * [ ! 0 9 ] * | " " )r e t u r n$ F A I L U R E ; ; * )r e t u r n$ S U C C E S S ; ; e s a c

c h e c k _ v a r( ) #F r o n t e n dt oi s a l p h a( ) . { i fi s a l p h a" $ @ " t h e n e c h o" \ " $ * \ "b e g i n sw i t ha na l p h ac h a r a c t e r . " i fi s a l p h a 2" $ @ " t h e n #N op o i n ti nt e s t i n gi ff i r s tc h a ri sn o n a l p h a . e c h o" \ " $ * \ "c o n t a i n so n l ya l p h ac h a r a c t e r s . " e l s e e c h o" \ " $ * \ "c o n t a i n sa tl e a s to n en o n a l p h ac h a r a c t e r . " f i e l s e e c h o" \ " $ * \ "b e g i n sw i t han o n a l p h ac h a r a c t e r . " #A l s o" n o n a l p h a "i fn oa r g u m e n tp a s s e d . f i e c h o } d i g i t _ c h e c k( ) #F r o n t e n dt oi s d i g i t( ) . { i fi s d i g i t" $ @ " t h e n e c h o" \ " $ * \ "c o n t a i n so n l yd i g i t s[ 0-9 ] . " e l s e e c h o" \ " $ * \ "h a sa tl e a s to n en o n d i g i tc h a r a c t e r . " f i e c h o } a = 2 3 s k i d o o b = H 3 l l o c = W h a t ? d = W h a t ? e = $ ( e c h o$ b ) f = A b c D e f g = 2 7 2 3 4 h = 2 7 a 3 4 i = 2 7 . 3 4

#C o m m a n ds u b s t i t u t i o n .

c h e c k _ v a r$ a c h e c k _ v a r$ b c h e c k _ v a r$ c c h e c k _ v a r$ d c h e c k _ v a r$ e c h e c k _ v a r$ f c h e c k _ v a r #N oa r g u m e n tp a s s e d ,s ow h a th a p p e n s ? # d i g i t _ c h e c k$ g d i g i t _ c h e c k$ h d i g i t _ c h e c k$ i

e x i t0

#S c r i p ti m p r o v e db yS . C .

#E x e r c i s e : ## W r i t ea n' i s f l o a t( ) 'f u n c t i o nt h a tt e s t sf o rf l o a t i n gp o i n tn u m b e r s . # H i n t :T h ef u n c t i o nd u p l i c a t e s' i s d i g i t( ) ' , # +b u ta d d sat e s tf o ram a n d a t o r yd e c i m a lp o i n t .

select The select construct, adopted from the Korn Shell, is yet another tool for building menus. select v a r i a b l e[in l i s t ] do c o m m a n d ... break done This prompts the user to enter one of the choices presented in the variable list. Note that select uses the $ P S 3prompt (# ? ) by default, but this may be changed. Example 11-29. Creating menus using select
# ! / b i n / b a s h P S 3 = ' C h o o s ey o u rf a v o r i t ev e g e t a b l e :'#S e t st h ep r o m p ts t r i n g . #O t h e r w i s ei td e f a u l t st o# ?. e c h o s e l e c tv e g e t a b l ei n" b e a n s "" c a r r o t s "" p o t a t o e s "" o n i o n s "" r u t a b a g a s " d o e c h o e c h o" Y o u rf a v o r i t ev e g g i ei s$ v e g e t a b l e . " e c h o" Y u c k ! " e c h o b r e a k #W h a th a p p e n si ft h e r ei sn o' b r e a k 'h e r e ? d o n e e x i t #E x e r c i s e : ## F i xt h i ss c r i p tt oa c c e p tu s e ri n p u tn o ts p e c i f i e di n # +t h e" s e l e c t "s t a t e m e n t . # F o re x a m p l e ,i ft h eu s e ri n p u t s" p e a s , " # +t h es c r i p tw o u l dr e s p o n d" S o r r y .T h a ti sn o to nt h em e n u . "

If i nl i s tis omitted, then select uses the list of command line arguments ($ @ ) passed to the script or the function containing the select construct. Compare this to the behavior of a for v a r i a b l e[in l i s t ] construct with the i nl i s tomitted. Example 11-30. Creating menus using select in a function
# ! / b i n / b a s h P S 3 = ' C h o o s ey o u rf a v o r i t ev e g e t a b l e :' e c h o c h o i c e _ o f ( ) {

s e l e c tv e g e t a b l e #[ i nl i s t ]o m i t t e d ,s o' s e l e c t 'u s e sa r g u m e n t sp a s s e dt of u n c t i o n . d o e c h o e c h o" Y o u rf a v o r i t ev e g g i ei s$ v e g e t a b l e . " e c h o" Y u c k ! " e c h o b r e a k d o n e } c h o i c e _ o fb e a n sr i c ec a r r o t sr a d i s h e sr u t a b a g as p i n a c h # $ 1 $ 2 $ 3 $ 4 $ 5 $ 6 # p a s s e dt oc h o i c e _ o f ( )f u n c t i o n e x i t0

See also Example 37-3.

Chapter 12. Command Substitution


Command substitution reassigns the output of a command [55] or even multiple commands; it literally plugs the command output into another context. [56] The classic form of command substitution uses backquotes (`...`). Commands within backquotes (backticks) generate command-line text.
s c r i p t _ n a m e = ` b a s e n a m e$ 0 ` e c h o" T h en a m eo ft h i ss c r i p ti s$ s c r i p t _ n a m e . "

The output of commands can be used as arguments to another command, to set a variable, and even for generating the argument list in a for loop.
r m` c a tf i l e n a m e ` #" f i l e n a m e "c o n t a i n sal i s to ff i l e st od e l e t e . # #S .C .p o i n t so u tt h a t" a r gl i s tt o ol o n g "e r r o rm i g h tr e s u l t . #B e t t e ri s x a r g sr m-<f i l e n a m e #(-c o v e r st h o s ec a s e sw h e r e" f i l e n a m e "b e g i n sw i t ha" ") t e x t f i l e _ l i s t i n g = ` l s* . t x t ` #V a r i a b l ec o n t a i n sn a m e so fa l l* . t x tf i l e si nc u r r e n tw o r k i n gd i r e c t o r y . e c h o$ t e x t f i l e _ l i s t i n g t e x t f i l e _ l i s t i n g 2 = $ ( l s* . t x t ) e c h o$ t e x t f i l e _ l i s t i n g 2 #S a m er e s u l t . #T h ea l t e r n a t i v ef o r mo fc o m m a n ds u b s t i t u t i o n .

#Ap o s s i b l ep r o b l e mw i t hp u t t i n gal i s to ff i l e si n t oas i n g l es t r i n g #i st h a tan e w l i n em a yc r e e pi n . # #As a f e rw a yt oa s s i g nal i s to ff i l e st oap a r a m e t e ri sw i t ha na r r a y . # s h o p tsn u l l g l o b #I fn om a t c h ,f i l e n a m ee x p a n d st on o t h i n g . # t e x t f i l e _ l i s t i n g = (* . t x t) # #T h a n k s ,S . C .

Command substitution invokes a subshell. Command substitution may result in word splitting.
C O M M A N D` e c h oab ` C O M M A N D" ` e c h oab ` " #2a r g s :aa n db #1a r g :" ab "

C O M M A N D` e c h o ` C O M M A N D" ` e c h o ` "

#n oa r g #o n ee m p t ya r g

#T h a n k s ,S . C .

Even when there is no word splitting, command substitution can remove trailing newlines.
#c d" ` p w d ` " #T h i ss h o u l da l w a y sw o r k . #H o w e v e r . . . m k d i r' d i rw i t ht r a i l i n gn e w l i n e ' c d' d i rw i t ht r a i l i n gn e w l i n e ' c d" ` p w d ` " #E r r o rm e s s a g e : #b a s h :c d :/ t m p / f i l ew i t ht r a i l i n gn e w l i n e :N os u c hf i l eo rd i r e c t o r y c d" $ P W D " #W o r k sf i n e .

o l d _ t t y _ s e t t i n g = $ ( s t t yg ) e c h o" H i tak e y" s t t yi c a n o ne c h o

#S a v eo l dt e r m i n a ls e t t i n g .

#D i s a b l e" c a n o n i c a l "m o d ef o rt e r m i n a l . #A l s o ,d i s a b l e* l o c a l *e c h o . k e y = $ ( d db s = 1c o u n t = 12 >/ d e v / n u l l ) #U s i n g' d d 't og e tak e y p r e s s . s t t y" $ o l d _ t t y _ s e t t i n g " #R e s t o r eo l ds e t t i n g . e c h o" Y o uh i t$ { # k e y }k e y . " #$ { # v a r i a b l e }=n u m b e ro fc h a r a c t e r si n$ v a r i a b l e # #H i ta n yk e ye x c e p tR E T U R N ,a n dt h eo u t p u ti s" Y o uh i t1k e y . " #H i tR E T U R N ,a n di t ' s" Y o uh i t0k e y . " #T h en e w l i n eg e t se a t e ni nt h ec o m m a n ds u b s t i t u t i o n . # C o d es n i p p e tb yS t p h a n eC h a z e l a s .

Using echo to output an unquoted variable set with command substitution removes trailing newlines characters from the output of the reassigned command(s). This can cause unpleasant surprises.
d i r _ l i s t i n g = ` l sl ` e c h o$ d i r _ l i s t i n g #u n q u o t e d

#E x p e c t i n gan i c e l yo r d e r e dd i r e c t o r yl i s t i n g . #H o w e v e r ,w h a ty o ug e ti s : #t o t a l3r w r w r -1b o z ob o z o3 0M a y1 31 7 : 1 51 . t x tr w r w r -1b o z o #b o z o5 1M a y1 52 0 : 5 7t 2 . s hr w x r x r x1b o z ob o z o2 1 7M a r52 1 : 1 3w i . s h #T h en e w l i n e sd i s a p p e a r e d .

e c h o" $ d i r _ l i s t i n g " #q u o t e d #r w r w r 1b o z o 3 0M a y1 31 7 : 1 51 . t x t #r w r w r 1b o z o 5 1M a y1 52 0 : 5 7t 2 . s h #r w x r x r x 1b o z o 2 1 7M a r 52 1 : 1 3w i . s h

Command substitution even permits setting a variable to the contents of a file, using either redirection or the cat command.
v a r i a b l e 1 = ` < f i l e 1 ` v a r i a b l e 2 = ` c a tf i l e 2 ` # S e t" v a r i a b l e 1 "t oc o n t e n t so f" f i l e 1 " . # S e t" v a r i a b l e 2 "t oc o n t e n t so f" f i l e 2 " . # T h i s ,h o w e v e r ,f o r k san e wp r o c e s s ,

# +s ot h el i n eo fc o d ee x e c u t e ss l o w e rt h a nt h ea b o v ev e r s i o n . # N o t et h a tt h ev a r i a b l e sm a yc o n t a i ne m b e d d e dw h i t e s p a c e , # +o re v e n( h o r r o r s ) ,c o n t r o lc h a r a c t e r s . # I ti sn o tn e c e s s a r yt oe x p l i c i t l ya s s i g nav a r i a b l e . e c h o" `< $ 0 ` " #E c h o e st h es c r i p ti t s e l ft os t d o u t . # E x c e r p t sf r o ms y s t e mf i l e ,/ e t c / r c . d / r c . s y s i n i t # +( o naR e dH a tL i n u xi n s t a l l a t i o n )

i f[f/ f s c k o p t i o n s] ;t h e n f s c k o p t i o n s = ` c a t/ f s c k o p t i o n s ` . . . f i # # i f[e" / p r o c / i d e / $ { d i s k [ $ d e v i c e ] } / m e d i a "];t h e n h d m e d i a = ` c a t/ p r o c / i d e / $ { d i s k [ $ d e v i c e ] } / m e d i a ` . . . f i # # i f[!n" ` u n a m er|g r e p-" " ` "] ;t h e n k t a g = " ` c a t/ p r o c / v e r s i o n ` " . . . f i # # i f[$ u s b=" 1 "] ;t h e n s l e e p5 m o u s e o u t p u t = ` c a t/ p r o c / b u s / u s b / d e v i c e s2 > / d e v / n u l l | g r e pE" ^ I . * C l s = 0 3 . * P r o t = 0 2 " ` k b d o u t p u t = ` c a t/ p r o c / b u s / u s b / d e v i c e s2 > / d e v / n u l l | g r e pE" ^ I . * C l s = 0 3 . * P r o t = 0 1 " ` . . . f i

Do not set a variable to the contents of a long text file unless you have a very good reason for doing so. Do not set a variable to the contents of a binary file, even as a joke. Example 12-1. Stupid script tricks
# ! / b i n / b a s h #s t u p i d s c r i p t t r i c k s . s h :D o n ' tt r yt h i sa th o m e ,f o l k s . #F r o m" S t u p i dS c r i p tT r i c k s , "V o l u m eI . e x i t9 9 # # #C o m m e n to u tt h i sl i n ei fy o ud a r e . d a n g e r o u s _ v a r i a b l e = ` c a t/ b o o t / v m l i n u z ` #T h ec o m p r e s s e dL i n u xk e r n e li t s e l f .

e c h o" s t r i n g l e n g t ho f\ $ d a n g e r o u s _ v a r i a b l e=$ { # d a n g e r o u s _ v a r i a b l e } " #s t r i n g l e n g t ho f$ d a n g e r o u s _ v a r i a b l e=7 9 4 1 5 1 #( N e w e rk e r n e l sa r eb i g g e r . ) #D o e sn o tg i v es a m ec o u n ta s' w cc/ b o o t / v m l i n u z ' . #e c h o" $ d a n g e r o u s _ v a r i a b l e " #D o n ' tt r yt h i s !I tw o u l dh a n gt h es c r i p t .

# T h ed o c u m e n ta u t h o ri sa w a r eo fn ou s e f u la p p l i c a t i o n sf o r # +s e t t i n gav a r i a b l et ot h ec o n t e n t so fab i n a r yf i l e . e x i t0

Notice that a buffer overrun does not occur. This is one instance where an interpreted language, such as Bash, provides more protection from programmer mistakes than a compiled language.

Command substitution permits setting a variable to the output of a loop. The key to this is grabbing the output of an echo command within the loop. Example 12-2. Generating a variable from a loop
# ! / b i n / b a s h #c s u b l o o p . s h :S e t t i n gav a r i a b l et ot h eo u t p u to fal o o p . v a r i a b l e 1 = ` f o rii n12345 d o e c h on" $ i " # T h e' e c h o 'c o m m a n di sc r i t i c a l d o n e ` # +t oc o m m a n ds u b s t i t u t i o nh e r e . e c h o" v a r i a b l e 1=$ v a r i a b l e 1 " #v a r i a b l e 1=1 2 3 4 5

i = 0 v a r i a b l e 2 = ` w h i l e[" $ i "l t1 0] d o e c h on" $ i " #A g a i n ,t h en e c e s s a r y' e c h o ' . l e t" i+ =1 " #I n c r e m e n t . d o n e ` e c h o" v a r i a b l e 2=$ v a r i a b l e 2 " #v a r i a b l e 2=0 1 2 3 4 5 6 7 8 9 # D e m o n s t r a t e st h a ti t ' sp o s s i b l et oe m b e dal o o p # +w i t h i nav a r i a b l ed e c l a r a t i o n . e x i t0

Command substitution makes it possible to extend the toolset available to Bash. It is simply a matter of writing a program or script that outputs to s t d o u t(like a well-behaved UNIX tool should) and assigning that output to a variable.
# i n c l u d e< s t d i o . h > / * " H e l l o ,w o r l d . "Cp r o g r a m * / i n tm a i n ( ) { p r i n t f (" H e l l o ,w o r l d . \ n ") ; r e t u r n( 0 ) ; } b a s h $g c coh e l l oh e l l o . c

# ! / b i n / b a s h #h e l l o . s h g r e e t i n g = ` . / h e l l o ` e c h o$ g r e e t i n g b a s h $s hh e l l o . s h H e l l o ,w o r l d .

The $(...) form has superseded backticks for command substitution.


o u t p u t = $ ( s e dn/ " $ 1 " / p$ f i l e ) #F r o m" g r p . s h " e x a m p l e .

#S e t t i n gav a r i a b l et ot h ec o n t e n t so fat e x tf i l e . F i l e _ c o n t e n t s 1 = $ ( c a t$ f i l e 1 ) F i l e _ c o n t e n t s 2 = $ ( < $ f i l e 2 ) #B a s hp e r m i t st h i sa l s o .

The $(...) form of command substitution treats a double backslash in a different way than `...`.
b a s h $e c h o` e c h o\ \ `

b a s h $e c h o$ ( e c h o\ \ ) \

The $(...) form of command substitution permits nesting. [57]


w o r d _ c o u n t = $ (w cw$ ( e c h o*|a w k' { p r i n t$ 8 } ' ))

Or, for something a bit more elaborate . . . Example 12-3. Finding anagrams
# ! / b i n / b a s h #a g r a m 2 . s h #E x a m p l eo fn e s t e dc o m m a n ds u b s t i t u t i o n . # U s e s" a n a g r a m "u t i l i t y # +t h a ti sp a r to ft h ea u t h o r ' s" y a w l "w o r dl i s tp a c k a g e . # h t t p : / / i b i b l i o . o r g / p u b / L i n u x / l i b s / y a w l 0 . 3 . 2 . t a r . g z # h t t p : / / b a s h . d e t a . i n / y a w l 0 . 3 . 2 . t a r . g z E _ N O A R G S = 8 6 E _ B A D A R G = 8 7 M I N L E N = 7 i f[z" $ 1 "] t h e n e c h o" U s a g e$ 0L E T T E R S E T " e x i t$ E _ N O A R G S #S c r i p tn e e d sac o m m a n d l i n ea r g u m e n t . e l i f[$ { # 1 }l t$ M I N L E N] t h e n e c h o" A r g u m e n tm u s th a v ea tl e a s t$ M I N L E Nl e t t e r s . " e x i t$ E _ B A D A R G f i

F I L T E R = ' . . . . . . . ' #M u s th a v ea tl e a s t7l e t t e r s . # 1 2 3 4 5 6 7 A n a g r a m s = ($ ( e c h o$ ( a n a g r a m$ 1|g r e p$ F I L T E R ))) # $ ( $ ( n e s t e dc o m m a n ds u b . )) # ( a r r a ya s s i g n m e n t ) e c h o e c h o" $ { # A n a g r a m s [ * ] } 7 +l e t t e ra n a g r a m sf o u n d " e c h o e c h o$ { A n a g r a m s [ 0 ] } #F i r s ta n a g r a m . e c h o$ { A n a g r a m s [ 1 ] } #S e c o n da n a g r a m . #E t c . #e c h o" $ { A n a g r a m s [ * ] } " #T ol i s ta l lt h ea n a g r a m si nas i n g l el i n e... # L o o ka h e a dt ot h eA r r a y sc h a p t e rf o re n l i g h t e n m e n to n # +w h a t ' sg o i n go nh e r e . #S e ea l s ot h ea g r a m . s hs c r i p tf o ra ne x e r c i s ei na n a g r a mf i n d i n g . e x i t$ ?

Examples of command substitution in shell scripts:

1. Example 11-7 2. Example 11-26 3. Example 9-16 4. Example 16-3 5. Example 16-22 6. Example 16-17 7. Example 16-54 8. Example 11-13 9. Example 11-10 10. Example 16-32 11. Example 20-8 12. Example A-16 13. Example 29-3 14. Example 16-47 15. Example 16-48 16. Example 16-49

Chapter 13. Arithmetic Expansion


Arithmetic expansion provides a powerful tool for performing (integer) arithmetic operations in scripts. Translating a string into a numerical expression is relatively straightforward using backticks, double parentheses, or let . Variations Arithmetic expansion with backticks (often used in conjunction with expr)
z = ` e x p r$ z+3 ` #T h e' e x p r 'c o m m a n dp e r f o r m st h ee x p a n s i o n .

Arithmetic expansion with double parentheses, and using let The use of backticks (backquotes) in arithmetic expansion has been superseded by double parentheses -- ( ( . . . ) ) and $ ( ( . . . ) )-- and also by the very convenient let construction.
z = $ ( ( $ z + 3 ) ) z = $ ( ( z + 3 ) ) # A l s oc o r r e c t . # W i t h i nd o u b l ep a r e n t h e s e s , # +p a r a m e t e rd e r e f e r e n c i n g # +i so p t i o n a l .

#$ ( ( E X P R E S S I O N ) )i sa r i t h m e t i ce x p a n s i o n . # N o tt ob ec o n f u s e dw i t h # +c o m m a n ds u b s t i t u t i o n .

#Y o um a ya l s ou s eo p e r a t i o n sw i t h i nd o u b l ep a r e n t h e s e sw i t h o u ta s s i g n m e n t .

n = 0 e c h o" n=$ n " ( (n+ =1) ) #( ($ n+ =1) )i si n c o r r e c t ! e c h o" n=$ n "

#n=0 #I n c r e m e n t . #n=1

l e tz = z + 3 l e t" z+ =3 " # Q u o t e sp e r m i tt h eu s eo fs p a c e si nv a r i a b l ea s s i g n m e n t . # T h e' l e t 'o p e r a t o ra c t u a l l yp e r f o r m sa r i t h m e t i ce v a l u a t i o n , # +r a t h e rt h a ne x p a n s i o n .

Examples of arithmetic expansion in scripts: 1. Example 16-9 2. Example 11-14 3. Example 27-1 4. Example 27-11 5. Example A-16

Chapter 14. Recess Time


This bizarre little intermission gives the reader a chance to relax and maybe laugh a bit.

Fellow Linux user, greetings! You are reading something which will bring you luck and good fortune. Just e-mail a copy of this document to 10 of your friends. Before making the copies, send a 100-line Bash script to the first person on the list at the bottom of this letter. Then delete their name and add yours to the bottom of the list. Don't break the chain! Make the copies within 48 hours. Wilfred P. of Brooklyn failed to send out his ten copies and woke the next morning to find his job description changed to "COBOL programmer." Howard L. of Newport News sent out his ten copies and within a month had enough hardware to build a 100-node Beowulf cluster dedicated to playing Tuxracer. Amelia V. of Chicago laughed at this letter and broke the chain. Shortly thereafter, a fire broke out in her terminal and she now spends her days writing documentation for MS Windows. Don't break the chain! Send out your ten copies today! Courtesy 'NIX "fortune cookies", with some alterations and many apologies

Part 4. Commands

Mastering the commands on your Linux machine is an indispensable prelude to writing effective shell scripts. This section covers the following commands: . (See also source) ac adduser agetty agrep ar arch at autoload awk (See also Using awk for math operations) badblocks banner basename batch bc bg bind bison builtin bzgrep bzip2 cal caller cat cd chattr chfn chgrp chkconfig

chmod chown chroot cksum clear clock cmp col colrm column comm command compgen complete compress coproc cp cpio cron crypt csplit cu cut date dc dd debugfs declare depmod df dialog

diff diff3 diffstat dig dirname dirs disown dmesg doexec dos2unix du dump dumpe2fs e2fsck echo egrep enable enscript env eqn eval exec exit (Related topic: exit status) expand export expr factor false fdformat fdisk fg

fgrep file find finger flex flock fmt fold free fsck ftp fuser getfacl getopt getopts gettext getty gnome-mount grep groff groupmod groups (Related topic: the $GROUPS variable) gs gzip halt hash hdparm head help hexdump host

hostid hostname (Related topic: the $HOSTNAME variable) hwclock iconv id (Related topic: the $UID variable) ifconfig info infocmp init insmod install ip ipcalc iptables iwconfig jobs join jot kill killall last lastcomm lastlog ldd less let lex lid ln locate lockfile

logger logname logout logrotate look losetup lp ls lsdev lsmod lsof lspci lsusb ltrace lynx lzcat lzma m4 mail mailstats mailto make MAKEDEV man mapfile mcookie md5sum merge mesg mimencode mkbootdisk

mkdir mkdosfs mke2fs mkfifo mkisofs mknod mkswap mktemp mmencode modinfo modprobe more mount msgfmt mv nc netconfig netstat newgrp nice nl nm nmap nohup nslookup objdump od openssl passwd paste patch (Related topic: diff)

pathchk pax pgrep pidof ping pkill popd pr printenv printf procinfo ps pstree ptx pushd pwd (Related topic: the $PWD variable) quota rcp rdev rdist read readelf readlink readonly reboot recode renice reset resize restore rev

rlogin rm rmdir rmmod route rpm rpm2cpio rsh rsync runlevel run-parts rx rz sar scp script sdiff sed seq service set setfacl setquota setserial setterm sha1sum shar shopt shred shutdown size

skill sleep slocate snice sort source sox split sq ssh stat strace strings strip stty su sudo sum suspend swapoff swapon sx sync sz tac tail tar tbl tcpdump tee telinit

telnet Tex texexec time times tmpwatch top touch tput tr traceroute true tset tsort tty tune2fs type typeset ulimit umask umount uname unarc unarj uncompress unexpand uniq units unlzma unrar unset

unsq unzip uptime usbmodules useradd userdel usermod users usleep uucp uudecode uuencode uux vacation vdir vmstat vrfy w wait wall watch wc wget whatis whereis which who whoami whois write xargs

xrandr yacc yes zcat zdiff zdump zegrep zfgrep zgrep zip Table of Contents 15. Internal Commands and Builtins 15.1. Job Control Commands 16. External Filters, Programs and Commands 16.1. Basic Commands 16.2. Complex Commands 16.3. Time / Date Commands 16.4. Text Processing Commands 16.5. File and Archiving Commands 16.6. Communications Commands 16.7. Terminal Control Commands 16.8. Math Commands 16.9. Miscellaneous Commands 17. System and Administrative Commands 17.1. Analyzing a System Script

Chapter 15. Internal Commands and Builtins


A builtin is a command contained within the Bash tool set, literally built in. This is either for performance reasons -- builtins execute faster than external commands, which usually require forking off [58] a separate process -- or because a particular builtin needs direct access to the shell internals. When a command or the shell itself initiates (or spawns) a new subprocess to carry out a task, this is called forking. This new process is the child, and the process that forked it off is the parent . While the child process is doing its work, the parent process is still executing. Note that while a parent process gets the process ID of the child process, and can thus pass arguments to it, the reverse is not true. This can create problems that are subtle and hard to track down. Example 15-1. A script that spawns multiple instances of itself
# ! / b i n / b a s h

#s p a w n . s h

P I D S = $ ( p i d o fs h$ 0 ) #P r o c e s sI D so ft h ev a r i o u si n s t a n c e so ft h i ss c r i p t . P _ a r r a y = ($ P I D S) #P u tt h e mi na na r r a y( w h y ? ) . e c h o$ P I D S #S h o wp r o c e s sI D so fp a r e n ta n dc h i l dp r o c e s s e s . l e t" i n s t a n c e s=$ { # P _ a r r a y [ * ] }-1 " #C o u n te l e m e n t s ,l e s s1 . #W h ys u b t r a c t1 ? e c h o" $ i n s t a n c e si n s t a n c e ( s )o ft h i ss c r i p tr u n n i n g . " e c h o" [ H i tC t l Ct oe x i t . ] " ;e c h o

s l e e p1 s h$ 0 e x i t0

#W a i t . #P l a yi ta g a i n ,S a m . #N o tn e c e s s a r y ;s c r i p tw i l ln e v e rg e tt oh e r e . #W h yn o t ?

# A f t e re x i t i n gw i t haC t l C , # +d oa l lt h es p a w n e di n s t a n c e so ft h es c r i p td i e ? # I fs o ,w h y ? #N o t e : ##B ec a r e f u ln o tt or u nt h i ss c r i p tt o ol o n g . #I tw i l le v e n t u a l l ye a tu pt o om a n ys y s t e mr e s o u r c e s . # I sh a v i n gas c r i p ts p a w nm u l t i p l ei n s t a n c e so fi t s e l f # +a na d v i s a b l es c r i p t i n gt e c h n i q u e . # W h yo rw h yn o t ?

Generally, a Bash builtin does not fork a subprocess when it executes within a script. An external system command or filter in a script usually will fork a subprocess. A builtin may be a synonym to a system command of the same name, but Bash reimplements it internally. For example, the Bash echo command is not the same as / b i n / e c h o , although their behavior is almost identical.
# ! / b i n / b a s h e c h o" T h i sl i n eu s e st h e\ " e c h o \ "b u i l t i n . " / b i n / e c h o" T h i sl i n eu s e st h e/ b i n / e c h os y s t e mc o m m a n d . "

A keyword is a reserved word, token or operator. Keywords have a special meaning to the shell, and indeed are the building blocks of the shell's syntax. As examples, for, while, do, and ! are keywords. Similar to a builtin, a keyword is hard-coded into Bash, but unlike a builtin, a keyword is not in itself a command, but a subunit of a command construct . [59] I/O echo prints (to s t d o u t ) an expression or variable (see Example 4-1).
e c h oH e l l o e c h o$ a

An echo requires the eoption to print escaped characters. See Example 5-2. Normally, each echo command prints a terminal newline, but the noption suppresses this. An echo can be used to feed a sequence of commands down a pipe.
i fe c h o" $ V A R "|g r e pqt x t #i f[ [$ V A R=* t x t *] ] t h e n e c h o" $ V A Rc o n t a i n st h es u b s t r i n gs e q u e n c e\ " t x t \ " " f i

An echo, in combination with command substitution can set a variable.


a = ` e c h o" H E L L O "|t rA Za z `

See also Example 16-22, Example 16-3, Example 16-47, and Example 16-48. Be aware that echo `command` deletes any linefeeds that the output of c o m m a n dgenerates. The $IFS (internal field separator) variable normally contains \n (linefeed) as one of its set of whitespace characters. Bash therefore splits the output of c o m m a n dat linefeeds into arguments to echo. Then echo outputs these arguments, separated by spaces.
b a s h $l sl/ u s r / s h a r e / a p p s / k j e z z / s o u n d s r w r r 1r o o t r o o t 1 4 0 7N o v 7 2 0 0 0r e f l e c t . a u r w r r 1r o o t r o o t 3 6 2N o v 7 2 0 0 0s e c o n d s . a u

b a s h $e c h o` l sl/ u s r / s h a r e / a p p s / k j e z z / s o u n d s ` t o t a l4 0r w r r -1r o o tr o o t7 1 6N o v72 0 0 0r e f l e c t . a ur w r r -1r o o tr o o t. . .

So, how can we embed a linefeed within an echoed character string?


#E m b e d d i n gal i n e f e e d ? e c h o" W h yd o e s n ' tt h i ss t r i n g\ ns p l i to nt w ol i n e s ? " #D o e s n ' ts p l i t . #L e t ' st r ys o m e t h i n ge l s e . e c h o e c h o$ " Al i n eo ft e x tc o n t a i n i n g al i n e f e e d . " #P r i n t sa st w od i s t i n c tl i n e s( e m b e d d e dl i n e f e e d ) . #B u t ,i st h e" $ "v a r i a b l ep r e f i xr e a l l yn e c e s s a r y ? e c h o e c h o" T h i ss t r i n gs p l i t s o nt w ol i n e s . " #N o ,t h e" $ "i sn o tn e e d e d . e c h o e c h o" " e c h o e c h on$ " A n o t h e rl i n eo ft e x tc o n t a i n i n g al i n e f e e d . " #P r i n t sa st w od i s t i n c tl i n e s( e m b e d d e dl i n e f e e d ) . #E v e nt h eno p t i o nf a i l st os u p p r e s st h el i n e f e e dh e r e . e c h o e c h o e c h o" " e c h o e c h o #H o w e v e r ,t h ef o l l o w i n gd o e s n ' tw o r ka se x p e c t e d . #W h yn o t ?H i n t :A s s i g n m e n tt oav a r i a b l e . s t r i n g 1 = $ " Y e ta n o t h e rl i n eo ft e x tc o n t a i n i n g al i n e f e e d( m a y b e ) . " e c h o$ s t r i n g 1 #Y e ta n o t h e rl i n eo ft e x tc o n t a i n i n gal i n e f e e d( m a y b e ) .

# #L i n e f e e db e c o m e sas p a c e .

#T h a n k s ,S t e v eP a r k e r ,f o rp o i n t i n gt h i so u t .

This command is a shell builtin, and not the same as / b i n / e c h o , although its behavior is similar.
b a s h $t y p eae c h o e c h oi sas h e l lb u i l t i n e c h oi s/ b i n / e c h o

printf The printf, formatted print, command is an enhanced echo. It is a limited variant of the C language p r i n t f ( )library function, and its syntax is somewhat different. printf f o r m a t s t r i n g ... p a r a m e t e r ... This is the Bash builtin version of the / b i n / p r i n t for / u s r / b i n / p r i n t fcommand. See the printf manpage (of the system command) for in-depth coverage. Older versions of Bash may not support printf. Example 15-2. printf in action
# ! / b i n / b a s h #p r i n t fd e m o d e c l a r erP I = 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 d e c l a r erD e c i m a l C o n s t a n t = 3 1 3 7 3 M e s s a g e 1 = " G r e e t i n g s , " M e s s a g e 2 = " E a r t h l i n g . " e c h o p r i n t f" P it o2d e c i m a lp l a c e s=% 1 . 2 f "$ P I e c h o p r i n t f" P it o9d e c i m a lp l a c e s=% 1 . 9 f "$ P I #I te v e nr o u n d so f fc o r r e c t l y . p r i n t f" \ n " #P r i n t sal i n ef e e d , #E q u i v a l e n tt o' e c h o '... #R e a d o n l yv a r i a b l e ,i . e . ,ac o n s t a n t .

p r i n t f" C o n s t a n t=\ t % d \ n "$ D e c i m a l C o n s t a n t #I n s e r t st a b( \ t ) . p r i n t f" % s% s\ n "$ M e s s a g e 1$ M e s s a g e 2 e c h o #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # #S i m u l a t i o no fCf u n c t i o n ,s p r i n t f ( ) . #L o a d i n gav a r i a b l ew i t haf o r m a t t e ds t r i n g . e c h o P i 1 2 = $ ( p r i n t f" % 1 . 1 2 f "$ P I ) e c h o" P it o1 2d e c i m a lp l a c e s=$ P i 1 2 " M s g = ` p r i n t f" % s% s\ n "$ M e s s a g e 1$ M e s s a g e 2 ` e c h o$ M s g ;e c h o$ M s g # A si th a p p e n s ,t h e' s p r i n t f 'f u n c t i o nc a nn o wb ea c c e s s e d # +a sal o a d a b l em o d u l et oB a s h , # +b u tt h i si sn o tp o r t a b l e .

#R o u n d o f fe r r o r !

e x i t0

Formatting error messages is a useful application of printf


E _ B A D D I R = 8 5 v a r = n o n e x i s t e n t _ d i r e c t o r y e r r o r ( ) { p r i n t f" $ @ "> & 2 #F o r m a t sp o s i t i o n a lp a r a m sp a s s e d ,a n ds e n d st h e mt os t d e r r . e c h o e x i t$ E _ B A D D I R } c d$ v a r| |e r r o r$ " C a n ' tc dt o% s . "" $ v a r " #T h a n k s ,S . C .

See also Example 36-15. read "Reads" the value of a variable from s t d i n , that is, interactively fetches input from the keyboard. The aoption lets read get array variables (see Example 27-6). Example 15-3. Variable assignment, using read
# ! / b i n / b a s h #" R e a d i n g "v a r i a b l e s . e c h on" E n t e rt h ev a l u eo fv a r i a b l e' v a r 1 ' :" #T h eno p t i o nt oe c h os u p p r e s s e sn e w l i n e . r e a dv a r 1 #N o t en o' $ 'i nf r o n to fv a r 1 ,s i n c ei ti sb e i n gs e t . e c h o" v a r 1=$ v a r 1 "

e c h o #As i n g l e' r e a d 's t a t e m e n tc a ns e tm u l t i p l ev a r i a b l e s . e c h on" E n t e rt h ev a l u e so fv a r i a b l e s' v a r 2 'a n d' v a r 3 '" e c h o= n" ( s e p a r a t e db yas p a c eo rt a b ) :" r e a dv a r 2v a r 3 e c h o" v a r 2=$ v a r 2 v a r 3=$ v a r 3 " # I fy o ui n p u to n l yo n ev a l u e , # +t h eo t h e rv a r i a b l e ( s )w i l lr e m a i nu n s e t( n u l l ) . e x i t0

A read without an associated variable assigns its input to the dedicated variable $REPLY. Example 15-4. What happens when read has no variable
# ! / b i n / b a s h #r e a d n o v a r . s h e c h o #-# e c h on" E n t e rav a l u e :" r e a dv a r

e c h o" \ " v a r \ "=" $ v a r " " #E v e r y t h i n ga se x p e c t e dh e r e . #-# e c h o #-# e c h on" E n t e ra n o t h e rv a l u e :" r e a d # N ov a r i a b l es u p p l i e df o r' r e a d ' ,t h e r e f o r e . . . # +I n p u tt o' r e a d 'a s s i g n e dt od e f a u l tv a r i a b l e ,$ R E P L Y . v a r = " $ R E P L Y " e c h o" \ " v a r \ "=" $ v a r " " #T h i si se q u i v a l e n tt ot h ef i r s tc o d eb l o c k . #-# e c h o e c h o" = = = = = = = = = = = = = = = = = = = = = = = = = " e c h o

# T h i se x a m p l ei ss i m i l a rt ot h e" r e p l y . s h "s c r i p t . # H o w e v e r ,t h i so n es h o w st h a t$ R E P L Yi sa v a i l a b l e # +e v e na f t e ra' r e a d 't oav a r i a b l ei nt h ec o n v e n t i o n a lw a y .

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# # I ns o m ei n s t a n c e s ,y o um i g h tw i s ht od i s c a r dt h ef i r s tv a l u er e a d . # I ns u c hc a s e s ,s i m p l yi g n o r et h e$ R E P L Yv a r i a b l e . {#C o d eb l o c k . r e a d #L i n e1 ,t ob ed i s c a r d e d . r e a dl i n e 2 #L i n e2 ,s a v e di nv a r i a b l e . }< $ 0 e c h o" L i n e2o ft h i ss c r i p ti s : " e c h o" $ l i n e 2 " # #r e a d n o v a r . s h e c h o # # ! / b i n / b a s h l i n ed i s c a r d e d . #S e ea l s ot h es o u n d c a r d o n . s hs c r i p t . e x i t0

Normally, inputting a \suppresses a newline during input to a read. The roption causes an inputted \to be interpreted literally. Example 15-5. Multi-line input to read
# ! / b i n / b a s h e c h o e c h o" E n t e ras t r i n gt e r m i n a t e db ya\ \ ,t h e np r e s s< E N T E R > . " e c h o" T h e n ,e n t e ras e c o n ds t r i n g( n o\ \t h i st i m e ) ,a n da g a i np r e s s< E N T E R > . " r e a dv a r 1 #T h e" \ "s u p p r e s s e st h en e w l i n e ,w h e nr e a d i n g$ v a r 1 . # f i r s tl i n e\ # s e c o n dl i n e

e c h o" v a r 1=$ v a r 1 " # v a r 1=f i r s tl i n es e c o n dl i n e # F o re a c hl i n et e r m i n a t e db ya" \ " # +y o ug e tap r o m p to nt h en e x tl i n et oc o n t i n u ef e e d i n gc h a r a c t e r si n t ov a r 1 . e c h o ;e c h o e c h o" E n t e ra n o t h e rs t r i n gt e r m i n a t e db ya\ \,t h e np r e s s< E N T E R > . " r e a drv a r 2 #T h ero p t i o nc a u s e st h e" \ "t ob er e a dl i t e r a l l y .

f i r s tl i n e\

e c h o" v a r 2=$ v a r 2 " # v a r 2=f i r s tl i n e\ #D a t ae n t r yt e r m i n a t e sw i t ht h ef i r s t< E N T E R > . e c h o e x i t0

The read command has some interesting options that permit echoing a prompt and even reading keystrokes without hitting ENTER.
#R e a dak e y p r e s sw i t h o u th i t t i n gE N T E R . r e a dsn 1p" H i tak e y"k e y p r e s s e c h o ;e c h o" K e y p r e s sw a s" \ " $ k e y p r e s s \ " " . " #so p t i o nm e a n sd on o te c h oi n p u t . #nNo p t i o nm e a n sa c c e p to n l yNc h a r a c t e r so fi n p u t . #po p t i o nm e a n se c h ot h ef o l l o w i n gp r o m p tb e f o r er e a d i n gi n p u t . #U s i n gt h e s eo p t i o n si st r i c k y ,s i n c et h e yn e e dt ob ei nt h ec o r r e c to r d e r .

The noption to read also allows detection of the arrow keys and certain of the other unusual keys. Example 15-6. Detecting the arrow keys
# ! / b i n / b a s h #a r r o w d e t e c t . s h :D e t e c t st h ea r r o wk e y s ,a n daf e wm o r e . #T h a n ky o u ,S a n d r oM a g i ,f o rs h o w i n gm eh o w . ##C h a r a c t e rc o d e sg e n e r a t e db yt h ek e y p r e s s e s . a r r o w u p = ' \ [ A ' a r r o w d o w n = ' \ [ B ' a r r o w r t = ' \ [ C ' a r r o w l e f t = ' \ [ D ' i n s e r t = ' \ [ 2 ' d e l e t e = ' \ [ 3 ' #S U C C E S S = 0 O T H E R = 6 5 e c h on" P r e s sak e y . . . " #M a yn e e dt oa l s op r e s sE N T E Ri fak e yn o tl i s t e da b o v ep r e s s e d . r e a dn 3k e y #R e a d3c h a r a c t e r s . e c h on" $ k e y "|g r e p" $ a r r o w u p " # C h e c ki fc h a r a c t e rc o d ed e t e c t e d . i f[" $ ? "e q$ S U C C E S S] t h e n e c h o" U p a r r o wk e yp r e s s e d . " e x i t$ S U C C E S S f i e c h on" $ k e y "|g r e p" $ a r r o w d o w n " i f[" $ ? "e q$ S U C C E S S] t h e n e c h o" D o w n a r r o wk e yp r e s s e d . " e x i t$ S U C C E S S f i e c h on" $ k e y "|g r e p" $ a r r o w r t " i f[" $ ? "e q$ S U C C E S S] t h e n

e c h o" R i g h t a r r o wk e yp r e s s e d . " e x i t$ S U C C E S S f i e c h on" $ k e y "|g r e p" $ a r r o w l e f t " i f[" $ ? "e q$ S U C C E S S] t h e n e c h o" L e f t a r r o wk e yp r e s s e d . " e x i t$ S U C C E S S f i e c h on" $ k e y "|g r e p" $ i n s e r t " i f[" $ ? "e q$ S U C C E S S] t h e n e c h o" \ " I n s e r t \ "k e yp r e s s e d . " e x i t$ S U C C E S S f i e c h on" $ k e y "|g r e p" $ d e l e t e " i f[" $ ? "e q$ S U C C E S S] t h e n e c h o" \ " D e l e t e \ "k e yp r e s s e d . " e x i t$ S U C C E S S f i

e c h o"S o m eo t h e rk e yp r e s s e d . " e x i t$ O T H E R #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# # M a r kA l e x a n d e rc a m eu pw i t has i m p l i f i e d # +v e r s i o no ft h ea b o v es c r i p t( T h a n ky o u ! ) . # I te l i m i n a t e st h en e e df o rg r e p . # ! / b i n / b a s h u p a r r o w = $ ' \ x 1 b [ A ' d o w n a r r o w = $ ' \ x 1 b [ B ' l e f t a r r o w = $ ' \ x 1 b [ D ' r i g h t a r r o w = $ ' \ x 1 b [ C ' r e a dsn 3p" H i ta na r r o wk e y :"x c a s e" $ x "i n $ u p a r r o w ) e c h o" Y o up r e s s e du p a r r o w " ; ; $ d o w n a r r o w ) e c h o" Y o up r e s s e dd o w n a r r o w " ; ; $ l e f t a r r o w ) e c h o" Y o up r e s s e dl e f t a r r o w " ; ; $ r i g h t a r r o w ) e c h o" Y o up r e s s e dr i g h t a r r o w " ; ; e s a c e x i t$ ? #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #A n t o n i oM a c c h ih a sas i m p l e ra l t e r n a t i v e . # ! / b i n / b a s h w h i l et r u e

d o r e a ds n 1a t e s t" $ a "= =` e c h oe n" \ e " `| |c o n t i n u e r e a ds n 1a t e s t" $ a "= =" [ "| |c o n t i n u e r e a ds n 1a c a s e" $ a "i n A ) e c h o" u p " ; ; B ) e c h o" d o w n " ; ; C ) e c h o" r i g h t " ; ; D ) e c h o" l e f t " ; ; e s a c d o n e #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# # E x e r c i s e : # # 1 )A d dd e t e c t i o no ft h e" H o m e , "" E n d , "" P g U p , "a n d" P g D n "k e y s .

The noption to read will not detect the ENTER (newline) key. The toption to read permits timed input (see Example 9-4 and Example A-41). The uoption takes the file descriptor of the target file. The read command may also "read" its variable value from a file redirected to s t d i n . If the file contains more than one line, only the first line is assigned to the variable. If read has more than one parameter, then each of these variables gets assigned a successive whitespace-delineated string. Caution! Example 15-7. Using read with file redirection
# ! / b i n / b a s h r e a dv a r 1< d a t a f i l e e c h o" v a r 1=$ v a r 1 " #v a r 1s e tt ot h ee n t i r ef i r s tl i n eo ft h ei n p u tf i l e" d a t a f i l e " r e a dv a r 2v a r 3< d a t a f i l e e c h o" v a r 2=$ v a r 2 v a r 3=$ v a r 3 " #N o t en o n i n t u i t i v eb e h a v i o ro f" r e a d "h e r e . #1 )R e w i n d sb a c kt ot h eb e g i n n i n go fi n p u tf i l e . #2 )E a c hv a r i a b l ei sn o ws e tt oac o r r e s p o n d i n gs t r i n g , # s e p a r a t e db yw h i t e s p a c e ,r a t h e rt h a nt oa ne n t i r el i n eo ft e x t . #3 )T h ef i n a lv a r i a b l eg e t st h er e m a i n d e ro ft h el i n e . #4 )I ft h e r ea r em o r ev a r i a b l e st ob es e tt h a nw h i t e s p a c e t e r m i n a t e ds t r i n g s # o nt h ef i r s tl i n eo ft h ef i l e ,t h e nt h ee x c e s sv a r i a b l e sr e m a i ne m p t y . e c h o" " #H o wt or e s o l v et h ea b o v ep r o b l e mw i t hal o o p : w h i l er e a dl i n e d o e c h o" $ l i n e " d o n e< d a t a f i l e #T h a n k s ,H e i n e rS t e v e nf o rp o i n t i n gt h i so u t . e c h o" " #U s e$ I F S( I n t e r n a lF i e l dS e p a r a t o rv a r i a b l e )t os p l i tal i n eo fi n p u tt o #" r e a d " ,i fy o ud on o tw a n tt h ed e f a u l tt ob ew h i t e s p a c e . e c h o" L i s to fa l lu s e r s : " O I F S = $ I F S ;I F S = : #/ e t c / p a s s w du s e s" : "f o rf i e l ds e p a r a t o r . w h i l er e a dn a m ep a s s w du i dg i df u l l n a m ei g n o r e d o

e c h o" $ n a m e( $ f u l l n a m e ) " d o n e< / e t c / p a s s w d #I / Or e d i r e c t i o n . I F S = $ O I F S #R e s t o r eo r i g i n a l$ I F S . #T h i sc o d es n i p p e ta l s ob yH e i n e rS t e v e n .

# S e t t i n gt h e$ I F Sv a r i a b l ew i t h i nt h el o o pi t s e l f # +e l i m i n a t e st h en e e df o rs t o r i n gt h eo r i g i n a l$ I F S # +i nat e m p o r a r yv a r i a b l e . # T h a n k s ,D i mS e g e b a r t ,f o rp o i n t i n gt h i so u t . e c h o" " e c h o" L i s to fa l lu s e r s : " w h i l eI F S = :r e a dn a m ep a s s w du i dg i df u l l n a m ei g n o r e d o e c h o" $ n a m e( $ f u l l n a m e ) " d o n e< / e t c / p a s s w d #I / Or e d i r e c t i o n . e c h o e c h o" \ $ I F Ss t i l l$ I F S " e x i t0

Piping output to a read, using echo to set variables will fail. Yet, piping the output of cat seems to work.
c a tf i l e 1f i l e 2| w h i l er e a dl i n e d o e c h o$ l i n e d o n e

However, as Bjn Eriksson shows: Example 15-8. Problems reading from a pipe
# ! / b i n / s h #r e a d p i p e . s h #T h i se x a m p l ec o n t r i b u t e db yB j o nE r i k s s o n . # # #s h o p tsl a s t p i p e l a s t = " ( n u l l ) " c a t$ 0| w h i l er e a dl i n e d o e c h o" { $ l i n e } " l a s t = $ l i n e d o n e e c h o e c h o" + + + + + + + + + + + + + + + + + + + + + + " p r i n t f" \ n A l ld o n e ,l a s t :$ l a s t \ n "# T h eo u t p u to ft h i sl i n e # +c h a n g e si fy o uu n c o m m e n tl i n e5 . # ( B a s h ,v e r s i o ng e4 . 2r e q u i r e d . ) e x i t0 #E n do fc o d e . #( P a r t i a l )o u t p u to fs c r i p tf o l l o w s . #T h e' e c h o 's u p p l i e se x t r ab r a c k e t s . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . / r e a d p i p e . s h { # ! / b i n / s h }

{ l a s t = " ( n u l l ) " } { c a t$ 0| } { w h i l er e a dl i n e } { d o } { e c h o" { $ l i n e } " } { l a s t = $ l i n e } { d o n e } { p r i n t f" n A l ld o n e ,l a s t :$ l a s t n " }

A l ld o n e ,l a s t :( n u l l ) T h ev a r i a b l e( l a s t )i ss e tw i t h i nt h el o o p / s u b s h e l l b u ti t sv a l u ed o e sn o tp e r s i s to u t s i d et h el o o p .

The gendiff script, usually found in / u s r / b i non many Linux distros, pipes the output of find to a while read construct.
f i n d$ 1\ (n a m e" * $ 2 "on a m e" . * $ 2 "\ )p r i n t| w h i l er e a df ;d o ...

It is possible to paste text into the input field of a read (but not multiple lines!). See Example A38. Filesystem cd The familiar cd change directory command finds use in scripts where execution of a command requires being in a specified directory.
( c d/ s o u r c e / d i r e c t o r y& &t a rc f-.)|( c d/ d e s t / d i r e c t o r y& &t a rx p v f)

[from the previously cited example by Alan Cox] The P(physical) option to cd causes it to ignore symbolic links. cd - changes to $OLDPWD, the previous working directory. The cd command does not function as expected when presented with two forward slashes.
b a s h $c d/ / b a s h $p w d / /

The output should, of course, be / . This is a problem both from the command-line and in a script. pwd Print Working Directory. This gives the user's (or script's) current directory (see Example 15-9). The effect is identical to reading the value of the builtin variable $PWD. pushd, popd, dirs This command set is a mechanism for bookmarking working directories, a means of moving back and forth through directories in an orderly manner. A pushdown stack is used to keep track of directory names. Options allow various manipulations of the directory stack.
p u s h dd i r n a m epushes the path d i r n a m eonto

the directory stack (to the top of the stack) and simultaneously

changes the current working directory to d i r n a m e popd removes (pops) the top directory path name off the directory stack and simultaneously changes the current

working directory to the directory now at the top of the stack. dirs lists the contents of the directory stack (compare this with the $DIRSTACK variable). A successful pushd or popd will automatically invoke dirs . Scripts that require various changes to the current working directory without hard-coding the directory name changes can make good use of these commands. Note that the implicit $ D I R S T A C Karray variable, accessible from within a script, holds the contents of the directory stack. Example 15-9. Changing the current working directory
# ! / b i n / b a s h d i r 1 = / u s r / l o c a l d i r 2 = / v a r / s p o o l p u s h d$ d i r 1 #W i l ld oa na u t o m a t i c' d i r s '( l i s td i r e c t o r ys t a c kt os t d o u t ) . e c h o" N o wi nd i r e c t o r y` p w d ` . "#U s e sb a c k q u o t e d' p w d ' . #N o w ,d os o m es t u f fi nd i r e c t o r y' d i r 1 ' . p u s h d$ d i r 2 e c h o" N o wi nd i r e c t o r y` p w d ` . " #N o w ,d os o m es t u f fi nd i r e c t o r y' d i r 2 ' . e c h o" T h et o pe n t r yi nt h eD I R S T A C Ka r r a yi s$ D I R S T A C K . " p o p d e c h o" N o wb a c ki nd i r e c t o r y` p w d ` . " #N o w ,d os o m em o r es t u f fi nd i r e c t o r y' d i r 1 ' . p o p d e c h o" N o wb a c ki no r i g i n a lw o r k i n gd i r e c t o r y` p w d ` . " e x i t0 #W h a th a p p e n si fy o ud o n ' t' p o p d '-t h e ne x i tt h es c r i p t ? #W h i c hd i r e c t o r yd oy o ue n du pi n ?W h y ?

Variables let The let command carries out arithmetic operations on variables. [60] In many cases, it functions as a less complex version of expr. Example 15-10. Letting let do arithmetic.
# ! / b i n / b a s h e c h o l e ta = 1 1 l e ta = a + 5 #S a m ea s' a = 1 1 ' #E q u i v a l e n tt o l e t" a=a+5 " #( D o u b l eq u o t e sa n ds p a c e sm a k ei tm o r er e a d a b l e . ) e c h o" 1 1+5=$ a " #1 6 l e t" a< < =3 " #E q u i v a l e n tt o l e t" a=a< <3 " e c h o" \ " \ $ a \ "( = 1 6 )l e f t s h i f t e d3p l a c e s=$ a " #1 2 8 l e t" a/ =4 " #E q u i v a l e n tt o l e t" a=a/4 " e c h o" 1 2 8/4=$ a "#3 2 l e t" a=5 " #E q u i v a l e n tt o l e t" a=a-5 " e c h o" 3 2-5=$ a " #2 7

l e t" a* = 1 0 " #E q u i v a l e n tt o l e t" a=a*1 0 " e c h o" 2 7*1 0=$ a "#2 7 0 l e t" a% =8 " #E q u i v a l e n tt o l e t" a=a%8 " e c h o" 2 7 0m o d u l o8=$ a ( 2 7 0/8=3 3 ,r e m a i n d e r$ a ) " #6

#D o e s" l e t "p e r m i tC s t y l eo p e r a t o r s ? #Y e s ,j u s ta st h e( (. . .) )d o u b l e p a r e n t h e s e sc o n s t r u c td o e s . l e ta + + #C s t y l e( p o s t )i n c r e m e n t . e c h o" 6 + +=$ a " #6 + +=7 l e ta #C s t y l ed e c r e m e n t . e c h o" 7 -=$ a " #7 -=6 #O fc o u r s e ,+ + a ,e t c . ,a l s oa l l o w e d... e c h o

#T r i n a r yo p e r a t o r . #N o t et h a t$ ai s6 ,s e ea b o v e . l e t" t=a < 7 ? 7 : 1 1 " #T r u e e c h o$ t #7 l e ta + + l e t" t=a < 7 ? 7 : 1 1 " e c h o$ t # 1 1 e x i t

#F a l s e

The let command can, in certain contexts, return a surprising exit status.
#E v g e n i yI v a n o vp o i n t so u t : v a r = 0 e c h o$ ?

#0 #A se x p e c t e d .

l e tv a r + + e c h o$ ?

#1 #T h ec o m m a n dw a ss u c c e s s f u l ,s ow h yi s n ' t$ ? = 0? ? ? #A n o m a l y !

l e tv a r + + e c h o$ ?

#0 #A se x p e c t e d .

#L i k e w i s e... l e tv a r = 0 e c h o$ ?

#1 #T h ec o m m a n dw a ss u c c e s s f u l ,s ow h yi s n ' t$ ? = 0? ? ?

# H o w e v e r ,a sJ e f fG o r a kp o i n t so u t , # +t h i si sp a r to ft h ed e s i g ns p e cf o r' l e t '... #" I ft h el a s tA R Ge v a l u a t e st o0 ,l e tr e t u r n s1 ; # l e tr e t u r n s0o t h e r w i s e . "[ ' h e l pl e t ' ]

eval
e v a la r g 1[ a r g 2 ]. . .[ a r g N ]

Combines the arguments in an expression or list of expressions and e v a l u a t e sthem. Any variables within the expression are expanded. The net result is to convert a string into a command.

The eval command can be used for code generation from the command-line or within a script.
b a s h $c o m m a n d _ s t r i n g = " p sa x " b a s h $p r o c e s s = " p sa x " b a s h $e v a l" $ c o m m a n d _ s t r i n g "|g r e p" $ p r o c e s s " 2 6 9 7 3p t s / 3 R + 0 : 0 0g r e pc o l o rp sa x 2 6 9 7 4p t s / 3 R + 0 : 0 0p sa x

Each invocation of eval forces a re- evaluation of its arguments.


a = ' $ b ' b = ' $ c ' c = d e c h o$ a e v a le c h o$ a e v a le v a le c h o$ a #$ b #F i r s tl e v e l . #$ c #S e c o n dl e v e l . #d #T h i r dl e v e l .

#T h a n ky o u ,E .C h o r o b a .

Example 15-11. Showing the effect of eval


# ! / b i n / b a s h #E x e r c i s i n g" e v a l ". . . y = ` e v a ll sl ` # S i m i l a rt oy = ` l sl ` e c h o$ y # +b u tl i n e f e e d sr e m o v e db e c a u s e" e c h o e d "v a r i a b l ei su n q u o t e d . e c h o e c h o" $ y " # L i n e f e e d sp r e s e r v e dw h e nv a r i a b l ei sq u o t e d . e c h o ;e c h o y = ` e v a ld f ` e c h o$ y # S i m i l a rt oy = ` d f ` # +b u tl i n e f e e d sr e m o v e d .

# W h e nL F ' sn o tp r e s e r v e d ,i tm a ym a k ei te a s i e rt op a r s eo u t p u t , # +u s i n gu t i l i t i e ss u c ha s" a w k " . e c h o e c h o" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " e c h o e v a l" ` s e q3|s e de' s / . * / e c h ov a r & = A B C D E F G H I J / ' ` " #v a r 1 = A B C D E F G H I J #v a r 2 = A B C D E F G H I J #v a r 3 = A B C D E F G H I J e c h o e c h o" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " e c h o

#N o w ,s h o w i n gh o wt od os o m e t h i n gu s e f u lw i t h" e v a l "... #( T h a n ky o u ,E .C h o r o b a ! ) v e r s i o n = 3 . 4 # C a nw es p l i tt h ev e r s i o ni n t om a j o ra n dm i n o r # +p a r ti no n ec o m m a n d ? e c h o" v e r s i o n=$ v e r s i o n " e v a lm a j o r = $ { v e r s i o n / . / ; m i n o r = } # R e p l a c e s' . 'i nv e r s i o nb y' ; m i n o r = ' # T h es u b s t i t u t i o ny i e l d s' 3 ;m i n o r = 4 ' # +s oe v a ld o e sm i n o r = 4 ,m a j o r = 3 e c h oM a j o r :$ m a j o r ,m i n o r :$ m i n o r # M a j o r :3 ,m i n o r :4

Example 15-12. Using eval to select among variables


# ! / b i n / b a s h #a r r c h o i c e . s h # P a s s i n ga r g u m e n t st oaf u n c t i o nt os e l e c t # +o n ep a r t i c u l a rv a r i a b l eo u to fag r o u p . a r r 0 = (1 01 11 21 31 41 5) a r r 1 = (2 02 12 22 32 42 5) a r r 2 = (3 03 13 23 33 43 5) # 0 1 2 3 4 5

E l e m e n tn u m b e r( z e r o i n d e x e d )

c h o o s e _ a r r a y( ) { e v a la r r a y _ m e m b e r = \ $ { a r r $ { a r r a y _ n u m b e r } [ e l e m e n t _ n u m b e r ] } # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # U s i n ge v a lt oc o n s t r u c tt h en a m eo fav a r i a b l e , # +i nt h i sp a r t i c u l a rc a s e ,a na r r a yn a m e . e c h o" E l e m e n t$ e l e m e n t _ n u m b e ro fa r r a y$ a r r a y _ n u m b e ri s$ a r r a y _ m e m b e r " }# F u n c t i o nc a nb er e w r i t t e nt ot a k ep a r a m e t e r s . a r r a y _ n u m b e r = 0 #F i r s ta r r a y . e l e m e n t _ n u m b e r = 3 c h o o s e _ a r r a y #1 3 a r r a y _ n u m b e r = 2 #T h i r da r r a y . e l e m e n t _ n u m b e r = 4 c h o o s e _ a r r a y #3 4 a r r a y _ n u m b e r = 3 #N u l la r r a y( a r r 3n o ta l l o c a t e d ) . e l e m e n t _ n u m b e r = 4 c h o o s e _ a r r a y #( n u l l ) #T h a n ky o u ,A n t o n i oM a c c h i ,f o rp o i n t i n gt h i so u t .

Example 15-13. Echoing the command-line parameters


# ! / b i n / b a s h #e c h o p a r a m s . s h #C a l lt h i ss c r i p tw i t haf e wc o m m a n d l i n ep a r a m e t e r s . #F o re x a m p l e : # s he c h o p a r a m s . s hf i r s ts e c o n dt h i r df o u r t hf i f t h p a r a m s = $ # p a r a m = 1 #N u m b e ro fc o m m a n d l i n ep a r a m e t e r s . #S t a r ta tf i r s tc o m m a n d l i n ep a r a m .

w h i l e[" $ p a r a m "l e" $ p a r a m s "] d o e c h on" C o m m a n d l i n ep a r a m e t e r" e c h on\ $ $ p a r a m # G i v e so n l yt h e* n a m e *o fv a r i a b l e . # ^ ^ ^ # $ 1 ,$ 2 ,$ 3 ,e t c . # W h y ? # \ $e s c a p e st h ef i r s t" $ " # +s oi te c h o e sl i t e r a l l y , # +a n d$ p a r a md e r e f e r e n c e s" $ p a r a m "... # +...a se x p e c t e d . e c h on"=" e v a le c h o\ $ $ p a r a m # G i v e st h e* v a l u e *o fv a r i a b l e . #^ ^ ^ ^ ^ ^ ^ # T h e" e v a l "f o r c e st h e* e v a l u a t i o n * # +o f\ $ $ # +a sa ni n d i r e c tv a r i a b l er e f e r e n c e . ( (p a r a m+ +) ) d o n e #O nt ot h en e x t .

e x i t$ ? #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = $s he c h o p a r a m s . s hf i r s ts e c o n dt h i r df o u r t hf i f t h C o m m a n d l i n ep a r a m e t e r$ 1=f i r s t C o m m a n d l i n ep a r a m e t e r$ 2=s e c o n d C o m m a n d l i n ep a r a m e t e r$ 3=t h i r d C o m m a n d l i n ep a r a m e t e r$ 4=f o u r t h C o m m a n d l i n ep a r a m e t e r$ 5=f i f t h

Example 15-14. Forcing a log-off


# ! / b i n / b a s h #K i l l i n gp p pt of o r c eal o g o f f . #F o rd i a l u pc o n n e c t i o n ,o fc o u r s e . #S c r i p ts h o u l db er u na sr o o tu s e r . S E R P O R T = t t y S 3 # D e p e n d i n go nt h eh a r d w a r ea n de v e nt h ek e r n e lv e r s i o n , # +t h em o d e mp o r to ny o u rm a c h i n em a yb ed i f f e r e n t# +/ d e v / t t y S 1o r/ d e v / t t y S 2 .

k i l l p p p = " e v a lk i l l9` p sa x|a w k' / p p p /{p r i n t$ 1} ' ` " # -p r o c e s sI Do fp p p$ k i l l p p p #T h i sv a r i a b l ei sn o wac o m m a n d .

#T h ef o l l o w i n go p e r a t i o n sm u s tb ed o n ea sr o o tu s e r . c h m o d6 6 6/ d e v / $ S E R P O R T #R e s t o r er + wp e r m i s s i o n s ,o re l s ew h a t ? # S i n c ed o i n gaS I G K I L Lo np p pc h a n g e dt h ep e r m i s s i o n so nt h es e r i a lp o r t , # +w er e s t o r ep e r m i s s i o n st op r e v i o u ss t a t e . r m/ v a r / l o c k / L C K . . $ S E R P O R T e x i t$ ? #E x e r c i s e s : ##1 )H a v es c r i p tc h e c kw h e t h e rr o o tu s e ri si n v o k i n gi t . #2 )D oac h e c ko nw h e t h e rt h ep r o c e s st ob ek i l l e d # + i sa c t u a l l yr u n n i n gb e f o r ea t t e m p t i n gt ok i l li t . #3 )W r i t ea na l t e r n a t ev e r s i o no ft h i ss c r i p tb a s e do n' f u s e r ' : # + i f[f u s e rs/ d e v / m o d e m] ;t h e n... #R e m o v et h es e r i a lp o r tl o c kf i l e .W h y ?

Example 15-15. A version of rot13


# ! / b i n / b a s h #Av e r s i o no f" r o t 1 3 "u s i n g' e v a l ' . #C o m p a r et o" r o t 1 3 . s h "e x a m p l e . s e t v a r _ r o t _ 1 3 ( ) #" r o t 1 3 "s c r a m b l i n g { l o c a lv a r n a m e = $ 1v a r v a l u e = $ 2 e v a l$ v a r n a m e = ' $ ( e c h o" $ v a r v a l u e "|t ra zn z a m ) ' }

s e t v a r _ r o t _ 1 3v a r" f o o b a r " e c h o$ v a r s e t v a r _ r o t _ 1 3v a r" $ v a r "

#R u n" f o o b a r "t h r o u g hr o t 1 3 . #s b b o n e #R u n" s b b o n e "t h r o u g hr o t 1 3 . #B a c kt oo r i g i n a lv a r i a b l e .

e c h o$ v a r

#f o o b a r

#T h i se x a m p l eb yS t e p h a n eC h a z e l a s . #M o d i f i e db yd o c u m e n ta u t h o r . e x i t0

Here is another example of using eval to evaluate a complex expression, this one from an earlier version of YongYe's Tetris game script.
e v a l$ { 1 } + = \ " $ { x }$ { y }\ "

Example A-53 uses eval to convert array elements into a command list. The eval command occurs in the older version of indirect referencing.
e v a lv a r = \ $ $ v a r

The eval command can be used to parameterize brace expansion. The eval command can be risky, and normally should be avoided when there exists a reasonable alternative. An e v a l$ C O M M A N D Sexecutes the contents of C O M M A N D S , which may contain such unpleasant surprises as rm -rf *. Running an eval on unfamiliar code written by persons unknown is living dangerously. set The set command changes the value of internal script variables/options. One use for this is to toggle option flags which help determine the behavior of the script. Another application for it is to reset the positional parameters that a script sees as the result of a command (s e t` c o m m a n d ` ). The script can then parse the fields of the command output. Example 15-16. Using set with positional parameters
# ! / b i n / b a s h #e x 3 4 . s h #S c r i p t" s e t t e s t " #I n v o k et h i ss c r i p tw i t ht h r e ec o m m a n d l i n ep a r a m e t e r s , #f o re x a m p l e ," s he x 3 4 . s ho n et w ot h r e e " . e c h o e c h o" P o s i t i o n a lp a r a m e t e r sb e f o r e s e t\ ` u n a m ea \ `: " e c h o" C o m m a n d l i n ea r g u m e n t# 1=$ 1 " e c h o" C o m m a n d l i n ea r g u m e n t# 2=$ 2 " e c h o" C o m m a n d l i n ea r g u m e n t# 3=$ 3 "

s e t` u n a m ea `#S e t st h ep o s i t i o n a lp a r a m e t e r st ot h eo u t p u t #o ft h ec o m m a n d` u n a m ea ` e c h o e c h o+ + + + + e c h o$ _ #+ + + + + #F l a g ss e ti ns c r i p t . e c h o$ #h B # A n o m a l o u sb e h a v i o r ? e c h o e c h o" P o s i t i o n a lp a r a m e t e r sa f t e r s e t\ ` u n a m ea \ `: " #$ 1 ,$ 2 ,$ 3 ,e t c .r e i n i t i a l i z e dt or e s u l to f` u n a m ea ` e c h o" F i e l d# 1o f' u n a m ea '=$ 1 " e c h o" F i e l d# 2o f' u n a m ea '=$ 2 " e c h o" F i e l d# 3o f' u n a m ea '=$ 3 " e c h o\ # \ # \ # e c h o$ _ ## # #

e c h o e x i t0

More fun with positional parameters. Example 15-17. Reversing the positional parameters
# ! / b i n / b a s h #r e v p o s p a r a m s . s h :R e v e r s ep o s i t i o n a lp a r a m e t e r s . #S c r i p tb yD a nJ a c o b s o n ,w i t hs t y l i s t i cr e v i s i o n sb yd o c u m e n ta u t h o r .

s e ta \bcd \e ; # ^ ^ S p a c e se s c a p e d # ^^ S p a c e sn o te s c a p e d O I F S = $ I F S ;I F S = : ; # ^ S a v i n go l dI F Sa n ds e t t i n gn e wo n e . e c h o u n t i l[$ #e q0] d o # S t e pt h r o u g hp o s i t i o n a lp a r a m e t e r s . e c h o" # # #k 0=" $ k " " #B e f o r e k = $ 1 : $ k ; # A p p e n de a c hp o sp a r a mt ol o o pv a r i a b l e . # ^ e c h o" # # #k=" $ k " " #A f t e r e c h o s h i f t ; d o n e s e t$ k # S e tn e wp o s i t i o n a lp a r a m e t e r s . e c h oe c h o$ ## C o u n to fp o s i t i o n a lp a r a m e t e r s . e c h oe c h o f o ri # O m i t t i n gt h e" i nl i s t "s e t st h ev a r i a b l e-i# +t ot h ep o s i t i o n a lp a r a m e t e r s .

d o e c h o$ i #D i s p l a yn e wp o s i t i o n a lp a r a m e t e r s . d o n e I F S = $ O I F S #R e s t o r eI F S . # Q u e s t i o n : # I si tn e c e s s a r yt os e ta nn e wI F S ,i n t e r n a lf i e l ds e p a r a t o r , # +i no r d e rf o rt h i ss c r i p tt ow o r kp r o p e r l y ? # W h a th a p p e n si fy o ud o n ' t ?T r yi t . # A n d ,w h yu s et h en e wI F S-ac o l o n-i nl i n e1 7 , # +t oa p p e n dt ot h el o o pv a r i a b l e ? # W h a ti st h ep u r p o s eo ft h i s ? e x i t0 $. / r e v p o s p a r a m s . s h # # #k 0= # # #k=ab # # #k 0=ab # # #k=cab # # #k 0=cab # # #k=decab 3

de c ab

Invoking set without any options or arguments simply lists all the environmental and other variables that have been initialized.
b a s h $s e t A U T H O R C O P Y = / h o m e / b o z o / p o s t s B A S H = / b i n / b a s h B A S H _ V E R S I O N = $ ' 2 . 0 5 . 8 ( 1 ) r e l e a s e ' . . . X A U T H O R I T Y = / h o m e / b o z o / . X a u t h o r i t y _ = / e t c / b a s h r c v a r i a b l e 2 2 = a b c v a r i a b l e 2 3 = x z y

Using set with the -option explicitly assigns the contents of a variable to the positional parameters. If no variable follows the -it unsets the positional parameters. Example 15-18. Reassigning the positional parameters
# ! / b i n / b a s h v a r i a b l e = " o n et w ot h r e ef o u rf i v e " s e t-$ v a r i a b l e #S e t sp o s i t i o n a lp a r a m e t e r st ot h ec o n t e n t so f" $ v a r i a b l e " . f i r s t _ p a r a m = $ 1 s e c o n d _ p a r a m = $ 2 s h i f t ;s h i f t #S h i f tp a s tf i r s tt w op o s i t i o n a lp a r a m s . #s h i f t2 a l s ow o r k s . r e m a i n i n g _ p a r a m s = " $ * " e c h o e c h o" f i r s tp a r a m e t e r=$ f i r s t _ p a r a m " e c h o" s e c o n dp a r a m e t e r=$ s e c o n d _ p a r a m " e c h o" r e m a i n i n gp a r a m e t e r s=$ r e m a i n i n g _ p a r a m s " e c h o ;e c h o #A g a i n . s e t-$ v a r i a b l e f i r s t _ p a r a m = $ 1 s e c o n d _ p a r a m = $ 2 e c h o" f i r s tp a r a m e t e r=$ f i r s t _ p a r a m " e c h o" s e c o n dp a r a m e t e r=$ s e c o n d _ p a r a m "

#o n e #t w o #t h r e ef o u rf i v e

#o n e #t w o

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = s e t#U n s e t sp o s i t i o n a lp a r a m e t e r si fn ov a r i a b l es p e c i f i e d . f i r s t _ p a r a m = $ 1 s e c o n d _ p a r a m = $ 2 e c h o" f i r s tp a r a m e t e r=$ f i r s t _ p a r a m " e c h o" s e c o n dp a r a m e t e r=$ s e c o n d _ p a r a m " e x i t0

#( n u l lv a l u e ) #( n u l lv a l u e )

See also Example 11-2 and Example 16-56.

unset The unset command deletes a shell variable, effectively setting it to null. Note that this command does not affect positional parameters.
b a s h $u n s e tP A T H b a s h $e c h o$ P A T H b a s h $

Example 15-19. "Unsetting" a variable


# ! / b i n / b a s h #u n s e t . s h :U n s e t t i n gav a r i a b l e . v a r i a b l e = h e l l o e c h o" v a r i a b l e=$ v a r i a b l e " u n s e tv a r i a b l e # I n i t i a l i z e d .

# U n s e t . # I nt h i sp a r t i c u l a rc o n t e x t , # +s a m ee f f e c ta s : v a r i a b l e = e c h o" ( u n s e t )v a r i a b l e=$ v a r i a b l e " # $ v a r i a b l ei sn u l l . i f[z" $ v a r i a b l e "] # T r yas t r i n g l e n g t ht e s t . t h e n e c h o" \ $ v a r i a b l eh a sz e r ol e n g t h . " f i e x i t0

In most contexts, an undeclared variable and one that has been unset are equivalent. However, the ${parameter:-default} parameter substitution construct can distinguish between the two. export The export [61] command makes available variables to all child processes of the running script or shell. One important use of the export command is in startup files, to initialize and make accessible environmental variables to subsequent user processes. Unfortunately, there is no way to export variables back to the parent process, to the process that called or invoked the script or shell. Example 15-20. Using export to pass a variable to an embedded awk script
# ! / b i n / b a s h # Y e ta n o t h e rv e r s i o no ft h e" c o l u m nt o t a l e r "s c r i p t( c o l t o t a l e r . s h ) # +t h a ta d d su pas p e c i f i e dc o l u m n( o fn u m b e r s )i nt h et a r g e tf i l e . # T h i su s e st h ee n v i r o n m e n tt op a s sas c r i p tv a r i a b l et o' a w k '... # +a n dp l a c e st h ea w ks c r i p ti nav a r i a b l e .

A R G S = 2 E _ W R O N G A R G S = 8 5 i f[$ #n e" $ A R G S "]#C h e c kf o rp r o p e rn u m b e ro fc o m m a n d l i n ea r g s . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m ec o l u m n n u m b e r " e x i t$ E _ W R O N G A R G S f i f i l e n a m e = $ 1 c o l u m n _ n u m b e r = $ 2

# = = = = =S a m ea so r i g i n a ls c r i p t ,u pt ot h i sp o i n t= = = = = # e x p o r tc o l u m n _ n u m b e r #E x p o r tc o l u m nn u m b e rt oe n v i r o n m e n t ,s oi t ' sa v a i l a b l ef o rr e t r i e v a l .

#a w k s c r i p t = ' {t o t a l+ =$ E N V I R O N [ " c o l u m n _ n u m b e r " ]} E N D{p r i n tt o t a l} ' #Y e s ,av a r i a b l ec a nh o l da na w ks c r i p t . ##N o w ,r u nt h ea w ks c r i p t . a w k" $ a w k s c r i p t "" $ f i l e n a m e " #T h a n k s ,S t e p h a n eC h a z e l a s . e x i t0

It is possible to initialize and export variables in the same operation, as in export var1=xxx. However, as Greg Keraunen points out, in certain situations this may have a different effect than setting a variable, then exporting it.
b a s h $e x p o r tv a r = ( ab ) ;e c h o$ { v a r [ 0 ] } ( ab )

b a s h $v a r = ( ab ) ;e x p o r tv a r ;e c h o$ { v a r [ 0 ] } a

A variable to be exported may require special treatment. See Example M-2. declare , typeset The declare and typeset commands specify and/or restrict properties of variables. readonly Same as declare -r, sets a variable as read-only, or, in effect, as a constant. Attempts to change the variable fail with an error message. This is the shell analog of the C language const type qualifier. getopts This powerful tool parses command-line arguments passed to the script. This is the Bash analog of the getopt external command and the getopt library function familiar to C programmers. It permits passing and concatenating multiple options [62] and associated arguments to a script (for example s c r i p t n a m ea b ce/ u s r / l o c a l ). The getopts construct uses two implicit variables. $ O P T I N Dis the argument pointer (OPTion INDex ) and $ O P T A R G (OPTion ARGument ) the (optional) argument attached to an option. A colon following the option name in the declaration tags that option as having an associated argument. A getopts construct usually comes packaged in a while loop, which processes the options and arguments one at a time, then increments the implicit $ O P T I N Dvariable to point to the next. 1. The arguments passed from the command-line to the script must be preceded by a dash (). It is the prefixed -that lets getopts recognize command-line arguments as options. In fact, getopts will not process arguments without the prefixed , and will terminate option processing at the first argument encountered lacking them.

2. The getopts template differs slightly from the standard while loop, in that it lacks condition brackets. 3. The getopts construct is a highly functional replacement for the traditional getopt external command.

w h i l eg e t o p t s" : a b c d e : f g "O p t i o n #I n i t i a ld e c l a r a t i o n . #a ,b ,c ,d ,e ,f ,a n dga r et h eo p t i o n s( f l a g s )e x p e c t e d . #T h e:a f t e ro p t i o n' e 's h o w si tw i l lh a v ea na r g u m e n tp a s s e dw i t hi t . d o c a s e$ O p t i o ni n a)#D os o m e t h i n gw i t hv a r i a b l e' a ' . b)#D os o m e t h i n gw i t hv a r i a b l e' b ' . . . . e ) #D os o m e t h i n gw i t h' e ' ,a n da l s ow i t h$ O P T A R G , #w h i c hi st h ea s s o c i a t e da r g u m e n tp a s s e dw i t ho p t i o n' e ' . . . . g)#D os o m e t h i n gw i t hv a r i a b l e' g ' . e s a c d o n e s h i f t$ ( ( $ O P T I N D-1 ) ) #M o v ea r g u m e n tp o i n t e rt on e x t . #A l lt h i si sn o tn e a r l ya sc o m p l i c a t e da si tl o o k s< g r i n > .

Example 15-21. Using getopts to read the options/arguments passed to a script


# ! / b i n / b a s h #e x 3 3 . s h :E x e r c i s i n gg e t o p t sa n dO P T I N D # S c r i p tm o d i f i e d1 0 / 0 9 / 0 3a tt h es u g g e s t i o no fB i l lG r a d w o h l .

#H e r ew eo b s e r v eh o w' g e t o p t s 'p r o c e s s e sc o m m a n d l i n ea r g u m e n t st os c r i p t . #T h ea r g u m e n t sa r ep a r s e da s" o p t i o n s "( f l a g s )a n da s s o c i a t e da r g u m e n t s . #T r yi n v o k i n gt h i ss c r i p tw i t h : # ' s c r i p t n a m em n ' # ' s c r i p t n a m eo qq O p t i o n '( q O p t i o nc a nb es o m ea r b i t r a r ys t r i n g . ) # ' s c r i p t n a m eq X X Xr ' # # ' s c r i p t n a m eq r ' # + -U n e x p e c t e dr e s u l t ,t a k e s" r "a st h ea r g u m e n tt oo p t i o n" q " # ' s c r i p t n a m eqr ' # + -U n e x p e c t e dr e s u l t ,s a m ea sa b o v e # ' s c r i p t n a m em n o pm n o p ' -U n e x p e c t e dr e s u l t # ( O P T I N Di su n r e l i a b l ea ts t a t i n gw h e r ea no p t i o nc a m ef r o m . ) # # I fa no p t i o ne x p e c t sa na r g u m e n t( " f l a g : " ) ,t h e ni tw i l lg r a b # +w h a t e v e ri sn e x to nt h ec o m m a n d l i n e . N O _ A R G S = 0 E _ O P T E R R O R = 8 5 i f[$ #e q" $ N O _ A R G S "] #S c r i p ti n v o k e dw i t hn oc o m m a n d l i n ea r g s ? t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `o p t i o n s( m n o p q r s ) " e x i t$ E _ O P T E R R O R #E x i ta n de x p l a i nu s a g e . #U s a g e :s c r i p t n a m eo p t i o n s #N o t e :d a s h( )n e c e s s a r y f i

w h i l eg e t o p t s" : m n o p q : r s "O p t i o n d o c a s e$ O p t i o ni n

m )e c h o" S c e n a r i o# 1 :o p t i o nm - [ O P T I N D = $ { O P T I N D } ] " ; ; n|o)e c h o" S c e n a r i o# 2 :o p t i o n$ O p t i o n - [ O P T I N D = $ { O P T I N D } ] " ; ; p )e c h o" S c e n a r i o# 3 :o p t i o np - [ O P T I N D = $ { O P T I N D } ] " ; ; q )e c h o" S c e n a r i o# 4 :o p t i o nq \ w i t ha r g u m e n t\ " $ O P T A R G \ " [ O P T I N D = $ { O P T I N D } ] " ; ; # N o t et h a to p t i o n' q 'm u s th a v ea na s s o c i a t e da r g u m e n t , # +o t h e r w i s ei tf a l l st h r o u g ht ot h ed e f a u l t . r|s)e c h o" S c e n a r i o# 5 :o p t i o n$ O p t i o n " ; ; * )e c h o" U n i m p l e m e n t e do p t i o nc h o s e n . " ; ; #D e f a u l t . e s a c d o n e s h i f t$ ( ( $ O P T I N D-1 ) ) # D e c r e m e n t st h ea r g u m e n tp o i n t e rs oi tp o i n t st on e x ta r g u m e n t . # $ 1n o wr e f e r e n c e st h ef i r s tn o n o p t i o ni t e ms u p p l i e do nt h ec o m m a n d l i n e # +i fo n ee x i s t s . e x i t$ ? # A sB i l lG r a d w o h ls t a t e s , # " T h eg e t o p t sm e c h a n i s ma l l o w so n et os p e c i f y : s c r i p t n a m em n o pm n o p # + b u tt h e r ei sn or e l i a b l ew a yt od i f f e r e n t i a t ew h a tc a m e # +f r o mw h e r eb yu s i n gO P T I N D . " # T h e r ea r e ,h o w e v e r ,w o r k a r o u n d s .

Script Behavior source , . (dot command) This command, when invoked from the command-line, executes a script. Within a script, a s o u r c ef i l e n a m e loads the file f i l e n a m e . Sourcing a file (dot-command) imports code into the script, appending to the script (same effect as the # i n c l u d edirective in a C program). The net result is the same as if the "sourced" lines of code were physically present in the body of the script. This is useful in situations when multiple scripts use a common data file or function library. Example 15-22. "Including" a data file
# ! / b i n / b a s h # N o t et h a tt h i se x a m p l em u s tb ei n v o k e dw i t hb a s h ,i . e . ,b a s he x 3 8 . s h # +n o t s he x 3 8 . s h! .d a t a f i l e #L o a dad a t af i l e . #S a m ee f f e c ta s" s o u r c ed a t a f i l e " ,b u tm o r ep o r t a b l e . # T h ef i l e" d a t a f i l e "m u s tb ep r e s e n ti nc u r r e n tw o r k i n gd i r e c t o r y , # +s i n c ei ti sr e f e r r e dt ob yi t sb a s e n a m e . #N o w ,l e t ' sr e f e r e n c es o m ed a t af r o mt h a tf i l e . e c h o" v a r i a b l e 1( f r o md a t a f i l e )=$ v a r i a b l e 1 " e c h o" v a r i a b l e 3( f r o md a t a f i l e )=$ v a r i a b l e 3 " l e t" s u m=$ v a r i a b l e 2+$ v a r i a b l e 4 " e c h o" S u mo fv a r i a b l e 2+v a r i a b l e 4( f r o md a t a f i l e )=$ s u m " e c h o" m e s s a g e 1( f r o md a t a f i l e )i s\ " $ m e s s a g e 1 \ " " # E s c a p e dq u o t e s e c h o" m e s s a g e 2( f r o md a t a f i l e )i s\ " $ m e s s a g e 2 \ " " p r i n t _ m e s s a g eT h i si st h em e s s a g e p r i n tf u n c t i o ni nt h ed a t a f i l e .

e x i t$ ?

File d a t a f i l efor Example 15-22, above. Must be present in same directory.


#T h i si sad a t af i l el o a d e db yas c r i p t .

#F i l e so ft h i st y p em a yc o n t a i nv a r i a b l e s ,f u n c t i o n s ,e t c . #I tl o a d sw i t ha' s o u r c e 'o r' . 'c o m m a n df r o mas h e l ls c r i p t . #L e t ' si n i t i a l i z es o m ev a r i a b l e s . v a r i a b l e 1 = 2 3 v a r i a b l e 2 = 4 7 4 v a r i a b l e 3 = 5 v a r i a b l e 4 = 9 7 m e s s a g e 1 = " G r e e t i n g sf r o m* * *l i n e$ L I N E N O* * *o ft h ed a t af i l e ! " m e s s a g e 2 = " E n o u g hf o rn o w .G o o d b y e . " p r i n t _ m e s s a g e( ) { #E c h o e sa n ym e s s a g ep a s s e dt oi t . i f[z" $ 1 "] t h e n r e t u r n1#E r r o r ,i fa r g u m e n tm i s s i n g . f i e c h o u n t i l[z" $ 1 "] d o #S t e pt h r o u g ha r g u m e n t sp a s s e dt of u n c t i o n . e c h on" $ 1 "#E c h oa r g so n ea tat i m e ,s u p p r e s s i n gl i n ef e e d s . e c h on"" #I n s e r ts p a c e sb e t w e e nw o r d s . s h i f t #N e x to n e . d o n e e c h o r e t u r n0 }

If the sourced file is itself an executable script, then it will run, then return control to the script that called it. A sourced executable script may use a return for this purpose. Arguments may be (optionally) passed to the sourced file as positional parameters.
s o u r c e$ f i l e n a m e$ a r g 1a r g 2

It is even possible for a script to source itself, though this does not seem to have any practical applications. Example 15-23. A (useless) script that sources itself
# ! / b i n / b a s h #s e l f s o u r c e . s h :as c r i p ts o u r c i n gi t s e l f" r e c u r s i v e l y . " #F r o m" S t u p i dS c r i p tT r i c k s , "V o l u m eI I . M A X P A S S C N T = 1 0 0 #M a x i m u mn u m b e ro fe x e c u t i o np a s s e s .

e c h on " $ p a s s _ c o u n t " # A tf i r s te x e c u t i o np a s s ,t h i sj u s te c h o e st w ob l a n ks p a c e s , # +s i n c e$ p a s s _ c o u n ts t i l lu n i n i t i a l i z e d . l e t" p a s s _ c o u n t+ =1 " # A s s u m e st h eu n i n i t i a l i z e dv a r i a b l e$ p a s s _ c o u n t # +c a nb ei n c r e m e n t e dt h ef i r s tt i m ea r o u n d . # T h i sw o r k sw i t hB a s ha n dp d k s h ,b u t # +i tr e l i e so nn o n p o r t a b l e( a n dp o s s i b l yd a n g e r o u s )b e h a v i o r . # B e t t e rw o u l db et oi n i t i a l i z e$ p a s s _ c o u n tt o0b e f o r ei n c r e m e n t i n g . w h i l e[" $ p a s s _ c o u n t "l e$ M A X P A S S C N T] d o .$ 0 #S c r i p t" s o u r c e s "i t s e l f ,r a t h e rt h a nc a l l i n gi t s e l f . #. / $ 0( w h i c hw o u l db et r u er e c u r s i o n )d o e s n ' tw o r kh e r e .W h y ? d o n e

# W h a to c c u r sh e r ei sn o ta c t u a l l yr e c u r s i o n , # +s i n c et h es c r i p te f f e c t i v e l y" e x p a n d s "i t s e l f ,i . e . , # +g e n e r a t e san e ws e c t i o no fc o d e # +w i t he a c hp a s st h r o u g ht h e' w h i l e 'l o o p ' , # w i t he a c h' s o u r c e 'i nl i n e2 0 . # # O fc o u r s e ,t h es c r i p ti n t e r p r e t se a c hn e w l y' s o u r c e d '" # ! "l i n e # +a sac o m m e n t ,a n dn o ta st h es t a r to fan e ws c r i p t . e c h o e x i t0 #T h en e te f f e c ti sc o u n t i n gf r o m1t o1 0 0 . #V e r yi m p r e s s i v e .

#E x e r c i s e : ##W r i t eas c r i p tt h a tu s e st h i st r i c kt oa c t u a l l yd os o m e t h i n gu s e f u l .

exit Unconditionally terminates a script. [63] The exit command may optionally take an integer argument, which is returned to the shell as the exit status of the script. It is good practice to end all but the simplest scripts with an e x i t 0 , indicating a successful run. If a script terminates with an exit lacking an argument, the exit status of the script is the exit status of the last command executed in the script, not counting the exit. This is equivalent to an exit $?. An exit command may also be used to terminate a subshell. exec This shell builtin replaces the current process with a specified command. Normally, when the shell encounters a command, it forks off a child process to actually execute the command. Using the exec builtin, the shell does not fork, and the command exec'ed replaces the shell. When used in a script, therefore, it forces an exit from the script when the exec'ed command terminates. [64] Example 15-24. Effects of exec
# ! / b i n / b a s h e x e ce c h o" E x i t i n g\ " $ 0 \ "a tl i n e$ L I N E N O . " #E x i tf r o ms c r i p th e r e . #$ L I N E N Oi sa ni n t e r n a lB a s hv a r i a b l es e tt ot h el i n en u m b e ri t ' so n . ##T h ef o l l o w i n gl i n e sn e v e re x e c u t e . e c h o" T h i se c h of a i l st oe c h o . " e x i t9 9 # T h i ss c r i p tw i l ln o te x i th e r e . # C h e c ke x i tv a l u ea f t e rs c r i p tt e r m i n a t e s # +w i t ha n' e c h o$ ? ' . # I tw i l l* n o t *b e9 9 .

Example 15-25. A script that exec's itself


# ! / b i n / b a s h #s e l f e x e c . s h #N o t e :S e tp e r m i s s i o n so nt h i ss c r i p tt o5 5 5o r7 5 5 , # t h e nc a l li tw i t h. / s e l f e x e c . s ho rs h. / s e l f e x e c . s h . e c h o e c h o" T h i sl i n ea p p e a r sO N C Ei nt h es c r i p t ,y e ti tk e e p se c h o i n g . " e c h o" T h eP I Do ft h i si n s t a n c eo ft h es c r i p ti ss t i l l$ $ . "

D e m o n s t r a t e st h a tas u b s h e l li sn o tf o r k e do f f .

e c h o" = = = = = = = = = = = = = = = = = = = =H i tC t l Ct oe x i t= = = = = = = = = = = = = = = = = = = = " s l e e p1 e x e c$ 0 # S p a w n sa n o t h e ri n s t a n c eo ft h i ss a m es c r i p t # +t h a tr e p l a c e st h ep r e v i o u so n e .

e c h o" T h i sl i n ew i l ln e v e re c h o ! " #W h yn o t ? e x i t9 9 #W i l ln o te x i th e r e ! #E x i tc o d ew i l ln o tb e9 9 !

An exec also serves to reassign file descriptors. For example, e x e c< z z z f i l ereplaces s t d i nwith the file z z z f i l e . The e x e coption to find is n o tthe same as the exec shell builtin. shopt This command permits changing shell options on the fly (see Example 25-1 and Example 25-2). It often appears in the Bash startup files, but also has its uses in scripts. Needs version 2 or later of Bash.
s h o p tsc d s p e l l #A l l o w sm i n o rm i s s p e l l i n go fd i r e c t o r yn a m e sw i t h' c d ' #O p t i o nss e t s ,uu n s e t s . c d/ h p m e #O o p s !M i s t y p e d' / h o m e ' . p w d #/ h o m e #T h es h e l lc o r r e c t e dt h em i s s p e l l i n g .

caller Putting a caller command inside a function echoes to s t d o u tinformation about the caller of that function.
# ! / b i n / b a s h f u n c t i o n 1( ) { #I n s i d ef u n c t i o n 1( ) . c a l l e r0 #T e l lm ea b o u ti t . } f u n c t i o n 1 #L i n e9o fs c r i p t .

#9m a i nt e s t . s h #^ # ^ ^ ^ ^ # ^ ^ ^ ^ ^ ^ ^ c a l l e r0

L i n en u m b e rt h a tt h ef u n c t i o nw a sc a l l e df r o m . I n v o k e df r o m" m a i n "p a r to fs c r i p t . N a m eo fc a l l i n gs c r i p t .

#H a sn oe f f e c tb e c a u s ei t ' sn o ti n s i d eaf u n c t i o n .

A caller command can also return caller information from a script sourced within another script. Analogous to a function, this is a "subroutine call." You may find this command useful in debugging. Commands true A command that returns a successful (zero) exit status, but does nothing else.
b a s h $t r u e

b a s h $e c h o$ ? 0

#E n d l e s sl o o p w h i l et r u e #a l i a sf o r" : " d o o p e r a t i o n 1 o p e r a t i o n 2 . . . o p e r a t i o n n #N e e daw a yt ob r e a ko u to fl o o po rs c r i p tw i l lh a n g . d o n e

false A command that returns an unsuccessful exit status, but does nothing else.
b a s h $f a l s e b a s h $e c h o$ ? 1

#T e s t i n g" f a l s e " i ff a l s e t h e n e c h o" f a l s ee v a l u a t e s\ " t r u e \ " " e l s e e c h o" f a l s ee v a l u a t e s\ " f a l s e \ " " f i #f a l s ee v a l u a t e s" f a l s e "

#L o o p i n gw h i l e" f a l s e "( n u l ll o o p ) w h i l ef a l s e d o #T h ef o l l o w i n gc o d ew i l ln o te x e c u t e . o p e r a t i o n 1 o p e r a t i o n 2 . . . o p e r a t i o n n #N o t h i n gh a p p e n s ! d o n e

type [cmd] Similar to the which external command, type cmd identifies "cmd." Unlike which, type is a Bash builtin. The useful a option to type identifies k e y w o r d sand b u i l t i n s , and also locates system commands with identical names.
b a s h $t y p e' [ ' [i sas h e l lb u i l t i n b a s h $t y p ea' [ ' [i sas h e l lb u i l t i n [i s/ u s r / b i n / [

b a s h $t y p et y p e t y p ei sas h e l lb u i l t i n

The type command can be useful for testing whether a certain command exists. hash [cmds] Records the path name of specified commands -- in the shell hash table [65] -- so the shell or script will not need to

search the $PATH on subsequent calls to those commands. When hash is called with no arguments, it simply lists the commands that have been hashed. The roption resets the hash table. bind The bind builtin displays or modifies readline [66] key bindings. help Gets a short usage summary of a shell builtin. This is the counterpart to whatis, but for builtins. The display of help information got a much-needed update in the version 4 release of Bash.
b a s h $h e l pe x i t e x i t :e x i t[ n ] E x i tt h es h e l lw i t has t a t u so fN . I fNi so m i t t e d ,t h ee x i ts t a t u s i st h a to ft h el a s tc o m m a n de x e c u t e d .

15.1. Job Control Commands


Certain of the following job control commands take a job identifier as an argument. See the table at end of the chapter. jobs Lists the jobs running in the background, giving the job number. Not as useful as ps. It is all too easy to confuse jobs and processes. Certain builtins, such as kill, disown, and wait accept either a job number or a process number as an argument. The fg, bg and jobs commands accept only a job number.
b a s h $s l e e p1 0 0& [ 1 ]1 3 8 4 b a s h$j o b s [ 1 ] + R u n n i n g

s l e e p1 0 0&

"1" is the job number (jobs are maintained by the current shell). "1384" is the PID or process ID number (processes are maintained by the system). To kill this job/process, either a kill %1 or a kill 1384 works. Thanks, S.C. disown Remove job(s) from the shell's table of active jobs. fg, bg The fg command switches a job running in the background into the foreground. The bg command restarts a suspended job, and runs it in the background. If no job number is specified, then the fg or bg command acts upon the currently running job. wait Suspend script execution until all jobs running in background have terminated, or until the job number or process ID specified as an option terminates. Returns the exit status of waited-for command. You may use the wait command to prevent a script from exiting before a background job finishes executing (this

would create a dreaded orphan process). Example 15-26. Waiting for a process to finish before proceeding
# ! / b i n / b a s h R O O T _ U I D = 0 #O n l yu s e r sw i t h$ U I D0h a v er o o tp r i v i l e g e s . E _ N O T R O O T = 6 5 E _ N O P A R A M S = 6 6 i f[" $ U I D "n e" $ R O O T _ U I D "] t h e n e c h o" M u s tb er o o tt or u nt h i ss c r i p t . " #" R u na l o n gk i d ,i t ' sp a s ty o u rb e d t i m e . " e x i t$ E _ N O T R O O T f i i f[z" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i n d s t r i n g " e x i t$ E _ N O P A R A M S f i

e c h o" U p d a t i n g' l o c a t e 'd a t a b a s e . . . " e c h o" T h i sm a yt a k eaw h i l e . " u p d a t e d b/ u s r& #M u s tb er u na sr o o t . w a i t #D o n ' tr u nt h er e s to ft h es c r i p tu n t i l' u p d a t e d b 'f i n i s h e d . #Y o uw a n tt h et h ed a t a b a s eu p d a t e db e f o r el o o k i n gu pt h ef i l en a m e . l o c a t e$ 1 # W i t h o u tt h e' w a i t 'c o m m a n d ,i nt h ew o r s ec a s es c e n a r i o , # +t h es c r i p tw o u l de x i tw h i l e' u p d a t e d b 'w a ss t i l lr u n n i n g , # +l e a v i n gi ta sa no r p h a np r o c e s s . e x i t0

Optionally, wait can take a job identifier as an argument, for example, w a i t % 1or w a i t$ P P I D . [67] See the job id table. Within a script, running a command in the background with an ampersand (&) may cause the script to hang until ENTER is hit. This seems to occur with commands that write to s t d o u t . It can be a major annoyance.
# ! / b i n / b a s h #t e s t . s h l sl& e c h o" D o n e . " b a s h $. / t e s t . s h D o n e . [ b o z o @ l o c a l h o s tt e s t s c r i p t s ] $t o t a l1 r w x r x r x 1b o z o b o z o 3 4O c t1 11 5 : 0 9t e s t . s h _

As Walter Brameld IV explains it: As far as I can tell, such scripts don't actually hang. It just seems that they do because the background command writes text to the console after the prompt. The user gets the impression that the prompt was never displayed. Here's the sequence of events:

1. Script launches background command. 2. Script exits. 3. Shell displays the prompt. 4. Background command continues running and writing text to the console. 5. Background command finishes. 6. User doesn't see a prompt at the bottom of the output, thinks script is hanging. Placing a wait after the background command seems to remedy this.
# ! / b i n / b a s h #t e s t . s h l sl& e c h o" D o n e . " w a i t b a s h $. / t e s t . s h D o n e . [ b o z o @ l o c a l h o s tt e s t s c r i p t s ] $t o t a l1 r w x r x r x 1b o z o b o z o 3 4O c t1 11 5 : 0 9t e s t . s h

Redirecting the output of the command to a file or even to / d e v / n u l lalso takes care of this problem. suspend This has a similar effect to Control- Z, but it suspends the shell (the shell's parent process should resume it at an appropriate time). logout Exit a login shell, optionally specifying an exit status. times Gives statistics on the system time elapsed when executing commands, in the following form:
0 m 0 . 0 2 0 s0 m 0 . 0 2 0 s

This capability is of relatively limited value, since it is not common to profile and benchmark shell scripts. kill Forcibly terminate a process by sending it an appropriate terminate signal (see Example 17-6). Example 15-27. A script that kills itself
# ! / b i n / b a s h #s e l f d e s t r u c t . s h k i l l$ $ #S c r i p tk i l l si t so w np r o c e s sh e r e . #R e c a l lt h a t" $ $ "i st h es c r i p t ' sP I D . e c h o" T h i sl i n ew i l ln o te c h o . " #I n s t e a d ,t h es h e l ls e n d sa" T e r m i n a t e d "m e s s a g et os t d o u t . e x i t0 #N o r m a le x i t ?N o !

# A f t e rt h i ss c r i p tt e r m i n a t e sp r e m a t u r e l y , # +w h a te x i ts t a t u sd o e si tr e t u r n ? #

#s hs e l f d e s t r u c t . s h #e c h o$ ? #1 4 3 # #1 4 3=1 2 8+1 5 # T E R Ms i g n a l k i l lllists all the signals (as does the file / u s r / i n c l u d e / a s m / s i g n a l . h ).

Ak i l l9is a sure kill, which will usually terminate a process that stubbornly refuses to die with a plain kill. Sometimes, a k i l l1 5works. A zombie process, that is, a child process that has terminated, but that the parent process has not (yet) killed, cannot be killed by a logged-on user -- you can't kill something that is already dead -- but init will generally clean it up sooner or later. killall The killall command kills a running process by name, rather than by process ID. If there are multiple instances of a particular command running, then doing a killall on that command will terminate them all. This refers to the killall command in / u s r / b i n , not the killall script in / e t c / r c . d / i n i t . d . command The command directive disables aliases and functions for the command immediately following it.
b a s h $c o m m a n dl s

This is one of three shell directives that effect script command processing. The others are builtin and enable. builtin Invoking builtin BUILTIN_COMMAND runs the command B U I L T I N _ C O M M A N Das a shell builtin, temporarily disabling both functions and external system commands with the same name. enable This either enables or disables a shell builtin command. As an example, e n a b l enk i l ldisables the shell builtin kill, so that when Bash subsequently encounters kill, it invokes the external command / b i n / k i l l . The aoption to enable lists all the shell builtins, indicating whether or not they are enabled. The ff i l e n a m e option lets enable load a builtin as a shared library (DLL) module from a properly compiled object file. [68]. autoload This is a port to Bash of the ksh autoloader. With autoload in place, a function with an autoload declaration will load from an external file at its first invocation. [69] This saves system resources. Note that autoload is not a part of the core Bash installation. It needs to be loaded in with e n a b l ef(see above). Table 15-1. Job identifiers Notation Meaning
% N % S % ? S % % % + % -

Job number [N] Invocation (command-line) of job begins with string S Invocation (command-line) of job contains within it string S "current" job (last job stopped in foreground or started in background) "current" job (last job stopped in foreground or started in background) Last job

$ !

Last background process

Chapter 16. External Filters, Programs and Commands


Standard UNIX commands make shell scripts more versatile. The power of scripts comes from coupling system commands and shell directives with simple programming constructs.

16.1. Basic Commands


The first commands a novice learns ls The basic file "list" command. It is all too easy to underestimate the power of this humble command. For example, using the R , recursive option, ls provides a tree-like listing of a directory structure. Other useful options are S , sort listing by file size, t , sort by file modification time, v , sort by (numerical) version numbers embedded in the filenames, [70] b , show escape characters, and i , show file inodes (see Example 16-4).
b a s h $l sl r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 0 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 1 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 2 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 2 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 3 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 9C h a p t e r _ h e a d i n g s . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 9P r e f a c e . t x t

b a s h $l sl v t o t a l0 r w r w r -1b o z ob o z o0S e p1 41 8 : 4 9C h a p t e r _ h e a d i n g s . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 9P r e f a c e . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 2 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 3 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 0 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 1 . t x t r w r w r -1b o z ob o z o0S e p1 41 8 : 4 4c h a p t e r 1 2 . t x t

The ls command returns a non-zero exit status when attempting to list a non-existent file.
b a s h $l sa b c l s :a b c :N os u c hf i l eo rd i r e c t o r y

b a s h $e c h o$ ? 2

Example 16-1. Using ls to create a table of contents for burning a CDR disk
# ! / b i n / b a s h #e x 4 0 . s h( b u r n c d . s h ) #S c r i p tt oa u t o m a t eb u r n i n gaC D R .

S P E E D = 1 0 #M a yu s eh i g h e rs p e e di fy o u rh a r d w a r es u p p o r t si t . I M A G E F I L E = c d i m a g e . i s o C O N T E N T S F I L E = c o n t e n t s #D E V I C E = / d e v / c d r o m F o ro l d e rv e r s i o n so fc d r e c o r d D E V I C E = " 1 , 0 , 0 " D E F A U L T D I R = / o p t #T h i si st h ed i r e c t o r yc o n t a i n i n gt h ed a t at ob eb u r n e d . #M a k es u r ei te x i s t s . #E x e r c i s e :A d dat e s tf o rt h i s . #U s e sJ o e r gS c h i l l i n g ' s" c d r e c o r d "p a c k a g e : #h t t p : / / w w w . f o k u s . f h g . d e / u s r / s c h i l l i n g / c d r e c o r d . h t m l # I ft h i ss c r i p ti n v o k e da sa no r d i n a r yu s e r ,m a yn e e dt os u i dc d r e c o r d # +c h m o du + s/ u s r / b i n / c d r e c o r d ,a sr o o t . # O fc o u r s e ,t h i sc r e a t e sas e c u r i t yh o l e ,t h o u g har e l a t i v e l ym i n o ro n e . i f[z" $ 1 "] t h e n I M A G E _ D I R E C T O R Y = $ D E F A U L T D I R #D e f a u l td i r e c t o r y ,i fn o ts p e c i f i e do nc o m m a n d l i n e . e l s e I M A G E _ D I R E C T O R Y = $ 1 f i #C r e a t ea" t a b l eo fc o n t e n t s "f i l e . l sl R F$ I M A G E _ D I R E C T O R Y>$ I M A G E _ D I R E C T O R Y / $ C O N T E N T S F I L E #T h e" l "o p t i o ng i v e sa" l o n g "f i l el i s t i n g . #T h e" R "o p t i o nm a k e st h el i s t i n gr e c u r s i v e . #T h e" F "o p t i o nm a r k st h ef i l et y p e s( d i r e c t o r i e sg e tat r a i l i n g/ ) . e c h o" C r e a t i n gt a b l eo fc o n t e n t s . " #C r e a t ea ni m a g ef i l ep r e p a r a t o r yt ob u r n i n gi to n t ot h eC D R . m k i s o f sro$ I M A G E F I L E$ I M A G E _ D I R E C T O R Y e c h o" C r e a t i n gI S O 9 6 6 0f i l es y s t e mi m a g e( $ I M A G E F I L E ) . " #B u r nt h eC D R . e c h o" B u r n i n gt h ed i s k . " e c h o" P l e a s eb ep a t i e n t ,t h i sw i l lt a k eaw h i l e . " w o d i mvi s o s i z ed e v = $ D E V I C E$ I M A G E F I L E # I nn e w e rL i n u xd i s t r o s ,t h e" w o d i m "u t i l i t ya s s u m e st h e # +f u n c t i o n a l i t yo f" c d r e c o r d . " e x i t c o d e = $ ? e c h o" E x i tc o d e=$ e x i t c o d e " e x i t$ e x i t c o d e

cat, tac cat, an acronym for concatenate, lists a file to s t d o u t . When combined with redirection (> or >>), it is commonly used to concatenate files.
#U s e so f' c a t ' c a tf i l e n a m e c a tf i l e . 1f i l e . 2f i l e . 3>f i l e . 1 2 3 #L i s t st h ef i l e . #C o m b i n e st h r e ef i l e si n t oo n e .

The noption to cat inserts consecutive numbers before all lines of the target file(s). The boption numbers only the non-blank lines. The voption echoes nonprintable characters, using ^ notation. The soption squeezes multiple consecutive blank lines into a single blank line. See also Example 16-28 and Example 16-24. In a pipe, it may be more efficient to redirect the s t d i nto a file, rather than to cat the file.
c a tf i l e n a m e|t ra zA Z t ra zA Z<f i l e n a m e # S a m ee f f e c t ,b u ts t a r t so n el e s sp r o c e s s , # +a n da l s od i s p e n s e sw i t ht h ep i p e .

tac, is the inverse of cat , listing a file backwards from its end. rev reverses each line of a file, and outputs to s t d o u t . This does not have the same effect as tac, as it preserves the order of the lines, but flips each one around (mirror image).
b a s h $c a tf i l e 1 . t x t T h i si sl i n e1 . T h i si sl i n e2 .

b a s h $t a cf i l e 1 . t x t T h i si sl i n e2 . T h i si sl i n e1 .

b a s h $r e vf i l e 1 . t x t . 1e n i ls is i h T . 2e n i ls is i h T

cp This is the file copy command. c pf i l e 1f i l e 2copies f i l e 1to f i l e 2 , overwriting f i l e 2if it already exists (see Example 16-6). Particularly useful are the aarchive flag (for copying an entire directory tree), the uupdate flag (which prevents overwriting identically-named newer files), and the rand Rrecursive flags.
c pus o u r c e _ d i r / *d e s t _ d i r # " S y n c h r o n i z e "d e s t _ d i rt os o u r c e _ d i r # + b yc o p y i n go v e ra l ln e w e ra n dn o tp r e v i o u s l ye x i s t i n gf i l e s .

mv This is the file move command. It is equivalent to a combination of cp and rm. It may be used to move multiple files to a directory, or even to rename a directory. For some examples of using mv in a script, see Example 10-11 and Example A-2. When used in a non-interactive script, mv takes the f(force) option to bypass user input. When a directory is moved to a preexisting directory, it becomes a subdirectory of the destination directory.
b a s h $m vs o u r c e _ d i r e c t o r yt a r g e t _ d i r e c t o r y b a s h $l sl Ft a r g e t _ d i r e c t o r y t o t a l1 d r w x r w x r x 2b o z o b o z o

1 0 2 4M a y2 81 9 : 2 0s o u r c e _ d i r e c t o r y /

rm Delete (remove) a file or files. The foption forces removal of even readonly files, and is useful for bypassing user input in a script. The rm command will, by itself, fail to remove filenames beginning with a dash. Why? Because rm sees a dash-prefixed filename as an option.
b a s h $r mb a d n a m e

r m :i n v a l i do p t i o n-b T r y` r mh e l p 'f o rm o r ei n f o r m a t i o n .

One clever workaround is to precede the filename with a " -- " (the end-of-options flag).
b a s h $r m-b a d n a m e

Another method to is to preface the filename to be removed with a d o t s l a s h.


b a s h $r m. / b a d n a m e

When used with the recursive flag r , this command removes files all the way down the directory tree from the current directory. A careless rm -rf * can wipe out a big chunk of a directory structure. rmdir Remove directory. The directory must be empty of all files -- including "invisible" dotfiles [71] -- for this command to succeed. mkdir Make directory, creates a new directory. For example, m k d i rpp r o j e c t / p r o g r a m s / D e c e m b e rcreates the named directory. The poption automatically creates any necessary parent directories. chmod Changes the attributes of an existing file or directory (see Example 15-14).
c h m o d+ xf i l e n a m e #M a k e s" f i l e n a m e "e x e c u t a b l ef o ra l lu s e r s . c h m o du + sf i l e n a m e #S e t s" s u i d "b i to n" f i l e n a m e "p e r m i s s i o n s . #A no r d i n a r yu s e rm a ye x e c u t e" f i l e n a m e "w i t hs a m ep r i v i l e g e sa st h ef i l e ' so w n e r . #( T h i sd o e sn o ta p p l yt os h e l ls c r i p t s . ) c h m o d6 4 4f i l e n a m e # M a k e s" f i l e n a m e "r e a d a b l e / w r i t a b l et oo w n e r ,r e a d a b l et oo t h e r s # +( o c t a lm o d e ) . c h m o d4 4 4f i l e n a m e # M a k e s" f i l e n a m e "r e a d o n l yf o ra l l . # M o d i f y i n gt h ef i l e( f o re x a m p l e ,w i t hat e x te d i t o r ) # +n o ta l l o w e df o rau s e rw h od o e sn o to w nt h ef i l e( e x c e p tf o rr o o t ) , # +a n de v e nt h ef i l eo w n e rm u s tf o r c eaf i l e s a v e # +i fs h em o d i f i e st h ef i l e . # S a m er e s t r i c t i o n sa p p l yf o rd e l e t i n gt h ef i l e . c h m o d1 7 7 7d i r e c t o r y n a m e # G i v e se v e r y o n er e a d ,w r i t e ,a n de x e c u t ep e r m i s s i o ni nd i r e c t o r y , # +h o w e v e ra l s os e t st h e" s t i c k yb i t " . # T h i sm e a n st h a to n l yt h eo w n e ro ft h ed i r e c t o r y , # +o w n e ro ft h ef i l e ,a n d ,o fc o u r s e ,r o o t # +c a nd e l e t ea n yp a r t i c u l a rf i l ei nt h a td i r e c t o r y . c h m o d1 1 1d i r e c t o r y n a m e # G i v e se v e r y o n ee x e c u t e o n l yp e r m i s s i o ni nad i r e c t o r y . # T h i sm e a n st h a ty o uc a ne x e c u t ea n dR E A Dt h ef i l e si nt h a td i r e c t o r y # +( e x e c u t ep e r m i s s i o nn e c e s s a r i l yi n c l u d e sr e a dp e r m i s s i o n # +b e c a u s ey o uc a n ' te x e c u t eaf i l ew i t h o u tb e i n ga b l et or e a di t ) . # B u ty o uc a n ' tl i s tt h ef i l e so rs e a r c hf o rt h e mw i t ht h e" f i n d "c o m m a n d . # T h e s er e s t r i c t i o n sd on o ta p p l yt or o o t . c h m o d0 0 0d i r e c t o r y n a m e

# N op e r m i s s i o n sa ta l lf o rt h a td i r e c t o r y . # C a n ' tr e a d ,w r i t e ,o re x e c u t ef i l e si ni t . # C a n ' te v e nl i s tf i l e si ni to r" c d "t oi t . # B u t ,y o uc a nr e n a m e( m v )t h ed i r e c t o r y # +o rd e l e t ei t( r m d i r )i fi ti se m p t y . # Y o uc a ne v e ns y m l i n kt of i l e si nt h ed i r e c t o r y , # +b u ty o uc a n ' tr e a d ,w r i t e ,o re x e c u t et h es y m l i n k s . # T h e s er e s t r i c t i o n sd on o ta p p l yt or o o t .

chattr Change file attributes. This is analogous to chmod above, but with different options and a different invocation syntax, and it works only on ext2/ext3 filesystems. One particularly interesting chattr option is i . A chattr +i f i l e n a m emarks the file as immutable. The file cannot be modified, linked to, or deleted, not even by root . This file attribute can be set or removed only by root . In a similar fashion, the aoption marks the file as append only.
r o o t #c h a t t r+ if i l e 1 . t x t

r o o t #r mf i l e 1 . t x t r m :r e m o v ew r i t e p r o t e c t e dr e g u l a rf i l e` f i l e 1 . t x t ' ?y r m :c a n n o tr e m o v e` f i l e 1 . t x t ' :O p e r a t i o nn o tp e r m i t t e d

If a file has the s(secure) attribute set, then when it is deleted its block is overwritten with binary zeroes. [72] If a file has the u(undelete) attribute set, then when it is deleted, its contents can still be retrieved (undeleted). If a file has the c(compress) attribute set, then it will automatically be compressed on writes to disk, and uncompressed on reads. The file attributes set with chattr do not show in a file listing (ls -l). ln Creates links to pre-existings files. A "link" is a reference to a file, an alternate name for it. The ln command permits referencing the linked file by more than one name and is a superior alternative to aliasing (see Example 4-6). The ln creates only a reference, a pointer to the file only a few bytes in size. The ln command is most often used with the s , symbolic or "soft" link flag. Advantages of using the sflag are that it permits linking across file systems or to directories. The syntax of the command is a bit tricky. For example: l nso l d f i l en e w f i l elinks the previously existing o l d f i l eto the newly created link, n e w f i l e . If a file named n e w f i l ehas previously existed, an error message will result. Which type of link to use? As John Macdonald explains it: Both of these [types of links] provide a certain measure of dual reference -- if you edit the contents of the file using any name, your changes will affect both the original name and either a hard or soft new name. The differences between them occurs when you work at a higher level. The advantage of a hard link is that the new name is totally independent of the old name -- if you remove or rename the old name, that does not affect the hard link, which continues to point to the data while it would leave a soft link hanging pointing to the old name which is no longer there. The advantage of a soft link is that it can refer to a different file system (since it is just a reference to a file

name, not to actual data). And, unlike a hard link, a symbolic link can refer to a directory. Links give the ability to invoke a script (or any other type of executable) with multiple names, and having that script behave according to how it was invoked. Example 16-2. Hello or Good-bye
# ! / b i n / b a s h #h e l l o . s h :S a y i n g" h e l l o "o r" g o o d b y e " # + d e p e n d i n go nh o ws c r i p ti si n v o k e d . #M a k eal i n ki nc u r r e n tw o r k i n gd i r e c t o r y( $ P W D )t ot h i ss c r i p t : # l nsh e l l o . s hg o o d b y e #N o w ,t r yi n v o k i n gt h i ss c r i p tb o t hw a y s : #. / h e l l o . s h #. / g o o d b y e

H E L L O _ C A L L = 6 5 G O O D B Y E _ C A L L = 6 6 i f[$ 0=" . / g o o d b y e "] t h e n e c h o" G o o d b y e ! " #S o m eo t h e rg o o d b y e t y p ec o m m a n d s ,a sa p p r o p r i a t e . e x i t$ G O O D B Y E _ C A L L f i e c h o" H e l l o ! " #S o m eo t h e rh e l l o t y p ec o m m a n d s ,a sa p p r o p r i a t e . e x i t$ H E L L O _ C A L L

man, info These commands access the manual and information pages on system commands and installed utilities. When available, the info pages usually contain more detailed descriptions than do the man pages. There have been various attempts at "automating" the writing of man pages. For a script that makes a tentative first step in that direction, see Example A-39.

16.2. Complex Commands


Commands for more advanced users find -exec C O M M A N D\; Carries out C O M M A N Don each file that find matches. The command sequence terminates with ; (the ";" is escaped to make certain the shell passes it to find literally, without interpreting it as a special character).
b a s h $f i n d~ /n a m e' * . t x t ' / h o m e / b o z o / . k d e / s h a r e / a p p s / k a r m / k a r m d a t a . t x t / h o m e / b o z o / m i s c / i r m e y c . t x t / h o m e / b o z o / t e s t s c r i p t s / 1 . t x t

If C O M M A N Dcontains {}, then find substitutes the full path name of the selected file for "{}".
f i n d~ /n a m e' c o r e * 'e x e cr m{ }\ ; #R e m o v e sa l lc o r ed u m pf i l e sf r o mu s e r ' sh o m ed i r e c t o r y .

f i n d/ h o m e / b o z o / p r o j e c t sm t i m e1 # ^ N o t em i n u ss i g n ! # L i s t sa l lf i l e si n/ h o m e / b o z o / p r o j e c t sd i r e c t o r yt r e e # +t h a tw e r em o d i f i e dw i t h i nt h el a s td a y( c u r r e n t _ d a y-1 ) . # f i n d/ h o m e / b o z o / p r o j e c t sm t i m e1 # S a m ea sa b o v e ,b u tm o d i f i e d* e x a c t l y *o n ed a ya g o . # # m t i m e=l a s tm o d i f i c a t i o nt i m eo ft h et a r g e tf i l e # c t i m e=l a s ts t a t u sc h a n g et i m e( v i a' c h m o d 'o ro t h e r w i s e ) # a t i m e=l a s ta c c e s st i m e D I R = / h o m e / b o z o / j u n k _ f i l e s f i n d" $ D I R "t y p efa t i m e+ 5e x e cr m{ }\ ; # ^ ^ ^ # C u r l yb r a c k e t sa r ep l a c e h o l d e rf o rt h ep a t hn a m eo u t p u tb y" f i n d . " # # D e l e t e sa l lf i l e si n" / h o m e / b o z o / j u n k _ f i l e s " # +t h a th a v en o tb e e na c c e s s e di n* a tl e a s t *5d a y s( p l u ss i g n. . .+ 5 ) . # # " t y p ef i l e t y p e " ,w h e r e # f=r e g u l a rf i l e # d=d i r e c t o r y # l=s y m b o l i cl i n k ,e t c . # # ( T h e' f i n d 'm a n p a g ea n di n f op a g eh a v ec o m p l e t eo p t i o nl i s t i n g s . ) f i n d/ e t ce x e cg r e p' [ 0 9 ] [ 0 9 ] * [ . ] [ 0 9 ] [ 0 9 ] * [ . ] [ 0 9 ] [ 0 9 ] * [ . ] [ 0 9 ] [ 0 9 ] * '{ }\ ; #F i n d sa l lI Pa d d r e s s e s( x x x . x x x . x x x . x x x )i n/ e t cd i r e c t o r yf i l e s . #T h e r eaf e we x t r a n e o u sh i t s .C a nt h e yb ef i l t e r e do u t ? #P o s s i b l yb y : f i n d/ e t ct y p efe x e cc a t' { } '\ ;|t rc' . [ : d i g i t : ] '' \ n '\ |g r e p' ^ [ ^ . ] [ ^ . ] * \ . [ ^ . ] [ ^ . ] * \ . [ ^ . ] [ ^ . ] * \ . [ ^ . ] [ ^ . ] * $ ' # # [ : d i g i t : ]i so n eo ft h ec h a r a c t e rc l a s s e s # +i n t r o d u c e dw i t ht h eP O S I X1 0 0 3 . 2s t a n d a r d . #T h a n k s ,S t p h a n eC h a z e l a s .

The e x e coption to find should not be confused with the exec shell builtin. Example 16-3. Badname, eliminate file names in current directory containing bad characters and whitespace.
# ! / b i n / b a s h #b a d n a m e . s h #D e l e t ef i l e n a m e si nc u r r e n td i r e c t o r yc o n t a i n i n gb a dc h a r a c t e r s . f o rf i l e n a m ei n* d o b a d n a m e = ` e c h o" $ f i l e n a m e "|s e dn/ [ \ + \ { \ ; \ " \ \ \ = \ ? ~ \ ( \ ) \ < \ > \ & \ * \ | \ $ ] / p ` #b a d n a m e = ` e c h o" $ f i l e n a m e "|s e dn' / [ + { ; " \ = ? ~ ( ) < > & * | $ ] / p ' ` a l s ow o r k s . #D e l e t e sf i l e sc o n t a i n i n gt h e s en a s t i e s : +{;"\=?~()<>&*|$ # r m$ b a d n a m e2 > / d e v / n u l l # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^E r r o rm e s s a g e sd e e p s i x e d . d o n e #N o w ,t a k ec a r eo ff i l e sc o n t a i n i n ga l lm a n n e ro fw h i t e s p a c e . f i n d.n a m e" ** "e x e cr mf{ }\ ; #T h ep a t hn a m eo ft h ef i l et h a t_ f i n d _f i n d sr e p l a c e st h e" { } " . #T h e' \ 'e n s u r e st h a tt h e' ; 'i si n t e r p r e t e dl i t e r a l l y ,a se n do fc o m m a n d .

e x i t0 # #C o m m a n d sb e l o wt h i sl i n ew i l ln o te x e c u t eb e c a u s eo f_ e x i t _c o m m a n d . #A na l t e r n a t i v et ot h ea b o v es c r i p t : f i n d.n a m e' * [ + { ; " \ \ = ? ~ ( ) < > & * | $] * 'm a x d e p t h0\ e x e cr mf' { } '\ ; # T h e" m a x d e p t h0 "o p t i o ne n s u r e st h a t_ f i n d _w i l ln o ts e a r c h # +s u b d i r e c t o r i e sb e l o w$ P W D . #( T h a n k s ,S . C . )

Example 16-4. Deleting a file by its inode number


# ! / b i n / b a s h #i d e l e t e . s h :D e l e t i n gaf i l eb yi t si n o d en u m b e r . # T h i si su s e f u lw h e naf i l e n a m es t a r t sw i t ha ni l l e g a lc h a r a c t e r , # +s u c ha s?o r. A R G C O U N T = 1 E _ W R O N G A R G S = 7 0 E _ F I L E _ N O T _ E X I S T = 7 1 E _ C H A N G E D _ M I N D = 7 2 #F i l e n a m ea r gm u s tb ep a s s e dt os c r i p t .

i f[$ #n e" $ A R G C O U N T "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ W R O N G A R G S f i i f[!e" $ 1 "] t h e n e c h o" F i l e\ " " $ 1 " \ "d o e sn o te x i s t . " e x i t$ E _ F I L E _ N O T _ E X I S T f i i n u m = ` l si|g r e p" $ 1 "|a w k' { p r i n t$ 1 } ' ` #i n u m=i n o d e( i n d e xn o d e )n u m b e ro ff i l e ##E v e r yf i l eh a sa ni n o d e ,ar e c o r dt h a th o l d si t sp h y s i c a la d d r e s si n f o . #e c h o ;e c h on" A r ey o ua b s o l u t e l ys u r ey o uw a n tt od e l e t e\ " $ 1 \ "( y / n ) ?" #T h e' v 'o p t i o nt o' r m 'a l s oa s k st h i s . r e a da n s w e r c a s e" $ a n s w e r "i n [ n N ] )e c h o" C h a n g e dy o u rm i n d ,h u h ? " e x i t$ E _ C H A N G E D _ M I N D ; ; * ) e c h o" D e l e t i n gf i l e\ " $ 1 \ " . " ; ; e s a c f i n d.i n u m$ i n u me x e cr m{ }\ ; # ^ ^ # C u r l yb r a c k e t sa r ep l a c e h o l d e r # + f o rt e x to u t p u tb y" f i n d . " e c h o" F i l e" \ " $ 1 " \ "d e l e t e d ! " e x i t0

The find command also works without the e x e coption.


# ! / b i n / b a s h # F i n ds u i dr o o tf i l e s . # As t r a n g es u i df i l em i g h ti n d i c a t eas e c u r i t yh o l e , # +o re v e nas y s t e mi n t r u s i o n .

d i r e c t o r y = " / u s r / s b i n " #M i g h ta l s ot r y/ s b i n ,/ b i n ,/ u s r / b i n ,/ u s r / l o c a l / b i n ,e t c . p e r m i s s i o n s = " + 4 0 0 0 " #s u i dr o o t( d a n g e r o u s ! )

f o rf i l ei n$ (f i n d" $ d i r e c t o r y "p e r m" $ p e r m i s s i o n s ") d o l sl t Fa u t h o r" $ f i l e " d o n e

See Example 16-30, Example 3-4, and Example 11-9 for scripts using find. Its manpage provides more detail on this complex and powerful command. xargs A filter for feeding arguments to a command, and also a tool for assembling the commands themselves. It breaks a data stream into small enough chunks for filters and commands to process. Consider it as a powerful replacement for backquotes. In situations where command substitution fails with a too many arguments error, substituting xargs often works. [73] Normally, xargs reads from s t d i nor from a pipe, but it can also be given the output of a file. The default command for xargs is echo. This means that input piped to xargs may have linefeeds and other whitespace characters stripped out.
b a s h $l sl t o t a l0 r w r w r r w r w r -

1b o z o b o z o 1b o z o b o z o

0J a n2 92 3 : 5 8f i l e 1 0J a n2 92 3 : 5 8f i l e 2

b a s h $l sl|x a r g s t o t a l0r w r w r -1b o z ob o z o0J a n2 92 3 : 5 8f i l e 1r w r w r -1b o z ob o z o0J a n . . .

b a s h $f i n d~ / m a i lt y p ef|x a r g sg r e p" L i n u x " . / m i s c : U s e r A g e n t :s l r n / 0 . 9 . 8 . 1( L i n u x ) . / s e n t m a i l j u l 2 0 0 5 :h o s t e db yt h eL i n u xD o c u m e n t a t i o nP r o j e c t . . / s e n t m a i l j u l 2 0 0 5 :( L i n u xD o c u m e n t a t i o nP r o j e c tS i t e ,r t fv e r s i o n ) . / s e n t m a i l j u l 2 0 0 5 :S u b j e c t :C r i t i c i s mo fB o z o ' sW i n d o w s / L i n u xa r t i c l e . / s e n t m a i l j u l 2 0 0 5 :w h i l em e n t i o n i n gt h a tt h eL i n u xe x t 2 / e x t 3f i l e s y s t e m ...

l s|x a r g splg z i pgzips every file in current directory,

one at a time, prompting before each operation.

Note that xargs processes the arguments passed to it sequentially, one at a time.
b a s h $f i n d/ u s r / b i n|x a r g sf i l e / u s r / b i n : d i r e c t o r y / u s r / b i n / f o o m a t i c p p d o p t i o n s : ...

p e r ls c r i p tt e x te x e c u t a b l e

An interesting xargs option is nN N , which limits to N Nthe number of arguments passed.


l s|x a r g sn8e c h olists the files in the current directory in 8columns.

Another useful option is 0 , in combination with f i n dp r i n t 0or g r e pl Z . This allows handling arguments containing whitespace or quotes.

f i n d/t y p efp r i n t 0|x a r g s0g r e pl i w ZG U I|x a r g s0r mf g r e pr l i w ZG U I/|x a r g s0r mf

Either of the above will remove any file containing "GUI". (Thanks, S.C.) Or:
c a t/ p r o c / " $ p i d " / " $ O P T I O N "|x a r g s0e c h o # F o r m a t so u t p u t : ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # F r o mH a nH o l l ' sf i x u po f" g e t c o m m a n d l i n e . s h " # +s c r i p ti n" / d e va n d/ p r o c "c h a p t e r .

The Poption to xargs permits running processes in parallel. This speeds up execution in a machine with a multicore CPU.
# ! / b i n / b a s h l s* g i f|x a r g stn 1P 2g i f 2 p n g #C o n v e r t sa l lt h eg i fi m a g e si nc u r r e n td i r e c t o r yt op n g . #O p t i o n s : #= = = = = = = #t P r i n tc o m m a n dt os t d e r r . #n 1 A tm o s t1a r g u m e n tp e rc o m m a n dl i n e . #P 2 R u nu pt o2p r o c e s s e ss i m u l t a n e o u s l y . #T h a n ky o u ,R o b e r t oP o l l i ,f o rt h ei n s p i r a t i o n .

Example 16-5. Logfile: Using xargs to monitor system log


# ! / b i n / b a s h #G e n e r a t e sal o gf i l ei nc u r r e n td i r e c t o r y #f r o mt h et a i le n do f/ v a r / l o g / m e s s a g e s . #N o t e :/ v a r / l o g / m e s s a g e sm u s tb ew o r l dr e a d a b l e #i ft h i ss c r i p ti n v o k e db ya no r d i n a r yu s e r . # # r o o tc h m o d6 4 4/ v a r / l o g / m e s s a g e s L I N E S = 5 (d a t e ;u n a m ea)> > l o g f i l e #T i m ea n dm a c h i n en a m e e c h o-> > l o g f i l e t a i ln$ L I N E S/ v a r / l o g / m e s s a g e s|x a r g s|f m ts> > l o g f i l e e c h o> > l o g f i l e e c h o> > l o g f i l e e x i t0 # N o t e : # # A sF r a n kW a n gp o i n t so u t , # +u n m a t c h e dq u o t e s( e i t h e rs i n g l eo rd o u b l eq u o t e s )i nt h es o u r c ef i l e # +m a yg i v ex a r g si n d i g e s t i o n . # # H es u g g e s t st h ef o l l o w i n gs u b s t i t u t i o nf o rl i n e1 5 : # t a i ln$ L I N E S/ v a r / l o g / m e s s a g e s|t rd" \ " ' "|x a r g s|f m ts> > l o g f i l e

# E x e r c i s e : # # M o d i f yt h i ss c r i p tt ot r a c kc h a n g e si n/ v a r / l o g / m e s s a g e sa ti n t e r v a l s

# +o f2 0m i n u t e s . # H i n t :U s et h e" w a t c h "c o m m a n d .

As in find, a curly bracket pair serves as a placeholder for replacement text. Example 16-6. Copying files in current directory to another
# ! / b i n / b a s h #c o p y d i r . s h # C o p y( v e r b o s e )a l lf i l e si nc u r r e n td i r e c t o r y( $ P W D ) # +t od i r e c t o r ys p e c i f i e do nc o m m a n d l i n e . E _ N O A R G S = 8 5 i f[z" $ 1 "] #E x i ti fn oa r g u m e n tg i v e n . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `d i r e c t o r y t o c o p y t o " e x i t$ E _ N O A R G S f i l s.|x a r g sitc p. / { }$ 1 # ^ ^^ ^ ^ ^ # ti s" v e r b o s e "( o u t p u tc o m m a n d l i n et os t d e r r )o p t i o n . # ii s" r e p l a c es t r i n g s "o p t i o n . # { }i sap l a c e h o l d e rf o ro u t p u tt e x t . # T h i si ss i m i l a rt ot h eu s eo fac u r l y b r a c k e tp a i ri n" f i n d . " # # L i s tt h ef i l e si nc u r r e n td i r e c t o r y( l s. ) , # +p a s st h eo u t p u to f" l s "a sa r g u m e n t st o" x a r g s "( ito p t i o n s ) , # +t h e nc o p y( c p )t h e s ea r g u m e n t s( { } )t on e wd i r e c t o r y( $ 1 ) . # # T h en e tr e s u l ti st h ee x a c te q u i v a l e n to f # + c p*$ 1 # +u n l e s sa n yo ft h ef i l e n a m e sh a se m b e d d e d" w h i t e s p a c e "c h a r a c t e r s . e x i t0

Example 16-7. Killing processes by name


# ! / b i n / b a s h #k i l l b y n a m e . s h :K i l l i n gp r o c e s s e sb yn a m e . #C o m p a r et h i ss c r i p tw i t hk i l l p r o c e s s . s h . # F o ri n s t a n c e , # +t r y" . / k i l l b y n a m e . s hx t e r m "# +a n dw a t c ha l lt h ex t e r m so ny o u rd e s k t o pd i s a p p e a r . # W a r n i n g : # # T h i si saf a i r l yd a n g e r o u ss c r i p t . # R u n n i n gi tc a r e l e s s l y( e s p e c i a l l ya sr o o t ) # +c a nc a u s ed a t al o s sa n do t h e ru n d e s i r a b l ee f f e c t s . E _ B A D A R G S = 6 6 i ft e s tz" $ 1 " #N oc o m m a n d l i n ea r gs u p p l i e d ? t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `P r o c e s s ( e s ) _ t o _ k i l l " e x i t$ E _ B A D A R G S f i

P R O C E S S _ N A M E = " $ 1 " p sa x|g r e p" $ P R O C E S S _ N A M E "|a w k' { p r i n t$ 1 } '|x a r g sik i l l{ }2 & > / d e v / n u l l # ^ ^ ^ ^ #-

#N o t e s : #ii st h e" r e p l a c es t r i n g s "o p t i o nt ox a r g s . #T h ec u r l yb r a c k e t sa r et h ep l a c e h o l d e rf o rt h er e p l a c e m e n t . #2 & > / d e v / n u l ls u p p r e s s e su n w a n t e de r r o rm e s s a g e s . # #C a n g r e p" $ P R O C E S S _ N A M E "b er e p l a c e db yp i d o f" $ P R O C E S S _ N A M E " ? #e x i t$ ? # T h e" k i l l a l l "c o m m a n dh a st h es a m ee f f e c ta st h i ss c r i p t , # +b u tu s i n gi ti sn o tq u i t ea se d u c a t i o n a l .

Example 16-8. Word frequency analysis using xargs


# ! / b i n / b a s h #w f 2 . s h :C r u d ew o r df r e q u e n c ya n a l y s i so nat e x tf i l e . #U s e s' x a r g s 't od e c o m p o s el i n e so ft e x ti n t os i n g l ew o r d s . #C o m p a r et h i se x a m p l et ot h e" w f . s h "s c r i p tl a t e ro n .

#C h e c kf o ri n p u tf i l eo nc o m m a n d l i n e . A R G S = 1 E _ B A D A R G S = 8 5 E _ N O F I L E = 8 6 i f[$ #n e" $ A R G S "] #C o r r e c tn u m b e ro fa r g u m e n t sp a s s e dt os c r i p t ? t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ B A D A R G S f i i f[!f" $ 1 "] #D o e sf i l ee x i s t ? t h e n e c h o" F i l e\ " $ 1 \ "d o e sn o te x i s t . " e x i t$ E _ N O F I L E f i

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # c a t" $ 1 "|x a r g sn 1|\ # L i s tt h ef i l e ,o n ew o r dp e rl i n e . t rA Za z|\ # S h i f tc h a r a c t e r st ol o w e r c a s e . s e de' s / \ . / / g ' e' s / \ , / / g 'e' s // \ / g '|\ # F i l t e ro u tp e r i o d sa n dc o m m a s ,a n d # +c h a n g es p a c eb e t w e e nw o r d st ol i n e f e e d , s o r t|u n i qc|s o r tn r # F i n a l l yr e m o v ed u p l i c a t e s ,p r e f i xo c c u r r e n c ec o u n t # +a n ds o r tn u m e r i c a l l y . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # T h i sd o e st h es a m ej o ba st h e" w f . s h "e x a m p l e , # +b u tab i tm o r ep o n d e r o u s l y ,a n di tr u n sm o r es l o w l y( w h y ? ) . e x i t$ ? e x p r

All-purpose expression evaluator: Concatenates and evaluates the arguments according to the operation given (arguments must be separated by spaces). Operations may be arithmetic, comparison, string, or logical.
e x p r3+5

returns 8
e x p r5%3

returns 2
e x p r1/0

returns the error message, expr: division by zero Illegal arithmetic operations not allowed.
e x p r5\ *3

returns 15 The multiplication operator must be escaped when used in an arithmetic expression with expr.
y = ` e x p r$ y+1 `

Increment a variable, with the same effect as l e ty = y + 1and y = $ ( ( $ y + 1 ) ) . This is an example of arithmetic expansion.
z = ` e x p rs u b s t r$ s t r i n g$ p o s i t i o n$ l e n g t h `

Extract substring of $length characters, starting at $position. Example 16-9. Using expr
# ! / b i n / b a s h #D e m o n s t r a t i n gs o m eo ft h eu s e so f' e x p r ' #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = e c h o #A r i t h m e t i cO p e r a t o r s #-e c h o" A r i t h m e t i cO p e r a t o r s " e c h o a = ` e x p r5+3 ` e c h o" 5+3=$ a " a = ` e x p r$ a+1 ` e c h o e c h o" a+1=$ a " e c h o" ( i n c r e m e n t i n gav a r i a b l e ) " a = ` e x p r5%3 ` #m o d u l o e c h o e c h o" 5m o d3=$ a " e c h o e c h o #L o g i c a lO p e r a t o r s #-# R e t u r n s1i ft r u e ,0i ff a l s e , # +o p p o s i t eo fn o r m a lB a s hc o n v e n t i o n . e c h o" L o g i c a lO p e r a t o r s " e c h o

x = 2 4 y = 2 5 b = ` e x p r$ x=$ y ` e c h o" b=$ b " e c h o

#T e s te q u a l i t y . #0 ($ xn e$ y)

a = 3 b = ` e x p r$ a\ >1 0 ` e c h o' b = ` e x p r$ a\ >1 0 ` ,t h e r e f o r e . . . ' e c h o" I fa>1 0 ,b=0( f a l s e ) " e c h o" b=$ b " #0 (3!g t1 0) e c h o b = ` e x p r$ a\ <1 0 ` e c h o" I fa<1 0 ,b=1( t r u e ) " e c h o" b=$ b " #1 (3l t1 0) e c h o #N o t ee s c a p i n go fo p e r a t o r s . b = ` e x p r$ a\ < =3 ` e c h o" I fa< =3 ,b=1( t r u e ) " e c h o" b=$ b " #1 (3l e3) #T h e r ei sa l s oa" \ > = "o p e r a t o r( g r e a t e rt h a no re q u a lt o ) .

e c h o e c h o

#S t r i n gO p e r a t o r s #-e c h o" S t r i n gO p e r a t o r s " e c h o a = 1 2 3 4 z i p p e r 4 3 2 3 1 e c h o" T h es t r i n gb e i n go p e r a t e du p o ni s\ " $ a \ " . " #l e n g t h :l e n g t ho fs t r i n g b = ` e x p rl e n g t h$ a ` e c h o" L e n g t ho f\ " $ a \ "i s$ b . " #i n d e x :p o s i t i o no ff i r s tc h a r a c t e ri ns u b s t r i n g # t h a tm a t c h e sac h a r a c t e ri ns t r i n g b = ` e x p ri n d e x$ a2 3 ` e c h o" N u m e r i c a lp o s i t i o no ff i r s t\ " 2 \ "i n\ " $ a \ "i s\ " $ b \ " . " #s u b s t r :e x t r a c ts u b s t r i n g ,s t a r t i n gp o s i t i o n&l e n g t hs p e c i f i e d b = ` e x p rs u b s t r$ a26 ` e c h o" S u b s t r i n go f\ " $ a \ " ,s t a r t i n ga tp o s i t i o n2 , \ a n d6c h a r sl o n gi s\ " $ b \ " . "

# T h ed e f a u l tb e h a v i o ro ft h e' m a t c h 'o p e r a t i o n si st o # +s e a r c hf o rt h es p e c i f i e dm a t c ha tt h eB E G I N N I N Go ft h es t r i n g . # # U s i n gR e g u l a rE x p r e s s i o n s. . . b = ` e x p rm a t c h" $ a "' [ 0 9 ] * ' ` # N u m e r i c a lc o u n t . e c h oN u m b e ro fd i g i t sa tt h eb e g i n n i n go f\ " $ a \ "i s$ b . b = ` e x p rm a t c h" $ a "' \ ( [ 0 9 ] * \ ) ' ` # N o t et h a te s c a p e dp a r e n t h e s e s # = = = = # +t r i g g e rs u b s t r i n gm a t c h . e c h o" T h ed i g i t sa tt h eb e g i n n i n go f\ " $ a \ "a r e\ " $ b \ " . " e c h o e x i t0

The : (null) operator can substitute for match. For example, b = ` e x p r$ a:[ 0 9 ] * `is the exact equivalent of b = ` e x p rm a t c h$ a[ 0 9 ] * `in the above listing.
# ! / b i n / b a s h e c h o e c h o" S t r i n go p e r a t i o n su s i n g\ " e x p r\ $ s t r i n g:\ "c o n s t r u c t " e c h o" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " e c h o a = 1 2 3 4 z i p p e r 5 F L I P P E R 4 3 2 3 1 e c h o" T h es t r i n gb e i n go p e r a t e du p o ni s\ " ` e x p r" $ a ":' \ ( . * \ ) ' ` \ " . " # E s c a p e dp a r e n t h e s e sg r o u p i n go p e r a t o r . = = = = # # + # + # * * * * * * * * * * * * * * * * * * * * * * * * * * * E s c a p e dp a r e n t h e s e s m a t c has u b s t r i n g * * * * * * * * * * * * * * * * * * * * * * * * * * *

# I fn oe s c a p e dp a r e n t h e s e s. . . # +t h e n' e x p r 'c o n v e r t st h es t r i n go p e r a n dt oa ni n t e g e r . e c h o" L e n g t ho f\ " $ a \ "i s` e x p r" $ a ":' . * ' ` . " #L e n g t ho fs t r i n g

e c h o" N u m b e ro fd i g i t sa tt h eb e g i n n i n go f\ " $ a \ "i s` e x p r" $ a ":' [ 0 9 ] * ' ` . " #-# e c h o e c h o" T h ed i g i t sa tt h eb e g i n n i n go f\ " $ a \ "a r e` e x p r" $ a ":' \ ( [ 0 9 ] * \ ) ' ` . " # = = = = e c h o" T h ef i r s t7c h a r a c t e r so f\ " $ a \ "a r e` e x p r" $ a ":' \ ( . . . . . . . \ ) ' ` . " # = = = = = = = = = #A g a i n ,e s c a p e dp a r e n t h e s e sf o r c eas u b s t r i n gm a t c h . # e c h o" T h el a s t7c h a r a c t e r so f\ " $ a \ "a r e` e x p r" $ a ":' . * \ ( . . . . . . . \ ) ' ` . " # = = = = e n do fs t r i n go p e r a t o r ^ ^ # ( I nf a c t ,m e a n ss k i po v e ro n eo rm o r eo fa n yc h a r a c t e r su n t i ls p e c i f i e d # + s u b s t r i n gf o u n d . ) e c h o e x i t0

The above script illustrates how expr uses the escaped parentheses -- \( ... \) -- grouping operator in tandem with regular expression parsing to match a substring. Here is a another example, this time from "real life."
#S t r i pt h ew h i t e s p a c ef r o mt h eb e g i n n i n ga n de n d . L R F D A T E = ` e x p r" $ L R F D A T E ":' [ [ : s p a c e : ] ] * \ ( . * \ ) [ [ : s p a c e : ] ] * $ ' ` # F r o mP e t e rK n o w l e s '" b o o k l i s t g e n . s h "s c r i p t # +f o rc o n v e r t i n gf i l e st oS o n yL i b r i e / P R S 5 0 Xf o r m a t . # ( h t t p : / / b o o k l i s t g e n s h . p e t e r k n o w l e s . c o m )

Perl, sed, and awk have far superior string parsing facilities. A short sed or awk "subroutine" within a script (see Section 36.2) is an attractive alternative to expr. See Section 10.1 for more on using expr in string operations.

16.3. Time / Date Commands

Time/date and timing date Simply invoked, date prints the date and time to s t d o u t . Where this command gets interesting is in its formatting and parsing options. Example 16-10. Using date
# ! / b i n / b a s h #E x e r c i s i n gt h e' d a t e 'c o m m a n d e c h o" T h en u m b e ro fd a y ss i n c et h ey e a r ' sb e g i n n i n gi s` d a t e+ % j ` . " #N e e d sal e a d i n g' + 't oi n v o k ef o r m a t t i n g . #% jg i v e sd a yo fy e a r . e c h o" T h en u m b e ro fs e c o n d se l a p s e ds i n c e0 1 / 0 1 / 1 9 7 0i s` d a t e+ % s ` . " # % sy i e l d sn u m b e ro fs e c o n d ss i n c e" U N I Xe p o c h "b e g a n , # +b u th o wi st h i su s e f u l ? p r e f i x = t e m p s u f f i x = $ ( d a t e+ % s ) #T h e" + % s "o p t i o nt o' d a t e 'i sG N U s p e c i f i c . f i l e n a m e = $ p r e f i x . $ s u f f i x e c h o" T e m p o r a r yf i l e n a m e=$ f i l e n a m e " # I t ' sg r e a tf o rc r e a t i n g" u n i q u ea n dr a n d o m "t e m pf i l e n a m e s , # +e v e nb e t t e rt h a nu s i n g$ $ . #R e a dt h e' d a t e 'm a np a g ef o rm o r ef o r m a t t i n go p t i o n s . e x i t0

The uoption gives the UTC (Universal Coordinated Time).


b a s h $d a t e F r iM a r2 92 1 : 0 7 : 3 9M S T2 0 0 2

b a s h $d a t eu S a tM a r3 00 4 : 0 7 : 4 2U T C2 0 0 2

This option facilitates calculating the time between different dates. Example 16-11. Date calculations
# ! / b i n / b a s h #d a t e c a l c . s h #A u t h o r :N a t h a nC o u l t e r #U s e di nA B SG u i d ew i t hp e r m i s s i o n( t h a n k s ! ) . M P H R = 6 0 H P D = 2 4 #M i n u t e sp e rh o u r . #H o u r sp e rd a y .

d i f f( ){ p r i n t f' % s '$ ( ($ ( d a t eud " $ T A R G E T "+ % s )$ ( d a t eud " $ C U R R E N T "+ % s ) ) ) # % d=d a yo fm o n t h . }

C U R R E N T = $ ( d a t eud' 2 0 0 7 0 9 0 11 7 : 3 0 : 2 4 '' + % F% T . % N% Z ' ) T A R G E T = $ ( d a t eud ' 2 0 0 7 1 2 2 51 2 : 3 0 : 0 0 '' + % F% T . % N% Z ' ) #% F=f u l ld a t e ,% T=% H : % M : % S ,% N=n a n o s e c o n d s ,% Z=t i m ez o n e . p r i n t f' \ n I n2 0 0 7 ,% s'\

" $ ( d a t ed " $ C U R R E N T+ $ ( ($ ( d i f f )/ $ M P H R/ $ M P H R/ $ H P D/2) )d a y s "' + % d% B ' ) " # % B=n a m eo fm o n t h ^h a l f w a y p r i n t f' w a sh a l f w a yb e t w e e n% s'" $ ( d a t ed " $ C U R R E N T "' + % d% B ' ) " p r i n t f' a n d% s \ n '" $ ( d a t ed " $ T A R G E T "' + % d% B ' ) " p r i n t f' \ n O n% sa t% s ,t h e r ew e r e \ n '\ $ ( d a t eud " $ C U R R E N T "+ % F )$ ( d a t eud " $ C U R R E N T "+ % T ) D A Y S = $ ( ($ ( d i f f )/$ M P H R/$ M P H R/$ H P D) ) C U R R E N T = $ ( d a t ed " $ C U R R E N T+ $ D A Y Sd a y s "' + % F% T . % N% Z ' ) H O U R S = $ ( ($ ( d i f f )/$ M P H R/$ M P H R) ) C U R R E N T = $ ( d a t ed " $ C U R R E N T+ $ H O U R Sh o u r s "' + % F% T . % N% Z ' ) M I N U T E S = $ ( ($ ( d i f f )/$ M P H R) ) C U R R E N T = $ ( d a t ed " $ C U R R E N T+ $ M I N U T E Sm i n u t e s "' + % F% T . % N% Z ' ) p r i n t f' % sd a y s ,% sh o u r s ,'" $ D A Y S "" $ H O U R S " p r i n t f' % sm i n u t e s ,a n d% ss e c o n d s'" $ M I N U T E S "" $ ( d i f f ) " p r i n t f' u n t i lC h r i s t m a sD i n n e r ! \ n \ n ' # E x e r c i s e : # # R e w r i t et h ed i f f( )f u n c t i o nt oa c c e p tp a s s e dp a r a m e t e r s , # +r a t h e rt h a nu s i n gg l o b a lv a r i a b l e s .

The date command has quite a number of output options. For example % Ngives the nanosecond portion of the current time. One interesting use for this is to generate random integers.
d a t e+ % N|s e de' s / 0 0 0 $ / / 'e' s / ^ 0 / / ' ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # S t r i po f fl e a d i n ga n dt r a i l i n gz e r o e s ,i fp r e s e n t . # L e n g t ho fg e n e r a t e di n t e g e rd e p e n d so n # +h o wm a n yz e r o e ss t r i p p e do f f . #1 1 5 2 8 1 0 3 2 #6 3 4 0 8 7 2 5 #3 9 4 5 0 4 2 8 4

There are many more options (try man date ).


d a t e+ % j #E c h o e sd a yo ft h ey e a r( d a y se l a p s e ds i n c eJ a n u a r y1 ) . d a t e+ % k % M #E c h o e sh o u ra n dm i n u t ei n2 4 h o u rf o r m a t ,a sas i n g l ed i g i ts t r i n g .

#T h e' T Z 'p a r a m e t e rp e r m i t so v e r r i d i n gt h ed e f a u l tt i m ez o n e . d a t e #M o nM a r2 82 1 : 4 2 : 1 6M S T2 0 0 5 T Z = E S Td a t e #M o nM a r2 82 3 : 4 2 : 1 6E S T2 0 0 5 #T h a n k s ,F r a n kK a n n e m a n na n dP e t eS j o b e r g ,f o rt h et i p .

S i x D a y s A g o = $ ( d a t ed a t e = ' 6d a y sa g o ' ) O n e M o n t h A g o = $ ( d a t ed a t e = ' 1m o n t ha g o ' ) #F o u rw e e k sb a c k( n o tam o n t h ! ) O n e Y e a r A g o = $ ( d a t ed a t e = ' 1y e a ra g o ' )

See also Example 3-4 and Example A-43. zdump Time zone dump: echoes the time in a specified time zone.
b a s h $z d u m pE S T E S T T u eS e p1 82 2 : 0 9 : 2 22 0 0 1E S T

time

Outputs verbose timing statistics for executing a command.


t i m el sl /gives something like this: r e a l u s e r s y s 0 m 0 . 0 6 7 s 0 m 0 . 0 0 4 s 0 m 0 . 0 0 5 s

See also the very similar times command in the previous section. As of version 2.0 of Bash, time became a shell reserved word, with slightly altered behavior in a pipeline. touch Utility for updating access/modification times of a file to current system time or other specified time, but also useful for creating a new file. The command t o u c hz z zwill create a new file of zero length, named z z z , assuming that z z zdid not previously exist. Time-stamping empty files in this way is useful for storing date information, for example in keeping track of modification times on a project. The touch command is equivalent to : > >n e w f i l eor > >n e w f i l e(for ordinary files). Before doing a cp -u (copy/update), use touch to update the time stamp of files you don't wish overwritten. As an example, if the directory / h o m e / b o z o / t a x _ a u d i tcontains the files s p r e a d s h e e t 0 5 1 6 0 6 . d a t a ,s p r e a d s h e e t 0 5 1 7 0 6 . d a t a , and s p r e a d s h e e t 0 5 1 8 0 6 . d a t a , then doing a touch spreadsheet*.data will protect these files from being overwritten by files with the same names during a cp -u /home/bozo/financial_info/spreadsheet*data /home/bozo/tax_audit. at The at job control command executes a given set of commands at a specified time. Superficially, it resembles cron, however, at is chiefly useful for one-time execution of a command set.
a t2 p mJ a n u a r y1 5prompts for a set of commands to

execute at that time. These commands should be shell-script compatible, since, for all practical purposes, the user is typing in an executable shell script a line at a time. Input terminates with a Ctl-D. Using either the foption or input redirection (<), at reads a command list from a file. This file is an executable shell script, though it should, of course, be non-interactive. Particularly clever is including the run-parts command in the file to execute a different set of scripts.
b a s h $a t2 : 3 0a mF r i d a y<a t j o b s . l i s t j o b2a t2 0 0 0 1 0 2 70 2 : 3 0

batch The batch job control command is similar to at, but it runs a command list when the system load drops below . 8 . Like at, it can read commands from a file with the foption. The concept of batch processing dates back to the era of mainframe computers. It means running a set of commands without user intervention. cal Prints a neatly formatted monthly calendar to s t d o u t . Will do current year or a large range of past and future years. sleep

This is the shell equivalent of a wait loop. It pauses for a specified number of seconds, doing nothing. It can be useful for timing or in processes running in the background, checking for a specific event every so often (polling), as in Example 32-6.
s l e e p3 #P a u s e s3s e c o n d s .

The sleep command defaults to seconds, but minute, hours, or days may also be specified.
s l e e p3h #P a u s e s3h o u r s !

The watch command may be a better choice than sleep for running commands at timed intervals. usleep Microsleep (the u may be read as the Greek mu, or micro- prefix). This is the same as sleep, above, but "sleeps" in microsecond intervals. It can be used for fine-grained timing, or for polling an ongoing process at very frequent intervals.
u s l e e p3 0 #P a u s e s3 0m i c r o s e c o n d s .

This command is part of the Red Hat initscripts / rc-scripts package. The usleep command does not provide particularly accurate timing, and is therefore unsuitable for critical timing loops. hwclock, clock The hwclock command accesses or adjusts the machine's hardware clock. Some options require root privileges. The / e t c / r c . d / r c . s y s i n i tstartup file uses hwclock to set the system time from the hardware clock at bootup. The clock command is a synonym for hwclock.

16.4. Text Processing Commands


Commands affecting text and text files sort File sort utility, often used as a filter in a pipe. This command sorts a text stream or file forwards or backwards, or according to various keys or character positions. Using the moption, it merges presorted input files. The info page lists its many capabilities and options. See Example 11-9, Example 11-10, and Example A-8. tsort Topological sort , reading in pairs of whitespace-separated strings and sorting according to input patterns. The original purpose of tsort was to sort a list of dependencies for an obsolete version of the ld linker in an "ancient" version of UNIX. The results of a tsort will usually differ markedly from those of the standard sort command, above. uniq This filter removes duplicate lines from a sorted file. It is often seen in a pipe coupled with sort.
c a tl i s t 1l i s t 2l i s t 3|s o r t|u n i q>f i n a l . l i s t #C o n c a t e n a t e st h el i s tf i l e s , #s o r t st h e m , #r e m o v e sd u p l i c a t el i n e s , #a n df i n a l l yw r i t e st h er e s u l tt oa no u t p u tf i l e .

The useful coption prefixes each line of the input file with its number of occurrences.
b a s h $c a tt e s t f i l e T h i sl i n eo c c u r so n l yo n c e . T h i sl i n eo c c u r st w i c e . T h i sl i n eo c c u r st w i c e . T h i sl i n eo c c u r st h r e et i m e s . T h i sl i n eo c c u r st h r e et i m e s . T h i sl i n eo c c u r st h r e et i m e s .

b a s h $u n i qct e s t f i l e 1T h i sl i n eo c c u r so n l yo n c e . 2T h i sl i n eo c c u r st w i c e . 3T h i sl i n eo c c u r st h r e et i m e s .

b a s h $s o r tt e s t f i l e|u n i qc|s o r tn r 3T h i sl i n eo c c u r st h r e et i m e s . 2T h i sl i n eo c c u r st w i c e . 1T h i sl i n eo c c u r so n l yo n c e .

The s o r tI N P U T F I L E|u n i qc|s o r tn rcommand string produces a frequency of occurrence listing on the I N P U T F I L Efile (the n roptions to sort cause a reverse numerical sort). This template finds use in analysis of log files and dictionary lists, and wherever the lexical structure of a document needs to be examined. Example 16-12. Word Frequency Analysis
# ! / b i n / b a s h #w f . s h :C r u d ew o r df r e q u e n c ya n a l y s i so nat e x tf i l e . #T h i si sam o r ee f f i c i e n tv e r s i o no ft h e" w f 2 . s h "s c r i p t .

#C h e c kf o ri n p u tf i l eo nc o m m a n d l i n e . A R G S = 1 E _ B A D A R G S = 8 5 E _ N O F I L E = 8 6 i f[$ #n e" $ A R G S "] #C o r r e c tn u m b e ro fa r g u m e n t sp a s s e dt os c r i p t ? t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ B A D A R G S f i i f[!f" $ 1 "] #C h e c ki ff i l ee x i s t s . t h e n e c h o" F i l e\ " $ 1 \ "d o e sn o te x i s t . " e x i t$ E _ N O F I L E f i

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #m a i n( ) s e de' s / \ . / / g ' e' s / \ , / / g 'e' s // \ / g '" $ 1 "|t r' A Z '' a z '|s o r t|u n i qc|s o r tn r # = = = = = = = = = = = = = = = = = = = = = = = = = # F r e q u e n c yo fo c c u r r e n c e # F i l t e ro u tp e r i o d sa n dc o m m a s ,a n d # +c h a n g es p a c eb e t w e e nw o r d st ol i n e f e e d , # +t h e ns h i f tc h a r a c t e r st ol o w e r c a s e ,a n d # +f i n a l l yp r e f i xo c c u r r e n c ec o u n ta n ds o r tn u m e r i c a l l y . # A r u nG i r i d h a rs u g g e s t sm o d i f y i n gt h ea b o v et o : # ...|s o r t|u n i qc|s o r t+ 1[ f ]|s o r t+ 0n r

# T h i sa d d sas e c o n d a r ys o r tk e y ,s oi n s t a n c e so f # +e q u a lo c c u r r e n c ea r es o r t e da l p h a b e t i c a l l y . # A sh ee x p l a i n si t : # " T h i si se f f e c t i v e l yar a d i xs o r t ,f i r s to nt h e # +l e a s ts i g n i f i c a n tc o l u m n # +( w o r do rs t r i n g ,o p t i o n a l l yc a s e i n s e n s i t i v e ) # +a n dl a s to nt h em o s ts i g n i f i c a n tc o l u m n( f r e q u e n c y ) . " # # A sF r a n kW a n ge x p l a i n s ,t h ea b o v ei se q u i v a l e n tt o # + ...|s o r t|u n i qc|s o r t+ 0n r # +a n dt h ef o l l o w i n ga l s ow o r k s : # + ...|s o r t|u n i qc|s o r tk 1 n rk # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # e x i t0 #E x e r c i s e s : ##1 )A d d' s e d 'c o m m a n d st of i l t e ro u to t h e rp u n c t u a t i o n , # + s u c ha ss e m i c o l o n s . #2 )M o d i f yt h es c r i p tt oa l s of i l t e ro u tm u l t i p l es p a c e sa n d # + o t h e rw h i t e s p a c e . b a s h $c a tt e s t f i l e T h i sl i n eo c c u r so n l yo n c e . T h i sl i n eo c c u r st w i c e . T h i sl i n eo c c u r st w i c e . T h i sl i n eo c c u r st h r e et i m e s . T h i sl i n eo c c u r st h r e et i m e s . T h i sl i n eo c c u r st h r e et i m e s .

b a s h $. / w f . s ht e s t f i l e 6t h i s 6o c c u r s 6l i n e 3t i m e s 3t h r e e 2t w i c e 1o n l y 1o n c e

expand, unexpand The expand filter converts tabs to spaces. It is often used in a pipe. The unexpand filter converts spaces to tabs. This reverses the effect of expand. cut A tool for extracting fields from files. It is similar to the p r i n t$ Ncommand set in awk, but more limited. It may be simpler to use cut in a script than awk . Particularly important are the d(delimiter) and f(field specifier) options. Using cut to obtain a listing of the mounted filesystems:
c u td''f 1 , 2/ e t c / m t a b

Using cut to list the OS and kernel version:


u n a m ea|c u td ""f 1 , 3 , 1 1 , 1 2

Using cut to extract message headers from an e-mail folder:


b a s h $g r e p' ^ S u b j e c t : 'r e a d m e s s a g e s|c u tc 1 0 8 0 R e :L i n u xs u i t a b l ef o rm i s s i o n c r i t i c a la p p s ? M A K EM I L L I O N SW O R K I N GA TH O M E ! ! ! S p a mc o m p l a i n t

R e :S p a mc o m p l a i n t

Using cut to parse a file:


#L i s ta l lt h eu s e r si n/ e t c / p a s s w d . F I L E N A M E = / e t c / p a s s w d f o ru s e ri n$ ( c u td :f 1$ F I L E N A M E ) d o e c h o$ u s e r d o n e #T h a n k s ,O l e gP h i l o nf o rs u g g e s t i n gt h i s . c u td''f 2 , 3f i l e n a m eis equivalent to a w kF ' [] '' {p r i n t$ 2 ,$ 3} 'f i l e n a m e

It is even possible to specify a linefeed as a delimiter. The trick is to actually embed a linefeed (RETURN) in the command sequence.
b a s h $c u td ' 'f 3 , 7 , 1 9t e s t f i l e T h i si sl i n e3o ft e s t f i l e . T h i si sl i n e7o ft e s t f i l e . T h i si sl i n e1 9o ft e s t f i l e .

Thank you, Jaka Kranjc, for pointing this out. See also Example 16-48. paste Tool for merging together different files into a single, multi-column file. In combination with cut, useful for creating system log files. join Consider this a special-purpose cousin of paste . This powerful utility allows merging two files in a meaningful fashion, which essentially creates a simple version of a relational database. The join command operates on exactly two files, but pastes together only those lines with a common tagged field (usually a numerical label), and writes the result to s t d o u t . The files to be joined should be sorted according to the tagged field for the matchups to work properly.
F i l e :1 . d a t a 1 0 0S h o e s 2 0 0L a c e s 3 0 0S o c k s F i l e :2 . d a t a 1 0 0$ 4 0 . 0 0 2 0 0$ 1 . 0 0 3 0 0$ 2 . 0 0 b a s h $j o i n1 . d a t a2 . d a t a F i l e :1 . d a t a2 . d a t a 1 0 0S h o e s$ 4 0 . 0 0 2 0 0L a c e s$ 1 . 0 0 3 0 0S o c k s$ 2 . 0 0

The tagged field appears only once in the output. head lists the beginning of a file to s t d o u t . The default is 1 0lines, but a different number can be specified. The command has a number of interesting options. Example 16-13. Which files are scripts?
# ! / b i n / b a s h #s c r i p t d e t e c t o r . s h :D e t e c t ss c r i p t sw i t h i nad i r e c t o r y . T E S T C H A R S = 2 S H A B A N G = ' # ! ' #T e s tf i r s t2c h a r a c t e r s . #S c r i p t sb e g i nw i t ha" s h a b a n g . "

f o rf i l ei n* #T r a v e r s ea l lt h ef i l e si nc u r r e n td i r e c t o r y . d o i f[ [` h e a dc $ T E S T C H A R S" $ f i l e " `=" $ S H A B A N G "] ] # h e a dc 2 # ! # T h e' c 'o p t i o nt o" h e a d "o u t p u t sas p e c i f i e d # +n u m b e ro fc h a r a c t e r s ,r a t h e rt h a nl i n e s( t h ed e f a u l t ) . t h e n e c h o" F i l e\ " $ f i l e \ "i sas c r i p t . " e l s e e c h o" F i l e\ " $ f i l e \ "i s* n o t *as c r i p t . " f i d o n e e x i t0 # E x e r c i s e s : # # 1 )M o d i f yt h i ss c r i p tt ot a k ea sa no p t i o n a la r g u m e n t # + t h ed i r e c t o r yt os c a nf o rs c r i p t s # + ( r a t h e rt h a nj u s tt h ec u r r e n tw o r k i n gd i r e c t o r y ) . # # 2 )A si ts t a n d s ,t h i ss c r i p tg i v e s" f a l s ep o s i t i v e s "f o r # + P e r l ,a w k ,a n do t h e rs c r i p t i n gl a n g u a g es c r i p t s . # C o r r e c tt h i s .

Example 16-14. Generating 10-digit random numbers


# ! / b i n / b a s h #r n d . s h :O u t p u t sa1 0 d i g i tr a n d o mn u m b e r #S c r i p tb yS t e p h a n eC h a z e l a s . h e a dc 4/ d e v / u r a n d o m|o dN 4t u 4|s e dn e' 1 s / . */ / p '

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #A n a l y s i s ##h e a d : #c 4o p t i o nt a k e sf i r s t4b y t e s . #o d : #N 4o p t i o nl i m i t so u t p u tt o4b y t e s . #t u 4o p t i o ns e l e c t su n s i g n e dd e c i m a lf o r m a tf o ro u t p u t . #s e d : #no p t i o n ,i nc o m b i n a t i o nw i t h" p "f l a gt ot h e" s "c o m m a n d , #o u t p u t so n l ym a t c h e dl i n e s .

#T h ea u t h o ro ft h i ss c r i p te x p l a i n st h ea c t i o no f' s e d ' ,a sf o l l o w s . #h e a dc 4/ d e v / u r a n d o m|o dN 4t u 4|s e dn e' 1 s / . */ / p ' #>| #A s s u m eo u t p u tu pt o" s e d ">| #i s0 0 0 0 0 0 01 1 9 8 1 9 5 1 5 4 \ n # s e db e g i n sr e a d i n gc h a r a c t e r s :0 0 0 0 0 0 01 1 9 8 1 9 5 1 5 4 \ n . # H e r ei tf i n d san e w l i n ec h a r a c t e r , # +s oi ti sr e a d yt op r o c e s st h ef i r s tl i n e( 0 0 0 0 0 0 01 1 9 8 1 9 5 1 5 4 ) . # I tl o o k sa ti t s< r a n g e > < a c t i o n > s .T h ef i r s ta n do n l yo n ei s # # r a n g e 1 a c t i o n s / . */ / p

# T h el i n en u m b e ri si nt h er a n g e ,s oi te x e c u t e st h ea c t i o n : # +t r i e st os u b s t i t u t et h el o n g e s ts t r i n ge n d i n gw i t has p a c ei nt h el i n e # ( " 0 0 0 0 0 0 0" )w i t hn o t h i n g( / / ) ,a n di fi ts u c c e e d s ,p r i n t st h er e s u l t # ( " p "i saf l a gt ot h e" s "c o m m a n dh e r e ,t h i si sd i f f e r e n t # +f r o mt h e" p "c o m m a n d ) . # s e di sn o wr e a d yt oc o n t i n u er e a d i n gi t si n p u t .( N o t et h a tb e f o r e # +c o n t i n u i n g ,i fno p t i o nh a dn o tb e e np a s s e d ,s e dw o u l dh a v ep r i n t e d # +t h el i n eo n c ea g a i n ) . # N o w ,s e dr e a d st h er e m a i n d e ro ft h ec h a r a c t e r s ,a n df i n d st h e # +e n do ft h ef i l e . # I ti sn o wr e a d yt op r o c e s si t s2 n dl i n e( w h i c hi sa l s on u m b e r e d' $ 'a s # +i t ' st h el a s to n e ) . # I ts e e si ti sn o tm a t c h e db ya n y< r a n g e > ,s oi t sj o bi sd o n e . # I nf e ww o r dt h i ss e dc o m m m a n dm e a n s : # " O nt h ef i r s tl i n eo n l y ,r e m o v ea n yc h a r a c t e ru pt ot h er i g h t m o s ts p a c e , # +t h e np r i n ti t . " #Ab e t t e rw a yt od ot h i sw o u l dh a v eb e e n : # s e de' s / . */ / ; q ' #H e r e ,t w o< r a n g e > < a c t i o n > s( c o u l dh a v eb e e nw r i t t e n # s e de' s / . */ / 'eq ) : # # # r a n g e n o t h i n g( m a t c h e sl i n e ) n o t h i n g( m a t c h e sl i n e ) a c t i o n s / . */ / q( q u i t )

# H e r e ,s e do n l yr e a d si t sf i r s tl i n eo fi n p u t . # I tp e r f o r m sb o t ha c t i o n s ,a n dp r i n t st h el i n e( s u b s t i t u t e d )b e f o r e # +q u i t t i n g( b e c a u s eo ft h e" q "a c t i o n )s i n c et h e" n "o p t i o ni sn o tp a s s e d . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #A ne v e ns i m p l e ra l t e n a t i v et ot h ea b o v eo n e l i n es c r i p tw o u l db e : # h e a dc 4/ d e v / u r a n d o m |o dA nt u 4 e x i t

See also Example 16-39. tail lists the (tail) end of a file to s t d o u t . The default is 1 0lines, but this can be changed with the noption. Commonly used to keep track of changes to a system logfile, using the foption, which outputs lines appended to the file. Example 16-15. Using tail to monitor the system log

# ! / b i n / b a s h f i l e n a m e = s y s . l o g c a t/ d e v / n u l l>$ f i l e n a m e ;e c h o" C r e a t i n g/c l e a n i n go u tf i l e . " # C r e a t e st h ef i l ei fi td o e sn o ta l r e a d ye x i s t , # +a n dt r u n c a t e si tt oz e r ol e n g t hi fi td o e s . # :>f i l e n a m e a n d >f i l e n a m ea l s ow o r k . t a i l/ v a r / l o g / m e s s a g e s>$ f i l e n a m e #/ v a r / l o g / m e s s a g e sm u s th a v ew o r l dr e a dp e r m i s s i o nf o rt h i st ow o r k . e c h o" $ f i l e n a m ec o n t a i n st a i le n do fs y s t e ml o g . " e x i t0

To list a specific line of a text file, pipe the output of head to tail -n 1. For example h e a dn8 d a t a b a s e . t x t|t a i ln 1lists the 8th line of the file d a t a b a s e . t x t . To set a variable to a given block of a text file:
v a r = $ ( h e a dn$ m$ f i l e n a m e|t a i ln$ n ) #f i l e n a m e=n a m eo ff i l e #m=f r o mb e g i n n i n go ff i l e ,n u m b e ro fl i n e st oe n do fb l o c k #n=n u m b e ro fl i n e st os e tv a r i a b l et o( t r i mf r o me n do fb l o c k )

Newer implementations of tail deprecate the older tail -$LINES filename usage. The standard tail -n $LINES filename is correct. See also Example 16-5, Example 16-39 and Example 32-6. grep A multi-purpose file search tool that uses Regular Expressions. It was originally a command/filter in the venerable ed line editor: g / r e / p-- global - regular expression - print . grep p a t t e r n[f i l e ...] Search the target file(s) for occurrences of p a t t e r n , where p a t t e r nmay be literal text or a Regular Expression.
b a s h $g r e p' [ r s t ] y s t e m . $ 'o s i n f o . t x t T h eG P Lg o v e r n st h ed i s t r i b u t i o no ft h eL i n u xo p e r a t i n gs y s t e m .

If no target file(s) specified, grep works as a filter on s t d o u t , as in a pipe.


b a s h $p sa x|g r e pc l o c k 7 6 5t t y 1 S 0 : 0 0x c l o c k 9 0 1p t s / 1 S 0 : 0 0g r e pc l o c k

The ioption causes a case-insensitive search. The woption matches only whole words. The loption lists only the files in which matches were found, but not the matching lines. The r(recursive) option searches files in the current working directory and all subdirectories below it. The noption lists the matching lines, together with line numbers.

b a s h $g r e pnL i n u xo s i n f o . t x t 2 : T h i si saf i l ec o n t a i n i n gi n f o r m a t i o na b o u tL i n u x . 6 : T h eG P Lg o v e r n st h ed i s t r i b u t i o no ft h eL i n u xo p e r a t i n gs y s t e m .

The v(or i n v e r t m a t c h ) option filters out matches.


g r e pp a t t e r n 1* . t x t|g r e pvp a t t e r n 2 #M a t c h e sa l ll i n e si n" * . t x t "f i l e sc o n t a i n i n g" p a t t e r n 1 " , #b u t* * * n o t * * *" p a t t e r n 2 " .

The c(c o u n t ) option gives a numerical count of matches, rather than actually listing the matches.
g r e pct x t* . s g m l #( n u m b e ro fo c c u r r e n c e so f" t x t "i n" * . s g m l "f i l e s )

# g r e pc z. # ^d o t #m e a n sc o u n t( c )z e r o s e p a r a t e d( z )i t e m sm a t c h i n g" . " #t h a ti s ,n o n e m p t yo n e s( c o n t a i n i n ga tl e a s t1c h a r a c t e r ) . # p r i n t f' ab \ n c d \ n \ n \ n \ n \ n \ 0 0 0 \ n \ 0 0 0 e \ 0 0 0 \ 0 0 0 \ n f '|g r e pc z. p r i n t f' ab \ n c d \ n \ n \ n \ n \ n \ 0 0 0 \ n \ 0 0 0 e \ 0 0 0 \ 0 0 0 \ n f '|g r e pc z' $ ' p r i n t f' ab \ n c d \ n \ n \ n \ n \ n \ 0 0 0 \ n \ 0 0 0 e \ 0 0 0 \ 0 0 0 \ n f '|g r e pc z' ^ ' # p r i n t f' ab \ n c d \ n \ n \ n \ n \ n \ 0 0 0 \ n \ 0 0 0 e \ 0 0 0 \ 0 0 0 \ n f '|g r e pc' $ ' #B yd e f a u l t ,n e w l i n ec h a r s( \ n )s e p a r a t ei t e m st om a t c h . #N o t et h a tt h ezo p t i o ni sG N U" g r e p "s p e c i f i c .

#3 #5 #5 #9

#T h a n k s ,S . C .

The c o l o r(or c o l o u r ) option marks the matching string in color (on the console or in an xterm window). Since grep prints out each entire line containing the matching pattern, this lets you see exactly what is being matched. See also the ooption, which shows only the matching portion of the line(s). Example 16-16. Printing out the From lines in stored e-mail messages
# ! / b i n / b a s h #f r o m . s h # E m u l a t e st h eu s e f u l' f r o m 'u t i l i t yi nS o l a r i s ,B S D ,e t c . # E c h o e st h e" F r o m "h e a d e rl i n ei na l lm e s s a g e s # +i ny o u re m a i ld i r e c t o r y .

M A I L D I R = ~ / m a i l / * # N oq u o t i n go fv a r i a b l e .W h y ? #M a y b ec h e c ki f e x i s t s$ M A I L D I R : i f[d$ M A I L D I R]... G R E P _ O P T S = " HA5c o l o r " # S h o wf i l e ,p l u se x t r ac o n t e x tl i n e s # +a n dd i s p l a y" F r o m "i nc o l o r . T A R G E T S T R = " ^ F r o m " #" F r o m "a tb e g i n n i n go fl i n e . f o rf i l ei n$ M A I L D I R # N oq u o t i n go fv a r i a b l e . d o g r e p$ G R E P _ O P T S" $ T A R G E T S T R "" $ f i l e " # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # A g a i n ,d on o tq u o t et h i sv a r i a b l e . e c h o d o n e e x i t$ ? # Y o um i g h tw i s ht op i p et h eo u t p u to ft h i ss c r i p tt o' m o r e ' # +o rr e d i r e c ti tt oaf i l e...

When invoked with more than one target file given, grep specifies which file contains matches.

b a s h $g r e pL i n u xo s i n f o . t x tm i s c . t x t o s i n f o . t x t : T h i si saf i l ec o n t a i n i n gi n f o r m a t i o na b o u tL i n u x . o s i n f o . t x t : T h eG P Lg o v e r n st h ed i s t r i b u t i o no ft h eL i n u xo p e r a t i n gs y s t e m . m i s c . t x t : T h eL i n u xo p e r a t i n gs y s t e mi ss t e a d i l yg a i n i n gi np o p u l a r i t y .

To force grep to show the filename when searching only one target file, simply give / d e v / n u l las the second file.
b a s h $g r e pL i n u xo s i n f o . t x t/ d e v / n u l l o s i n f o . t x t : T h i si saf i l ec o n t a i n i n gi n f o r m a t i o na b o u tL i n u x . o s i n f o . t x t : T h eG P Lg o v e r n st h ed i s t r i b u t i o no ft h eL i n u xo p e r a t i n gs y s t e m .

If there is a successful match, grep returns an exit status of 0, which makes it useful in a condition test in a script, especially in combination with the qoption to suppress output.
S U C C E S S = 0 w o r d = L i n u x f i l e n a m e = d a t a . f i l e g r e pq" $ w o r d "" $ f i l e n a m e " #i fg r e pl o o k u ps u c c e e d s

# T h e" q "o p t i o n # +c a u s e sn o t h i n gt oe c h ot os t d o u t .

i f[$ ?e q$ S U C C E S S] #i fg r e pq" $ w o r d "" $ f i l e n a m e " c a nr e p l a c el i n e s5-7 . t h e n e c h o" $ w o r df o u n di n$ f i l e n a m e " e l s e e c h o" $ w o r dn o tf o u n di n$ f i l e n a m e " f i

Example 32-6 demonstrates how to use grep to search for a word pattern in a system logfile. Example 16-17. Emulating grep in a script
# ! / b i n / b a s h #g r p . s h :R u d i m e n t a r yr e i m p l e m e n t a t i o no fg r e p . E _ B A D A R G S = 8 5 i f[z" $ 1 "] #C h e c kf o ra r g u m e n tt os c r i p t . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `p a t t e r n " e x i t$ E _ B A D A R G S f i e c h o f o rf i l ei n* #T r a v e r s ea l lf i l e si n$ P W D . d o o u t p u t = $ ( s e dn/ " $ 1 " / p$ f i l e ) #C o m m a n ds u b s t i t u t i o n . i f[!z" $ o u t p u t "] #W h a th a p p e n si f" $ o u t p u t "i sn o tq u o t e d ? t h e n e c h on" $ f i l e :" e c h o" $ o u t p u t " f i # s e dn e" / $ 1 / s | ^ | $ { f i l e } :| p " i se q u i v a l e n tt oa b o v e . e c h o d o n e e c h o e x i t0 #E x e r c i s e s :

##1 )A d dn e w l i n e st oo u t p u t ,i fm o r et h a no n em a t c hi na n yg i v e nf i l e . #2 )A d df e a t u r e s .

How can grep search for two (or more) separate patterns? What if you want grep to display all lines in a file or files that contain both "pattern1" and "pattern2"? One method is to pipe the result of grep pattern1 to grep pattern2. For example, given the following file:
#F i l e n a m e :t s t f i l e T h i si sas a m p l ef i l e . T h i si sa no r d i n a r yt e x tf i l e . T h i sf i l ed o e sn o tc o n t a i na n yu n u s u a lt e x t . T h i sf i l ei sn o tu n u s u a l . H e r ei ss o m et e x t .

Now, let's search this file for lines containing both "file" and "text" . . .
b a s h $g r e pf i l et s t f i l e #F i l e n a m e :t s t f i l e T h i si sas a m p l ef i l e . T h i si sa no r d i n a r yt e x tf i l e . T h i sf i l ed o e sn o tc o n t a i na n yu n u s u a lt e x t . T h i sf i l ei sn o tu n u s u a l . b a s h $g r e pf i l et s t f i l e|g r e pt e x t T h i si sa no r d i n a r yt e x tf i l e . T h i sf i l ed o e sn o tc o n t a i na n yu n u s u a lt e x t .

Now, for an interesting recreational use of grep . . . Example 16-18. Crossword puzzle solver
# ! / b i n / b a s h #c w s o l v e r . s h #T h i si sa c t u a l l yaw r a p p e ra r o u n dao n e l i n e r( l i n e4 6 ) . # C r o s s w o r dp u z z l ea n da n a g r a m m i n gw o r dg a m es o l v e r . # Y o uk n o w* s o m e *o ft h el e t t e r si nt h ew o r dy o u ' r el o o k i n gf o r , # +s oy o un e e dal i s to fa l lv a l i dw o r d s # +w i t ht h ek n o w nl e t t e r si ng i v e np o s i t i o n s . # F o re x a m p l e :w . . . i . . . . n # 1 ? ? ? 5 ? ? ? ? 1 0 #wi np o s i t i o n1 ,3u n k n o w n s ,ii nt h e5 t h ,4u n k n o w n s ,na tt h ee n d . #( S e ec o m m e n t sa te n do fs c r i p t . )

E _ N O P A T T = 7 1 D I C T = / u s r / s h a r e / d i c t / w o r d . l s t # ^ ^ ^ ^ ^ ^ ^ ^ L o o k sf o rw o r dl i s th e r e . # A S C I Iw o r dl i s t ,o n ew o r dp e rl i n e . # I fy o uh a p p e nt on e e da na p p r o p r i a t el i s t , # +d o w n l o a dt h ea u t h o r ' s" y a w l "w o r dl i s tp a c k a g e . # h t t p : / / i b i b l i o . o r g / p u b / L i n u x / l i b s / y a w l 0 . 3 . 2 . t a r . g z # o r # h t t p : / / b a s h . d e t a . i n / y a w l 0 . 3 . 2 . t a r . g z

i f[z" $ 1 "] t h e n e c h o e c h o" U s a g e : " e c h o

# I fn ow o r dp a t t e r ns p e c i f i e d # +a sac o m m a n d l i n ea r g u m e n t... # +...t h e n... # +U s a g em e s s a g e .

e c h o" " $ 0 "\ " p a t t e r n , \ " " e c h o" w h e r e\ " p a t t e r n \ "i si nt h ef o r m " e c h o" x x x . . x . x . . . " e c h o e c h o" T h ex ' sr e p r e s e n tk n o w nl e t t e r s , " e c h o" a n dt h ep e r i o d sa r eu n k n o w nl e t t e r s( b l a n k s ) . " e c h o" L e t t e r sa n dp e r i o d sc a nb ei na n yp o s i t i o n . " e c h o" F o re x a m p l e ,t r y : s hc w s o l v e r . s hw . . . i . . . . n " e c h o e x i t$ E _ N O P A T T f i e c h o #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #T h i si sw h e r ea l lt h ew o r kg e t sd o n e . g r e p^ " $ 1 " $" $ D I C T " #Y e s ,o n l yo n el i n e ! # | | #^i ss t a r t o f w o r dr e g e xa n c h o r . #$i se n d o f w o r dr e g e xa n c h o r . # F r o m_ S t u p i dG r e pT r i c k s _ ,v o l .1 , # +ab o o kt h eA B SG u i d ea u t h o rm a yy e tg e ta r o u n d # +t ow r i t i n g...o n eo ft h e s ed a y s... #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = e c h o

e x i t$ ? #S c r i p tt e r m i n a t e sh e r e . # I ft h e r ea r et o om a n yw o r d sg e n e r a t e d , # +r e d i r e c tt h eo u t p u tt oaf i l e . $s hc w s o l v e r . s hw . . . i . . . . n w e l l i n g t o n w o r k i n g m a n w o r k i n g m e n

egrep -- extended grep -- is the same as grep -E. This uses a somewhat different, extended set of Regular Expressions, which can make the search a bit more flexible. It also allows the boolean | (or) operator.
b a s h$e g r e p' m a t c h e s | M a t c h e s 'f i l e . t x t L i n e1m a t c h e s . L i n e3M a t c h e s . L i n e4c o n t a i n sm a t c h e s ,b u ta l s oM a t c h e s

fgrep -- fast grep -- is the same as grep -F. It does a literal string search (no Regular Expressions), which generally speeds things up a bit. On some Linux distros, egrep and fgrep are symbolic links to, or aliases for grep, but invoked with the Eand Foptions, respectively. Example 16-19. Looking up definitions in Webster's 1913 Dictionary
# ! / b i n / b a s h #d i c t l o o k u p . s h # T h i ss c r i p tl o o k su pd e f i n i t i o n si nt h e1 9 1 3W e b s t e r ' sD i c t i o n a r y . # T h i sP u b l i cD o m a i nd i c t i o n a r yi sa v a i l a b l ef o rd o w n l o a d # +f r o mv a r i o u ss i t e s ,i n c l u d i n g # +P r o j e c tG u t e n b e r g( h t t p : / / w w w . g u t e n b e r g . o r g / e t e x t / 2 4 7 ) . # # C o n v e r ti tf r o mD O St oU N I Xf o r m a t( w i t ho n l yL Fa te n do fl i n e ) # +b e f o r eu s i n gi tw i t ht h i ss c r i p t . # S t o r et h ef i l ei np l a i n ,u n c o m p r e s s e dA S C I It e x t . # S e tD E F A U L T _ D I C T F I L Ev a r i a b l eb e l o wt op a t h / f i l e n a m e .

E _ B A D A R G S = 8 5 M A X C O N T E X T L I N E S = 5 0 #M a x i m u mn u m b e ro fl i n e st os h o w . D E F A U L T _ D I C T F I L E = " / u s r / s h a r e / d i c t / w e b s t e r 1 9 1 3 d i c t . t x t " #D e f a u l td i c t i o n a r yf i l ep a t h n a m e . #C h a n g et h i sa sn e c e s s a r y . # N o t e : # # T h i sp a r t i c u l a re d i t i o no ft h e1 9 1 3W e b s t e r ' s # +b e g i n se a c he n t r yw i t ha nu p p e r c a s el e t t e r # +( l o w e r c a s ef o rt h er e m a i n i n gc h a r a c t e r s ) . # O n l yt h e* v e r yf i r s tl i n e *o fa ne n t r yb e g i n st h i sw a y , # +a n dt h a t ' sw h yt h es e a r c ha l g o r i t h mb e l o ww o r k s .

i f[ [z$ ( e c h o" $ 1 "|s e dn' / ^ [ A Z ] / p ' )] ] # M u s ta tl e a s ts p e c i f yw o r dt ol o o ku p ,a n d # +i tm u s ts t a r tw i t ha nu p p e r c a s el e t t e r . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `W o r d t o d e f i n e[ d i c t i o n a r y f i l e ] " e c h o e c h o" N o t e :W o r dt ol o o ku pm u s ts t a r tw i t hc a p i t a ll e t t e r , " e c h o" w i t ht h er e s to ft h ew o r di nl o w e r c a s e . " e c h o" " e c h o" E x a m p l e s :A b a n d o n ,D i c t i o n a r y ,M a r k i n g ,e t c . " e x i t$ E _ B A D A R G S f i

i f[z" $ 2 "] t h e n d i c t f i l e = $ D E F A U L T _ D I C T F I L E e l s e d i c t f i l e = " $ 2 " f i

# M a ys p e c i f yd i f f e r e n td i c t i o n a r y # +a sa na r g u m e n tt ot h i ss c r i p t .

#D e f i n i t i o n = $ ( f g r e pA$ M A X C O N T E X T L I N E S" $ 1\ \ "" $ d i c t f i l e " ) # D e f i n i t i o n si nf o r m" W o r d\ . . . " # # A n d ,y e s ," f g r e p "i sf a s te n o u g h # +t os e a r c he v e nav e r yl a r g et e x tf i l e .

#N o w ,s n i po u tj u s tt h ed e f i n i t i o nb l o c k . e c h o" $ D e f i n i t i o n "| s e dn' 1 , / ^ [ A Z ] / p '| # P r i n tf r o mf i r s tl i n eo fo u t p u t # +t ot h ef i r s tl i n eo ft h en e x te n t r y . s e d' $ d '|s e d' $ d ' # D e l e t el a s tt w ol i n e so fo u t p u t # +( b l a n kl i n ea n df i r s tl i n eo fn e x te n t r y ) . #e x i t$ ? #E x e r c i s e s : ##1 ) M o d i f yt h es c r i p tt oa c c e p ta n yt y p eo fa l p h a b e t i ci n p u t # +( u p p e r c a s e ,l o w e r c a s e ,m i x e dc a s e ) ,a n dc o n v e r ti t # +t oa na c c e p t a b l ef o r m a tf o rp r o c e s s i n g . # #2 ) C o n v e r tt h es c r i p tt oaG U Ia p p l i c a t i o n , # +u s i n gs o m e t h i n gl i k e' g d i a l o g 'o r' z e n i t y '... # T h es c r i p tw i l lt h e nn ol o n g e rt a k ei t sa r g u m e n t ( s ) # +f r o mt h ec o m m a n d l i n e .

# #3 ) M o d i f yt h es c r i p tt op a r s eo n eo ft h eo t h e ra v a i l a b l e # +P u b l i cD o m a i nD i c t i o n a r i e s ,s u c ha st h eU . S .C e n s u sB u r e a uG a z e t t e e r .

See also Example A-41 for an example of speedy fgrep lookup on a large text file. agrep (approximate grep) extends the capabilities of grep to approximate matching. The search string may differ by a specified number of characters from the resulting matches. This utility is not part of the core Linux distribution. To search compressed files, use zgrep, zegrep, or zfgrep. These also work on non-compressed files, though slower than plain grep, egrep, fgrep. They are handy for searching through a mixed set of files, some compressed, some not. To search bzipped files, use bzgrep. look The command look works like grep, but does a lookup on a "dictionary," a sorted word list. By default, look searches for a match in / u s r / d i c t / w o r d s , but a different dictionary file may be specified. Example 16-20. Checking words in a list for validity
# ! / b i n / b a s h #l o o k u p :D o e sad i c t i o n a r yl o o k u po ne a c hw o r di nad a t af i l e . f i l e = w o r d s . d a t a #D a t af i l ef r o mw h i c ht or e a dw o r d st ot e s t . e c h o e c h o" T e s t i n gf i l e$ f i l e " e c h o w h i l e[" $ w o r d "! =e n d] #L a s tw o r di nd a t af i l e . d o #^ ^ ^ r e a dw o r d #F r o md a t af i l e ,b e c a u s eo fr e d i r e c t i o na te n do fl o o p . l o o k$ w o r d>/ d e v / n u l l #D o n ' tw a n tt od i s p l a yl i n e si nd i c t i o n a r yf i l e . # S e a r c h e sf o rw o r d si nt h ef i l e/ u s r / s h a r e / d i c t / w o r d s # +( u s u a l l yal i n kt ol i n u x . w o r d s ) . l o o k u p = $ ? #E x i ts t a t u so f' l o o k 'c o m m a n d . i f[" $ l o o k u p "e q0] t h e n e c h o" \ " $ w o r d \ "i sv a l i d . " e l s e e c h o" \ " $ w o r d \ "i si n v a l i d . " f i d o n e< " $ f i l e " e c h o e x i t0 ##C o d eb e l o wl i n ew i l ln o te x e c u t eb e c a u s eo f" e x i t "c o m m a n da b o v e . #R e d i r e c t ss t d i nt o$ f i l e ,s o" r e a d s "c o m ef r o mt h e r e .

#S t e p h a n eC h a z e l a sp r o p o s e st h ef o l l o w i n g ,m o r ec o n c i s ea l t e r n a t i v e : w h i l er e a dw o r d& &[ [$ w o r d! =e n d] ] d oi fl o o k" $ w o r d ">/ d e v / n u l l t h e ne c h o" \ " $ w o r d \ "i sv a l i d . " e l s ee c h o" \ " $ w o r d \ "i si n v a l i d . " f i d o n e< " $ f i l e " e x i t0

sed, awk Scripting languages especially suited for parsing text files and command output. May be embedded singly or in combination in pipes and shell scripts. sed Non-interactive "stream editor", permits using many ex commands in batch mode. It finds many uses in shell scripts. awk Programmable file extractor and formatter, good for manipulating and/or extracting fields (columns) in structured text files. Its syntax is similar to C. wc wc gives a "word count" on a file or I/O stream:
b a s h$w c/ u s r / s h a r e / d o c / s e d 4 . 1 . 2 / R E A D M E 1 3 7 0 4 4 7R E A D M E [ 1 3l i n e s 7 0w o r d s 4 4 7c h a r a c t e r s ] w cwgives only the word

count.

w clgives only the line count. w ccgives only the byte count. w cmgives only the character count. w cLgives only the length of the longest line.

Using wc to count how many . t x tfiles are in current working directory:


$l s* . t x t|w cl # W i l lw o r ka sl o n ga sn o n eo ft h e" * . t x t "f i l e s # +h a v eal i n e f e e de m b e d d e di nt h e i rn a m e . # A l t e r n a t i v ew a y so fd o i n gt h i sa r e : # f i n d.m a x d e p t h1n a m e\ * . t x tp r i n t 0|g r e pc z. # ( s h o p tsn u l l g l o b ;s e t-* . t x t ;e c h o$ # ) # T h a n k s ,S . C .

Using wc to total up the size of all the files whose names begin with letters in the range d - h
b a s h $w c[ d h ] *|g r e pt o t a l|a w k' { p r i n t$ 3 } ' 7 1 8 3 2

Using wc to count the instances of the word "Linux" in the main source file for this book.
b a s h $g r e pL i n u xa b s b o o k . s g m l|w cl 5 0

See also Example 16-39 and Example 20-8. Certain commands include some of the functionality of wc as options.
. . .|g r e pf o o|w cl #T h i sf r e q u e n t l yu s e dc o n s t r u c tc a nb em o r ec o n c i s e l yr e n d e r e d . . . .|g r e pcf o o #J u s tu s et h e" c "( o r" c o u n t " )o p t i o no fg r e p . #T h a n k s ,S . C .

tr character translation filter. Must use quoting and/or brackets, as appropriate. Quotes prevent the shell from reinterpreting the special characters in tr command sequences. Brackets should be quoted to prevent expansion by the shell. Either t r" A Z "" * "< f i l e n a m eor t rA Z\ *< f i l e n a m echanges all the uppercase letters in f i l e n a m eto asterisks (writes to s t d o u t ). On some systems this may not work, but t rA Z' [ * * ] 'will. The doption deletes a range of characters.
e c h o" a b c d e f " e c h o" a b c d e f "|t rdb d #a b c d e f #a e f

t rd0 9< f i l e n a m e #D e l e t e sa l ld i g i t sf r o mt h ef i l e" f i l e n a m e " .

The s q u e e z e r e p e a t s(or s ) option deletes all but the first instance of a string of consecutive characters. This option is useful for removing excess whitespace.
b a s h $e c h o" X X X X X "|t rs q u e e z e r e p e a t s' X ' X

The c"complement" option inverts the character set to match. With this option, tr acts only upon those characters not matching the specified set.
b a s h $e c h o" a c f d e b 1 2 3 "|t rcb d+ + c + d + b + + + +

Note that tr recognizes POSIX character classes. [74]


b a s h $e c h o" a b c d 2 e f 1 "|t r' [ : a l p h a : ] '2 1

Example 16-21. toupper: Transforms a file to all uppercase.


# ! / b i n / b a s h #C h a n g e saf i l et oa l lu p p e r c a s e . E _ B A D A R G S = 8 5 i f[z" $ 1 "] #S t a n d a r dc h e c kf o rc o m m a n d l i n ea r g . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ B A D A R G S f i t ra zA Z< " $ 1 " #S a m ee f f e c ta sa b o v e ,b u tu s i n gP O S I Xc h a r a c t e rs e tn o t a t i o n : # t r' [ : l o w e r : ] '' [ : u p p e r : ] '< " $ 1 " #T h a n k s ,S . C . # # # O re v e n... c a t" $ 1 "|t ra zA Z O rd o z e n so fo t h e rw a y s...

e x i t0 # E x e r c i s e : # R e w r i t et h i ss c r i p tt og i v et h eo p t i o no fc h a n g i n gaf i l e

# +t o* e i t h e r *u p p e ro rl o w e r c a s e . # H i n t :U s ee i t h e rt h e" c a s e "o r" s e l e c t "c o m m a n d .

Example 16-22. lowercase: Changes all filenames in working directory to lowercase.


# ! / b i n / b a s h # # C h a n g e se v e r yf i l e n a m ei nw o r k i n gd i r e c t o r yt oa l ll o w e r c a s e . # # I n s p i r e db yas c r i p to fJ o h nD u b o i s , # +w h i c hw a st r a n s l a t e di n t oB a s hb yC h e tR a m e y , # +a n dc o n s i d e r a b l ys i m p l i f i e db yt h ea u t h o ro ft h eA B SG u i d e .

f o rf i l e n a m ei n* #T r a v e r s ea l lf i l e si nd i r e c t o r y . d o f n a m e = ` b a s e n a m e$ f i l e n a m e ` n = ` e c h o$ f n a m e|t rA Za z ` #C h a n g en a m et ol o w e r c a s e . i f[" $ f n a m e "! =" $ n "] #R e n a m eo n l yf i l e sn o ta l r e a d yl o w e r c a s e . t h e n m v$ f n a m e$ n f i d o n e e x i t$ ?

#C o d eb e l o wt h i sl i n ew i l ln o te x e c u t eb e c a u s eo f" e x i t " . # # #T or u ni t ,d e l e t es c r i p ta b o v el i n e . #T h ea b o v es c r i p tw i l ln o tw o r ko nf i l e n a m e sc o n t a i n i n gb l a n k so rn e w l i n e s . #S t e p h a n eC h a z e l a st h e r e f o r es u g g e s t st h ef o l l o w i n ga l t e r n a t i v e :

f o rf i l e n a m ei n*

#N o tn e c e s s a r yt ou s eb a s e n a m e , #s i n c e" * "w o n ' tr e t u r na n yf i l ec o n t a i n i n g" / " . d on = ` e c h o" $ f i l e n a m e / "|t r' [ : u p p e r : ] '' [ : l o w e r : ] ' ` # P O S I Xc h a rs e tn o t a t i o n . # S l a s ha d d e ds ot h a tt r a i l i n gn e w l i n e sa r en o t # r e m o v e db yc o m m a n ds u b s t i t u t i o n . #V a r i a b l es u b s t i t u t i o n : n = $ { n % / } #R e m o v e st r a i l i n gs l a s h ,a d d e da b o v e ,f r o mf i l e n a m e . [ [$ f i l e n a m e= =$ n] ]| |m v" $ f i l e n a m e "" $ n " #C h e c k si ff i l e n a m ea l r e a d yl o w e r c a s e . d o n e e x i t$ ?

Example 16-23. du: DOS to UNIX text file conversion.


# ! / b i n / b a s h #D u . s h :D O St oU N I Xt e x tf i l ec o n v e r t e r . E _ W R O N G A R G S = 8 5 i f[z" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e t o c o n v e r t " e x i t$ E _ W R O N G A R G S f i N E W F I L E N A M E = $ 1 . u n x C R = ' \ 0 1 5 ' #C a r r i a g er e t u r n . #0 1 5i so c t a lA S C I Ic o d ef o rC R . #L i n e si naD O St e x tf i l ee n di nC R L F . #L i n e si naU N I Xt e x tf i l ee n di nL Fo n l y .

t rd$ C R<$ 1>$ N E W F I L E N A M E #D e l e t eC R ' sa n dw r i t et on e wf i l e . e c h o" O r i g i n a lD O St e x tf i l ei s\ " $ 1 \ " . " e c h o" C o n v e r t e dU N I Xt e x tf i l ei s\ " $ N E W F I L E N A M E \ " . " e x i t0 #E x e r c i s e : ##C h a n g et h ea b o v es c r i p tt oc o n v e r tf r o mU N I Xt oD O S .

Example 16-24. rot13: ultra-weak encryption.


# ! / b i n / b a s h #r o t 1 3 . s h :C l a s s i cr o t 1 3a l g o r i t h m , # e n c r y p t i o nt h a tm i g h tf o o la3 y e a ro l d # f o ra b o u t1 0m i n u t e s . #U s a g e :. / r o t 1 3 . s hf i l e n a m e #o r . / r o t 1 3 . s h< f i l e n a m e #o r . / r o t 1 3 . s ha n ds u p p l yk e y b o a r di n p u t( s t d i n ) c a t" $ @ "|t r' a z A Z '' n z a m N Z A M ' #" a "g o e st o" n " ," b "t o" o ". . . # T h e c a t" $ @ " c o n s t r u c t # +p e r m i t si n p u te i t h e rf r o ms t d i no rf r o mf i l e s . e x i t0

Example 16-25. Generating "Crypto-Quote" Puzzles


# ! / b i n / b a s h #c r y p t o q u o t e . s h :E n c r y p tq u o t e s # W i l le n c r y p tf a m o u sq u o t e si nas i m p l em o n o a l p h a b e t i cs u b s t i t u t i o n . # T h er e s u l ti ss i m i l a rt ot h e" C r y p t oQ u o t e "p u z z l e s # +s e e ni nt h eO pE dp a g e so ft h eS u n d a yp a p e r .

k e y = E T A O I N S H R D L U B C F G J M Q P V W Z Y X K #T h e" k e y "i sn o t h i n gm o r et h a nas c r a m b l e da l p h a b e t . #C h a n g i n gt h e" k e y "c h a n g e st h ee n c r y p t i o n . #T h e' c a t" $ @ " 'c o n s t r u c t i o ng e t si n p u te i t h e rf r o ms t d i no rf r o mf i l e s . #I fu s i n gs t d i n ,t e r m i n a t ei n p u tw i t haC o n t r o l D . #O t h e r w i s e ,s p e c i f yf i l e n a m ea sc o m m a n d l i n ep a r a m e t e r . c a t" $ @ "|t r" a z "" A Z "|t r" A Z "" $ k e y " # | t ou p p e r c a s e | e n c r y p t #W i l lw o r ko nl o w e r c a s e ,u p p e r c a s e ,o rm i x e d c a s eq u o t e s . #P a s s e sn o n a l p h a b e t i cc h a r a c t e r st h r o u g hu n c h a n g e d .

#T r yt h i ss c r i p tw i t hs o m e t h i n gl i k e : #" N o t h i n gs on e e d sr e f o r m i n ga so t h e rp e o p l e ' sh a b i t s . " #M a r kT w a i n # #O u t p u ti s : #" C F P H R C SQ FC I I O QM I N F M B R C SE QF P H I MG I F G U I ' QH E T R P Q . " #B E M LP Z E R C #T or e v e r s et h ee n c r y p t i o n : #c a t" $ @ "|t r" $ k e y "" A Z "

# T h i ss i m p l e m i n d e dc i p h e rc a nb eb r o k e nb ya na v e r a g e1 2 y e a ro l d # +u s i n go n l yp e n c i la n dp a p e r .

e x i t0 # E x e r c i s e : # # M o d i f yt h es c r i p ts ot h a ti tw i l le i t h e re n c r y p to rd e c r y p t , # +d e p e n d i n go nc o m m a n d l i n ea r g u m e n t ( s ) .

Of course, tr lends itself to code obfuscation.


# ! / b i n / b a s h #j a b h . s h x = " w f t e d s k a e b j g d B s t b d b s m n j g z " e c h o$ x|t r" a z "" o h ,t u r t l e n e c kP h r a s eJ a r ! " #B a s e do nt h eW i k i p e d i a" J u s ta n o t h e rP e r lh a c k e r "a r t i c l e .

tr variants The tr utility has two historic variants. The BSD version does not use brackets (t ra zA Z ), but the SysV one does (t r' [ a z ] '' [ A Z ] ' ). The GNU version of tr resembles the BSD one. fold A filter that wraps lines of input to a specified width. This is especially useful with the soption, which breaks lines at word spaces (see Example 16-26 and Example A-1). fmt Simple-minded file formatter, used as a filter in a pipe to "wrap" long lines of text output. Example 16-26. Formatted file listing.
# ! / b i n / b a s h W I D T H = 4 0 b = ` l s/ u s r / l o c a l / b i n ` e c h o$ b|f m tw$ W I D T H #C o u l da l s oh a v eb e e nd o n eb y # e c h o$ b|f o l d-sw$ W I D T H e x i t0 #4 0c o l u m n sw i d e . #G e taf i l el i s t i n g . . .

See also Example 16-5. A powerful alternative to fmt is Kamil Toman's par utility, available from http://www.cs.berkeley.edu/~amc/Par/. col This deceptively named filter removes reverse line feeds from an input stream. It also attempts to replace whitespace with equivalent tabs. The chief use of col is in filtering the output from certain text processing utilities, such as groff and tbl. column Column formatter. This filter transforms list-type text output into a "pretty-printed" table by inserting tabs at appropriate places.

Example 16-27. Using column to format a directory listing


# ! / b i n / b a s h #c o l m s . s h #Am i n o rm o d i f i c a t i o no ft h ee x a m p l ef i l ei nt h e" c o l u m n "m a np a g e .

( p r i n t f" P E R M I S S I O N SL I N K SO W N E RG R O U PS I Z EM O N T HD A YH H : M MP R O G N A M E \ n "\ ;l sl|s e d1 d )|c o l u m nt # ^ ^ ^ ^ ^ ^ ^ ^ # T h e" s e d1 d "i nt h ep i p ed e l e t e st h ef i r s tl i n eo fo u t p u t , # +w h i c hw o u l db e" t o t a l N " , # +w h e r e" N "i st h et o t a ln u m b e ro ff i l e sf o u n db y" l sl " . #T h eto p t i o nt o" c o l u m n "p r e t t y p r i n t sat a b l e . e x i t0

colrm Column removal filter. This removes columns (characters) from a file and writes the file, lacking the range of specified columns, back to s t d o u t .c o l r m24< f i l e n a m eremoves the second through fourth characters from each line of the text file f i l e n a m e . If the file contains tabs or nonprintable characters, this may cause unpredictable behavior. In such cases, consider using expand and unexpand in a pipe preceding colrm. nl Line numbering filter: n lf i l e n a m elists f i l e n a m eto s t d o u t , but inserts consecutive numbers at the beginning of each non-blank line. If f i l e n a m eomitted, operates on s t d i n . The output of nl is very similar to c a tb , since, by default nl does not list blank lines. Example 16-28. nl : A self-numbering script.
# ! / b i n / b a s h #l i n e n u m b e r . s h #T h i ss c r i p te c h o e si t s e l ft w i c et os t d o u tw i t hi t sl i n e sn u m b e r e d . e c h o" # # l i n en u m b e r=$ L I N E N O "#' n l 's e e st h i sa sl i n e4 ( n ld o e sn o tn u m b e rb l a n kl i n e s ) . ' c a tn 's e e si tc o r r e c t l ya sl i n e# 6 .

n l` b a s e n a m e$ 0 ` e c h o ;e c h o #N o w ,l e t ' st r yi tw i t h' c a tn ' c a tn` b a s e n a m e$ 0 ` #T h ed i f f e r e n c ei st h a t' c a tn 'n u m b e r st h eb l a n kl i n e s . #N o t et h a t' n lb a 'w i l la l s od os o . e x i t0 #-

pr Print formatting filter. This will paginate files (or s t d o u t ) into sections suitable for hard copy printing or viewing on screen. Various options permit row and column manipulation, joining lines, setting margins, numbering lines, adding page headers, and merging files, among other things. The pr command combines much of the functionality of nl, paste , fold, column, and expand.
p ro5w i d t h = 6 5f i l e Z Z Z|m o r egives a nice paginated

listing to screen of f i l e Z Z Zwith margins set at 5

and 65.

A particularly useful option is d , forcing double-spacing (same effect as sed -G). gettext The GNU gettext package is a set of utilities for localizing and translating the text output of programs into foreign languages. While originally intended for C programs, it now supports quite a number of programming and scripting languages. The gettext program works on shell scripts. See the i n f op a g e . msgfmt A program for generating binary message catalogs. It is used for localization. iconv A utility for converting file(s) to a different encoding (character set). Its chief use is for localization.
#C o n v e r tas t r i n gf r o mU T F 8t oU T F 1 6a n dp r i n tt ot h eB o o k L i s t f u n c t i o nw r i t e _ u t f 8 _ s t r i n g{ S T R I N G = $ 1 B O O K L I S T = $ 2 e c h on" $ S T R I N G "|i c o n vfU T F 8tU T F 1 6|\ c u tb3 -|t rd\ \ n> >" $ B O O K L I S T " } # F r o mP e t e rK n o w l e s '" b o o k l i s t g e n . s h "s c r i p t # +f o rc o n v e r t i n gf i l e st oS o n yL i b r i e / P R S 5 0 Xf o r m a t . # ( h t t p : / / b o o k l i s t g e n s h . p e t e r k n o w l e s . c o m )

recode Consider this a fancier version of iconv, above. This very versatile utility for converting a file to a different encoding scheme. Note that recode is not part of the standard Linux installation. TeX, gs TeX and Postscript are text markup languages used for preparing copy for printing or formatted video display. TeX is Donald Knuth's elaborate typsetting system. It is often convenient to write a shell script encapsulating all the options and arguments passed to one of these markup languages. Ghostscript (gs ) is a GPL-ed Postscript interpreter. texexec Utility for processing TeX and pdf files. Found in / u s r / b i non many Linux distros, it is actually a shell wrapper that calls Perl to invoke Tex .
t e x e x e cp d f a r r a n g er e s u l t = C o n c a t e n a t e d . p d f* p d f # C o n c a t e n a t e sa l lt h ep d ff i l e si nt h ec u r r e n tw o r k i n gd i r e c t o r y # +i n t ot h em e r g e df i l e ,C o n c a t e n a t e d . p d f... # ( T h ep d f a r r a n g eo p t i o nr e p a g i n a t e sap d ff i l e .S e ea l s op d f c o m b i n e . ) # T h ea b o v ec o m m a n d l i n ec o u l db ep a r a m e t e r i z e da n dp u ti n t oas h e l ls c r i p t .

enscript Utility for converting plain text file to PostScript For example, enscript filename.txt -p filename.ps produces the PostScript output file f i l e n a m e . p s .

groff, tbl, eqn Yet another text markup and display formatting language is groff. This is the enhanced GNU version of the venerable UNIX roff/troff display and typesetting package. Manpages use groff. The tbl table processing utility is considered part of groff, as its function is to convert table markup into groff commands. The eqn equation processing utility is likewise part of groff, and its function is to convert equation markup into groff commands. Example 16-29. manview: Viewing formatted manpages
# ! / b i n / b a s h #m a n v i e w . s h :F o r m a t st h es o u r c eo fam a np a g ef o rv i e w i n g . # T h i ss c r i p ti su s e f u lw h e nw r i t i n gm a np a g es o u r c e . # I tl e t sy o ul o o ka tt h ei n t e r m e d i a t er e s u l t so nt h ef l y # +w h i l ew o r k i n go ni t . E _ W R O N G A R G S = 8 5 i f[z" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ W R O N G A R G S f i #g r o f fT a s c i im a n$ 1|l e s s #F r o mt h em a np a g ef o rg r o f f . ## I ft h em a np a g ei n c l u d e st a b l e sa n d / o re q u a t i o n s , # +t h e nt h ea b o v ec o d ew i l lb a r f . # T h ef o l l o w i n gl i n ec a nh a n d l es u c hc a s e s . # # g t b l<" $ 1 "|g e q nT l a t i n 1|g r o f fT l a t i n 1m t t y c h a rm a n # # T h a n k s ,S . C . e x i t$ ? #S e ea l s ot h e" m a n e d . s h "s c r i p t .

See also Example A-39. lex, yacc The lex lexical analyzer produces programs for pattern matching. This has been replaced by the nonproprietary flex on Linux systems. The yacc utility creates a parser based on a set of specifications. This has been replaced by the nonproprietary bison on Linux systems.

16.5. File and Archiving Commands


Archiving tar The standard UNIX archiving utility. [75] Originally a Tape ARchiving program, it has developed into a general purpose package that can handle all manner of archiving with all types of destination devices, ranging from tape drives

to regular files to even s t d o u t(see Example 3-4). GNU tar has been patched to accept various compression filters, for example: tar czvf archive_name.tar.gz *, which recursively archives and gzips all files in a directory tree except dotfiles in the current working directory ($PWD). [76] Some useful tar options: 1. ccreate (a new archive) 2. xextract (files from existing archive) 3. d e l e t edelete (files from existing archive) This option will not work on magnetic tape devices. 4. rappend (files to existing archive) 5. Aappend (tar files to existing archive) 6. tlist (contents of existing archive) 7. uupdate archive 8. dcompare archive with specified filesystem 9. a f t e r d a t eonly process files with a date stamp after specified date 10. zgzip the archive (compress or uncompress, depending on whether combined with the cor x ) option 11. jbzip2 the archive It may be difficult to recover data from a corrupted gzipped tar archive. When archiving important files, make multiple backups. shar Shell archiving utility. The text files in a shell archive are concatenated without compression, and the resultant archive is essentially a shell script, complete with #!/bin/sh header, containing all the necessary unarchiving commands, as well as the files themselves. Shar archives still show up in Usenet newsgroups, but otherwise shar has been replaced by tar/gzip. The unshar command unpacks shar archives. The mailshar command is a Bash script that uses shar to concatenate multiple files into a single one for e-mailing. This script supports compression and uuencoding. ar Creation and manipulation utility for archives, mainly used for binary object file libraries. rpm The Red Hat Package Manager, or rpm utility provides a wrapper for source or binary archives. It includes commands for installing and checking the integrity of packages, among other things. A simple rpm -i package_name.rpm usually suffices to install a package, though there are many more options available.
r p mq fidentifies which package a file originates from. b a s h $r p mq f/ b i n / l s

c o r e u t i l s 5 . 2 . 1 3 1

r p mq agives a complete list of all installed

rpm packages on a given system. An r p mq a

p a c k a g e _ n a m elists only the package(s) corresponding to p a c k a g e _ n a m e . b a s h $r p mq a r e d h a t l o g o s 1 . 1 . 3 1 g l i b c 2 . 2 . 4 1 3 c r a c k l i b 2 . 7 1 2 d o s f s t o o l s 2 . 7 1 g d b m 1 . 8 . 0 1 0 k s y m o o p s 2 . 4 . 1 1 m k t e m p 1 . 5 1 1 p e r l 5 . 6 . 0 1 7 r e i s e r f s u t i l s 3 . x . 0 j 2 . . .

b a s h $r p mq ad o c b o o k u t i l s d o c b o o k u t i l s 0 . 6 . 9 2

b a s h $r p mq ad o c b o o k|g r e pd o c b o o k d o c b o o k d t d 3 1 s g m l 1 . 0 1 0 d o c b o o k s t y l e d s s s l 1 . 6 4 3 d o c b o o k d t d 3 0 s g m l 1 . 0 1 0 d o c b o o k d t d 4 0 s g m l 1 . 0 1 1 d o c b o o k u t i l s p d f 0 . 6 . 9 2 d o c b o o k d t d 4 1 s g m l 1 . 0 1 0 d o c b o o k u t i l s 0 . 6 . 9 2

cpio This specialized archiving copy command (copy input and output) is rarely seen any more, having been supplanted by tar/gzip. It still has its uses, such as moving a directory tree. With an appropriate block size (for copying) specified, it can be appreciably faster than tar. Example 16-30. Using cpio to move a directory tree
# ! / b i n / b a s h #C o p y i n gad i r e c t o r yt r e eu s i n gc p i o . #A d v a n t a g e so fu s i n g' c p i o ' : # S p e e do fc o p y i n g .I t ' sf a s t e rt h a n' t a r 'w i t hp i p e s . # W e l ls u i t e df o rc o p y i n gs p e c i a lf i l e s( n a m e dp i p e s ,e t c . ) # + t h a t' c p 'm a yc h o k eo n . A R G S = 2 E _ B A D A R G S = 6 5 i f[$ #n e" $ A R G S "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `s o u r c ed e s t i n a t i o n " e x i t$ E _ B A D A R G S f i s o u r c e = " $ 1 " d e s t i n a t i o n = " $ 2 " # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # f i n d" $ s o u r c e "d e p t h|c p i oa d m v p" $ d e s t i n a t i o n " # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^

# R e a dt h e' f i n d 'a n d' c p i o 'i n f op a g e st od e c i p h e rt h e s eo p t i o n s . # T h ea b o v ew o r k so n l yr e l a t i v et o$ P W D( c u r r e n td i r e c t o r y )... # +f u l lp a t h n a m e sa r es p e c i f i e d . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

#E x e r c i s e : ## A d dc o d et oc h e c kt h ee x i ts t a t u s( $ ? )o ft h e' f i n d|c p i o 'p i p e # +a n do u t p u ta p p r o p r i a t ee r r o rm e s s a g e si fa n y t h i n gw e n tw r o n g . e x i t$ ?

rpm2cpio This command extracts a cpio archive from an rpm one. Example 16-31. Unpacking an rpm archive
# ! / b i n / b a s h #d e r p m . s h :U n p a c ka n' r p m 'a r c h i v e :$ { 1 ? " U s a g e :` b a s e n a m e$ 0 `t a r g e t f i l e " } #M u s ts p e c i f y' r p m 'a r c h i v en a m ea sa na r g u m e n t .

T E M P F I L E = $ $ . c p i o

# T e m p f i l ew i t h" u n i q u e "n a m e . # $ $i sp r o c e s sI Do fs c r i p t .

r p m 2 c p i o<$ 1>$ T E M P F I L E

# C o n v e r t sr p ma r c h i v ei n t o # +c p i oa r c h i v e . c p i om a k e d i r e c t o r i e sF$ T E M P F I L Ei # U n p a c k sc p i oa r c h i v e . r mf$ T E M P F I L E # D e l e t e sc p i oa r c h i v e . e x i t0 # E x e r c i s e : # A d dc h e c kf o rw h e t h e r1 )" t a r g e t f i l e "e x i s t sa n d # + 2 )i ti sa nr p ma r c h i v e . # H i n t : P a r s eo u t p u to f' f i l e 'c o m m a n d .

pax The pax portable archive exchange toolkit facilitates periodic file backups and is designed to be cross-compatible between various flavors of UNIX. It was designed to replace tar and cpio.
p a xw fd a i l y _ b a c k u p . p a x~ / l i n u x s e r v e r / f i l e s # C r e a t e sat a ra r c h i v eo fa l lf i l e si nt h et a r g e td i r e c t o r y . # N o t et h a tt h eo p t i o n st op a xm u s tb ei nt h ec o r r e c to r d e r# +p a xf w h a sa ne n t i r e l yd i f f e r e n te f f e c t . p a xfd a i l y _ b a c k u p . p a x # L i s t st h ef i l e si nt h ea r c h i v e . p a xr fd a i l y _ b a c k u p . p a x~ / b s d s e r v e r / f i l e s # R e s t o r e st h eb a c k e d u pf i l e sf r o mt h eL i n u xm a c h i n e # +o n t oaB S Do n e .

Note that pax handles many of the standard archiving and compression commands. Compression gzip The standard GNU/UNIX compression utility, replacing the inferior and proprietary compress . The corresponding decompression command is gunzip, which is the equivalent of gzip -d.

The coption sends the output of gzip to s t d o u t . This is useful when piping to other commands. The zcat filter decompresses a gzipped file to s t d o u t , as possible input to a pipe or redirection. This is, in effect, a cat command that works on compressed files (including files processed with the older compress utility). The zcat command is equivalent to gzip -dc. On some commercial UNIX systems, zcat is a synonym for uncompress -c, and will not work on gzipped files. See also Example 7-7. bzip2 An alternate compression utility, usually more efficient (but slower) than gzip, especially on large files. The corresponding decompression command is bunzip2. Similar to the zcat command, bzcat decompresses a bzipped2-ed file to s t d o u t . Newer versions of tar have been patched with bzip2 support. compress , uncompress This is an older, proprietary compression utility found in commercial UNIX distributions. The more efficient gzip has largely replaced it. Linux distributions generally include a compress workalike for compatibility, although gunzip can unarchive files treated with compress . The znew command transforms compressed files into gzipped ones. sq Yet another compression (squeeze) utility, a filter that works only on sorted ASCII word lists. It uses the standard invocation syntax for a filter, sq < input-file > output-file . Fast, but not nearly as efficient as gzip. The corresponding uncompression filter is unsq, invoked like sq. The output of sq may be piped to gzip for further compression. zip, unzip Cross-platform file archiving and compression utility compatible with DOS pkzip.exe. "Zipped" archives seem to be a more common medium of file exchange on the Internet than "tarballs." unarc, unarj, unrar These Linux utilities permit unpacking archives compressed with the DOS arc.exe, arj.exe, and rar.exe programs. lzma, unlzma, lzcat Highly efficient Lempel-Ziv-Markov compression. The syntax of lzma is similar to that of gzip. The 7-zip Website has more information. File Information file A utility for identifying file types. The command f i l ef i l e n a m ewill return a file specification for f i l e n a m e , such as a s c i it e x tor d a t a . It references the magic numbers found in / u s r / s h a r e / m a g i c ,/ e t c / m a g i c , or / u s r / l i b / m a g i c , depending on the Linux/UNIX distribution. The foption causes file to run in batch mode, to read from a designated file a list of filenames to analyze. The z option, when used on a compressed target file, forces an attempt to analyze the uncompressed file type.

b a s h $f i l et e s t . t a r . g z t e s t . t a r . g z :g z i pc o m p r e s s e dd a t a ,d e f l a t e d , l a s tm o d i f i e d :S u nS e p1 61 3 : 3 4 : 5 12 0 0 1 ,o s :U n i x b a s hf i l ezt e s t . t a r . g z t e s t . t a r . g z :G N Ut a ra r c h i v e( g z i pc o m p r e s s e dd a t a ,d e f l a t e d , l a s tm o d i f i e d :S u nS e p1 61 3 : 3 4 : 5 12 0 0 1 ,o s :U n i x )

#F i n ds ha n dB a s hs c r i p t si nag i v e nd i r e c t o r y : D I R E C T O R Y = / u s r / l o c a l / b i n K E Y W O R D = B o u r n e #B o u r n ea n dB o u r n e A g a i ns h e l ls c r i p t s f i l e$ D I R E C T O R Y / *|f g r e p$ K E Y W O R D #O u t p u t : #/ u s r / l o c a l / b i n / b u r n c d : #/ u s r / l o c a l / b i n / b u r n i t : #/ u s r / l o c a l / b i n / c a s s e t t e . s h : #/ u s r / l o c a l / b i n / c o p y c d : #... B o u r n e A g a i ns h e l ls c r i p tt e x te x e c u t a b l e B o u r n e A g a i ns h e l ls c r i p tt e x te x e c u t a b l e B o u r n es h e l ls c r i p tt e x te x e c u t a b l e B o u r n e A g a i ns h e l ls c r i p tt e x te x e c u t a b l e

Example 16-32. Stripping comments from C program files


# ! / b i n / b a s h #s t r i p c o m m e n t . s h :S t r i p so u tt h ec o m m e n t s( / *C O M M E N T* / )i naCp r o g r a m . E _ N O A R G S = 0 E _ A R G E R R O R = 6 6 E _ W R O N G _ F I L E _ T Y P E = 6 7 i f[$ #e q" $ E _ N O A R G S "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `C p r o g r a m f i l e "> & 2#E r r o rm e s s a g et os t d e r r . e x i t$ E _ A R G E R R O R f i #T e s tf o rc o r r e c tf i l et y p e . t y p e = ` f i l e$ 1|a w k' {p r i n t$ 2 ,$ 3 ,$ 4 ,$ 5} ' ` #" f i l e$ 1 "e c h o e sf i l et y p e... #T h e na w kr e m o v e st h ef i r s tf i e l d ,t h ef i l e n a m e... #T h e nt h er e s u l ti sf e di n t ot h ev a r i a b l e" t y p e . " c o r r e c t _ t y p e = " A S C I ICp r o g r a mt e x t " i f[" $ t y p e "! =" $ c o r r e c t _ t y p e "] t h e n e c h o e c h o" T h i ss c r i p tw o r k so nCp r o g r a mf i l e so n l y . " e c h o e x i t$ E _ W R O N G _ F I L E _ T Y P E f i

#R a t h e rc r y p t i cs e ds c r i p t : # s e d' / ^ \ / \ * / d / . * \ * \ / / d '$ 1 # #E a s yt ou n d e r s t a n di fy o ut a k es e v e r a lh o u r st ol e a r ns e df u n d a m e n t a l s .

# N e e dt oa d do n em o r el i n et ot h es e ds c r i p tt od e a lw i t h # +c a s ew h e r el i n eo fc o d eh a sac o m m e n tf o l l o w i n gi to ns a m el i n e .

# T h i si sl e f ta san o n t r i v i a le x e r c i s e . # A l s o ,t h ea b o v ec o d ed e l e t e sn o n c o m m e n tl i n e sw i t ha" * / "... # +n o tad e s i r a b l er e s u l t . e x i t0

##C o d eb e l o wt h i sl i n ew i l ln o te x e c u t eb e c a u s eo f' e x i t0 'a b o v e . #S t e p h a n eC h a z e l a ss u g g e s t st h ef o l l o w i n ga l t e r n a t i v e : u s a g e ( ){ e c h o" U s a g e :` b a s e n a m e$ 0 `C p r o g r a m f i l e "> & 2 e x i t1 } W E I R D = ` e c h one' \ 3 7 7 ' ` #o rW E I R D = $ ' \ 3 7 7 ' [ [$ #e q1] ]| |u s a g e c a s e` f i l e" $ 1 " `i n * " Cp r o g r a mt e x t " * )s e de" s % / \ * % $ { W E I R D } % g ; s % \ * / % $ { W E I R D } % g "" $ 1 "\ |t r' \ 3 7 7 \ n '' \ n \ 3 7 7 '\ |s e dn e' p ; n '\ |t rd' \ n '|t r' \ 3 7 7 '' \ n ' ; ; * )u s a g e ; ; e s a c # T h i si ss t i l lf o o l e db yt h i n g sl i k e : # p r i n t f ( " / * " ) ; # o r # / * / *b u g g ye m b e d d e dc o m m e n t* / # # T oh a n d l ea l ls p e c i a lc a s e s( c o m m e n t si ns t r i n g s ,c o m m e n t si ns t r i n g # +w h e r et h e r ei sa\ " ,\ \ ". . . ) , # +t h eo n l yw a yi st ow r i t eaCp a r s e r( u s i n gl e xo ry a c cp e r h a p s ? ) . e x i t0

which which command gives the full path to "command." This is useful for finding out whether a particular command or utility is installed on the system.
$ b a s hw h i c hr m / u s r / b i n / r m

For an interesting use of this command, see Example 36-14. whereis Similar to which, above, whereis command gives the full path to "command," but also to its manpage.
$ b a s hw h e r e i sr m r m :/ b i n / r m/ u s r / s h a r e / m a n / m a n 1 / r m . 1 . b z 2

whatis whatis command looks up "command" in the w h a t i sdatabase. This is useful for identifying system commands and important configuration files. Consider it a simplified man command.
$ b a s hw h a t i sw h a t i s w h a t i s ( 1 ) -s e a r c ht h ew h a t i sd a t a b a s ef o rc o m p l e t ew o r d s

Example 16-33. Exploring / u s r / X 1 1 R 6 / b i n

# ! / b i n / b a s h #W h a ta r ea l lt h o s em y s t e r i o u sb i n a r i e si n/ u s r / X 1 1 R 6 / b i n ? D I R E C T O R Y = " / u s r / X 1 1 R 6 / b i n " #T r ya l s o" / b i n " ," / u s r / b i n " ," / u s r / l o c a l / b i n " ,e t c . f o rf i l ei n$ D I R E C T O R Y / * d o w h a t i s` b a s e n a m e$ f i l e ` d o n e e x i t0 # N o t e :F o rt h i st ow o r k ,y o um u s tc r e a t ea" w h a t i s "d a t a b a s e # +w i t h/ u s r / s b i n / m a k e w h a t i s . # Y o um a yw i s ht or e d i r e c to u t p u to ft h i ss c r i p t ,l i k es o : # . / w h a t . s h> > w h a t i s . d b # o rv i e wi tap a g ea tat i m eo ns t d o u t , # . / w h a t . s h|l e s s

#E c h o e si n f oa b o u tt h eb i n a r y .

See also Example 11-3. vdir Show a detailed directory listing. The effect is similar to ls -lb. This is one of the GNU fileutils.
b a s h $v d i r t o t a l1 0 r w r r r w r r r w r r b a s hl sl t o t a l1 0 r w r r r w r r r w r r -

1b o z o b o z o 1b o z o b o z o 1b o z o b o z o

4 0 3 4J u l1 82 2 : 0 4d a t a 1 . x r o l o 4 6 0 2M a y2 51 3 : 5 8d a t a 1 . x r o l o . b a k 8 7 7D e c1 7 2 0 0 0e m p l o y m e n t . x r o l o

1b o z o b o z o 1b o z o b o z o 1b o z o b o z o

4 0 3 4J u l1 82 2 : 0 4d a t a 1 . x r o l o 4 6 0 2M a y2 51 3 : 5 8d a t a 1 . x r o l o . b a k 8 7 7D e c1 7 2 0 0 0e m p l o y m e n t . x r o l o

locate , slocate The locate command searches for files using a database stored for just that purpose. The slocate command is the secure version of locate (which may be aliased to slocate ).
$ b a s hl o c a t eh i c k s o n / u s r / l i b / x e p h e m / c a t a l o g s / h i c k s o n . e d b

getfacl, setfacl These commands retrieve or set the file access control list -- the owner, group, and file permissions.
b a s h $g e t f a c l* #f i l e :t e s t 1 . t x t #o w n e r :b o z o #g r o u p :b o z g r p u s e r : : r w g r o u p : : r w o t h e r : : r #f i l e :t e s t 2 . t x t #o w n e r :b o z o #g r o u p :b o z g r p

u s e r : : r w g r o u p : : r w o t h e r : : r -

b a s h $s e t f a c lmu : b o z o : r wy e a r l y _ b u d g e t . c s v b a s h $g e t f a c ly e a r l y _ b u d g e t . c s v #f i l e :y e a r l y _ b u d g e t . c s v #o w n e r :a c c o u n t a n t #g r o u p :b u d g e t g r p u s e r : : r w u s e r : b o z o : r w u s e r : a c c o u n t a n t : r w g r o u p : : r w m a s k : : r w o t h e r : : r -

readlink Disclose the file that a symbolic link points to.


b a s h $r e a d l i n k/ u s r / b i n / a w k . . / . . / b i n / g a w k

strings Use the strings command to find printable strings in a binary or data file. It will list sequences of printable characters found in the target file. This might be handy for a quick 'n dirty examination of a core dump or for looking at an unknown graphic image file (s t r i n g si m a g e f i l e|m o r emight show something like JFIF, which would identify the file as a jpeg graphic). In a script, you would probably parse the output of strings with grep or sed. See Example 11-7 and Example 11-9. Example 16-34. An "improved" strings command
# ! / b i n / b a s h #w s t r i n g s . s h :" w o r d s t r i n g s "( e n h a n c e d" s t r i n g s "c o m m a n d ) # # T h i ss c r i p tf i l t e r st h eo u t p u to f" s t r i n g s "b yc h e c k i n gi t # +a g a i n s tas t a n d a r dw o r dl i s tf i l e . # T h i se f f e c t i v e l ye l i m i n a t e sg i b b e r i s ha n dn o i s e , # +a n do u t p u t so n l yr e c o g n i z e dw o r d s . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # S t a n d a r dC h e c kf o rS c r i p tA r g u m e n t ( s ) A R G S = 1 E _ B A D A R G S = 8 5 E _ N O F I L E = 8 6 i f[$ #n e$ A R G S] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ B A D A R G S f i i f[!f" $ 1 "] #C h e c ki ff i l ee x i s t s . t h e n e c h o" F i l e\ " $ 1 \ "d o e sn o te x i s t . " e x i t$ E _ N O F I L E f i #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

M I N S T R L E N = 3

# M i n i m u ms t r i n gl e n g t h .

W O R D F I L E = / u s r / s h a r e / d i c t / l i n u x . w o r d s # D i c t i o n a r yf i l e . # M a ys p e c i f yad i f f e r e n tw o r dl i s tf i l e # +o fo n e w o r d p e r l i n ef o r m a t . # F o re x a m p l e ,t h e" y a w l "w o r d l i s tp a c k a g e , # h t t p : / / b a s h . d e t a . i n / y a w l 0 . 3 . 2 . t a r . g z

w l i s t = ` s t r i n g s" $ 1 "|t rA Za z|t r' [ : s p a c e : ] 'Z|\ t rc s' [ : a l p h a : ] 'Z|t rs' \ 1 7 3 \ 3 7 7 'Z|t rZ'' ` #T r a n s l a t eo u t p u to f' s t r i n g s 'c o m m a n dw i t hm u l t i p l ep a s s e so f' t r ' . # " t rA Za z " c o n v e r t st ol o w e r c a s e . # " t r' [ : s p a c e : ] ' " c o n v e r t sw h i t e s p a c ec h a r a c t e r st oZ ' s . # " t rc s' [ : a l p h a : ] 'Z " c o n v e r t sn o n a l p h a b e t i cc h a r a c t e r st oZ ' s , # +a n ds q u e e z e sm u l t i p l ec o n s e c u t i v eZ ' s . # " t rs' \ 1 7 3 \ 3 7 7 'Z " c o n v e r t sa l lc h a r a c t e r sp a s t' z 't oZ ' s # +a n ds q u e e z e sm u l t i p l ec o n s e c u t i v eZ ' s , # +w h i c hg e t sr i do fa l lt h ew e i r dc h a r a c t e r st h a tt h ep r e v i o u s # +t r a n s l a t i o nf a i l e dt od e a lw i t h . # F i n a l l y ," t rZ'' "c o n v e r t sa l lt h o s eZ ' st ow h i t e s p a c e , # +w h i c hw i l lb es e e na sw o r ds e p a r a t o r si nt h el o o pb e l o w . # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * # N o t et h et e c h n i q u eo ff e e d i n g / p i p i n gt h eo u t p u to f' t r 'b a c kt oi t s e l f , # +b u tw i t hd i f f e r e n ta r g u m e n t sa n d / o ro p t i o n so ne a c hs u c c e s s i v ep a s s . # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

f o rw o r di n$ w l i s t

# I m p o r t a n t : # $ w l i s tm u s tn o tb eq u o t e dh e r e . #" $ w l i s t "d o e sn o tw o r k . # W h yn o t ? # S t r i n gl e n g t h . # S k i po v e rs h o r ts t r i n g s .

d o s t r l e n = $ { # w o r d } i f[" $ s t r l e n "l t" $ M I N S T R L E N "] t h e n c o n t i n u e f i g r e pF w$ w o r d" $ W O R D F I L E " ^ ^ ^

# M a t c hw h o l ew o r d so n l y . # " F i x e ds t r i n g s "a n d # +" w h o l ew o r d s "o p t i o n s .

d o n e e x i t$ ?

Comparison diff, patch diff: flexible file comparison utility. It compares the target files line-by-line sequentially. In some applications, such as comparing word dictionaries, it may be helpful to filter the files through sort and uniq before piping them to diff. d i f f f i l e 1f i l e 2outputs the lines in the files that differ, with carets showing which file each particular line belongs to. The s i d e b y s i d eoption to diff outputs each compared file, line by line, in separate columns, with non-matching lines marked. The cand uoptions likewise make the output of the command easier to interpret. There are available various fancy frontends for diff, such as sdiff, wdiff, xdiff, and mgdiff. The diff command returns an exit status of 0 if the compared files are identical, and 1 if they differ. This permits use of diff in a test construct within a shell script (see below). A common use for diff is generating difference files to be used with patch The eoption outputs files suitable for ed or ex scripts.

patch: flexible versioning utility. Given a difference file generated by diff, patch can upgrade a previous version of a package to a newer version. It is much more convenient to distribute a relatively small "diff" file than the entire body of a newly revised package. Kernel "patches" have become the preferred method of distributing the frequent releases of the Linux kernel.
p a t c hp 1< p a t c h f i l e #T a k e sa l lt h ec h a n g e sl i s t e di n' p a t c h f i l e ' #a n da p p l i e st h e mt ot h ef i l e sr e f e r e n c e dt h e r e i n . #T h i su p g r a d e st oan e w e rv e r s i o no ft h ep a c k a g e .

Patching the kernel:


c d/ u s r / s r c g z i pc dp a t c h X X . g z|p a t c hp 0 #U p g r a d i n gk e r n e ls o u r c eu s i n g' p a t c h ' . #F r o mt h eL i n u xk e r n e ld o c s" R E A D M E " , #b ya n o n y m o u sa u t h o r( A l a nC o x ? ) .

The diff command can also recursively compare directories (for the filenames present).
b a s h $d i f fr~ / n o t e s 1~ / n o t e s 2 O n l yi n/ h o m e / b o z o / n o t e s 1 :f i l e 0 2 O n l yi n/ h o m e / b o z o / n o t e s 1 :f i l e 0 3 O n l yi n/ h o m e / b o z o / n o t e s 2 :f i l e 0 4

Use zdiff to compare gzipped files. Use diffstat to create a histogram (point-distribution graph) of output from diff. diff3, merge An extended version of diff that compares three files at a time. This command returns an exit value of 0 upon successful execution, but unfortunately this gives no information about the results of the comparison.
b a s h $d i f f 3f i l e 1f i l e 2f i l e 3 = = = = 1 : 1 c T h i si sl i n e1o f" f i l e 1 " . 2 : 1 c T h i si sl i n e1o f" f i l e 2 " . 3 : 1 c T h i si sl i n e1o f" f i l e 3 "

The merge (3-way file merge) command is an interesting adjunct to diff3. Its syntax is m e r g eM e r g e f i l ef i l e 1 f i l e 2 . The result is to output to M e r g e f i l ethe changes that lead from f i l e 1to f i l e 2 . Consider this command a stripped-down version of patch. sdiff Compare and/or edit two files in order to merge them into an output file. Because of its interactive nature, this command would find little use in a script. cmp The cmp command is a simpler version of diff, above. Whereas diff reports the differences between two files, cmp merely shows at what point they differ. Like diff, cmp returns an exit status of 0 if the compared files are identical, and 1 if they differ. This

permits use in a test construct within a shell script. Example 16-35. Using cmp to compare two files within a script.
# ! / b i n / b a s h #f i l e c o m p a r i s o n . s h A R G S = 2 #T w oa r g st os c r i p te x p e c t e d . E _ B A D A R G S = 8 5 E _ U N R E A D A B L E = 8 6 i f[$ #n e" $ A R G S "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e 1f i l e 2 " e x i t$ E _ B A D A R G S f i i f[ [!r" $ 1 "| |!r" $ 2 "] ] t h e n e c h o" B o t hf i l e st ob ec o m p a r e dm u s te x i s ta n db er e a d a b l e . " e x i t$ E _ U N R E A D A B L E f i c m p$ 1$ 2& >/ d e v / n u l l # R e d i r e c t i o nt o/ d e v / n u l lb u r i e st h eo u t p u to ft h e" c m p "c o m m a n d . # c m ps$ 1$ 2 h a ss a m er e s u l t( " s "s i l e n tf l a gt o" c m p " ) # T h a n ky o u A n d e r sG u s t a v s s o nf o rp o i n t i n gt h i so u t . # # A l s ow o r k sw i t h' d i f f ' ,i . e . , # +d i f f$ 1$ 2& >/ d e v / n u l l i f[$ ?e q0] #T e s te x i ts t a t u so f" c m p "c o m m a n d . t h e n e c h o" F i l e\ " $ 1 \ "i si d e n t i c a lt of i l e\ " $ 2 \ " . " e l s e e c h o" F i l e\ " $ 1 \ "d i f f e r sf r o mf i l e\ " $ 2 \ " . " f i e x i t0

Use zcmp on gzipped files. comm Versatile file comparison utility. The files must be sorted for this to be useful. comm o p t i o n sf i r s t f i l es e c o n d f i l e
c o m mf i l e 1f i l e 2outputs three columns:

column 1 = lines unique to f i l e 1 column 2 = lines unique to f i l e 2 column 3 = lines common to both. The options allow suppressing output of one or more columns.
1suppresses column 1 2suppresses column 2 3suppresses column 3 1 2suppresses both columns 1and 2 , etc.

This command is useful for comparing "dictionaries" or word lists -- sorted text files with one word per line. Utilities basename Strips the path information from a file name, printing only the file name. The construction b a s e n a m e$ 0lets the script know its name, that is, the name it was invoked by. This can be used for "usage" messages if, for example a script is called with missing arguments:
e c h o" U s a g e :` b a s e n a m e$ 0 `a r g 1a r g 2. . .a r g n "

dirname Strips the basename from a filename, printing only the path information. basename and dirname can operate on any arbitrary string. The argument does not need to refer to an existing file, or even be a filename for that matter (see Example A-7). Example 16-36. basename and dirname
# ! / b i n / b a s h a d d r e s s = / h o m e / b o z o / d a i l y j o u r n a l . t x t e c h o" B a s e n a m eo f/ h o m e / b o z o / d a i l y j o u r n a l . t x t=` b a s e n a m e$ a d d r e s s ` " e c h o" D i r n a m eo f/ h o m e / b o z o / d a i l y j o u r n a l . t x t=` d i r n a m e$ a d d r e s s ` " e c h o e c h o" M yo w nh o m ei s` b a s e n a m e~ / ` . " #` b a s e n a m e~ `a l s ow o r k s . e c h o" T h eh o m eo fm yh o m ei s` d i r n a m e~ / ` . " #` d i r n a m e~ ` a l s ow o r k s . e x i t0

split, csplit These are utilities for splitting a file into smaller chunks. Their usual use is for splitting up large files in order to back them up on floppies or preparatory to e-mailing or uploading them. The csplit command splits a file according to context , the split occuring where patterns are matched. Example 16-37. A script that copies itself in sections
# ! / b i n / b a s h #s p l i t c o p y . s h # As c r i p tt h a ts p l i t si t s e l fi n t oc h u n k s , # +t h e nr e a s s e m b l e st h ec h u n k si n t oa ne x a c tc o p y # +o ft h eo r i g i n a ls c r i p t . C H U N K S I Z E = 4 O U T P R E F I X = x x # S i z eo ff i r s tc h u n ko fs p l i tf i l e s . # c s p l i tp r e f i x e s ,b yd e f a u l t , # +f i l e sw i t h" x x ". . .

c s p l i t" $ 0 "" $ C H U N K S I Z E " #S o m ec o m m e n tl i n e sf o rp a d d i n g... #L i n e1 5 #L i n e1 6 #L i n e1 7 #L i n e1 8 #L i n e1 9 #L i n e2 0 c a t" $ O U T P R E F I X " *>" $ 0 . c o p y " #C o n c a t e n a t et h ec h u n k s . r m" $ O U T P R E F I X " * #G e tr i do ft h ec h u n k s .

e x i t$ ?

Encoding and Encryption sum, cksum, md5sum, sha1sum These are utilities for generating checksums. A checksum is a number [77] mathematically calculated from the contents of a file, for the purpose of checking its integrity. A script might refer to a list of checksums for security purposes, such as ensuring that the contents of key system files have not been altered or corrupted. For security applications, use the md5sum (message digest 5 checksum) command, or better yet, the newer sha1sum (Secure Hash Algorithm). [78]
b a s h $c k s u m/ b o o t / v m l i n u z 1 6 7 0 0 5 4 2 2 48 0 4 0 8 3/ b o o t / v m l i n u z b a s h $e c h on" T o pS e c r e t "|c k s u m 3 3 9 1 0 0 3 8 2 71 0

b a s h $m d 5 s u m/ b o o t / v m l i n u z 0 f 4 3 e c c e a 8 f 0 9 e 0 a 0 b 2 b 5 c f 1 d c f 3 3 3 b a / b o o t / v m l i n u z b a s h $e c h on" T o pS e c r e t "|m d 5 s u m 8 b a b c 9 7 a 6 f 6 2 a 4 6 4 9 7 1 6 f 4 d f 8 d 6 1 7 2 8 f -

The cksum command shows the size, in bytes, of its target, whether file or s t d o u t . The md5sum and sha1sum commands display a dash when they receive their input from s t d o u t . Example 16-38. Checking file integrity
# ! / b i n / b a s h #f i l e i n t e g r i t y . s h :C h e c k i n gw h e t h e rf i l e si nag i v e nd i r e c t o r y # h a v eb e e nt a m p e r e dw i t h . E _ D I R _ N O M A T C H = 8 0 E _ B A D _ D B F I L E = 8 1 d b f i l e = F i l e _ r e c o r d . m d 5 #F i l e n a m ef o rs t o r i n gr e c o r d s( d a t a b a s ef i l e ) .

s e t _ u p _ d a t a b a s e( ) { e c h o" " $ d i r e c t o r y " ">" $ d b f i l e " #W r i t ed i r e c t o r yn a m et of i r s tl i n eo ff i l e . m d 5 s u m" $ d i r e c t o r y " / *> >" $ d b f i l e " #A p p e n dm d 5c h e c k s u m sa n df i l e n a m e s . } c h e c k _ d a t a b a s e( ) { l o c a ln = 0 l o c a lf i l e n a m e l o c a lc h e c k s u m #-# # T h i sf i l ec h e c ks h o u l db eu n n e c e s s a r y , # +b u tb e t t e rs a f et h a ns o r r y . i f[!r" $ d b f i l e "] t h e n e c h o" U n a b l et or e a dc h e c k s u md a t a b a s ef i l e ! "

e x i t$ E _ B A D _ D B F I L E f i #-# w h i l er e a dr e c o r d [ n ] d o d i r e c t o r y _ c h e c k e d = " $ { r e c o r d [ 0 ] } " i f[" $ d i r e c t o r y _ c h e c k e d "! =" $ d i r e c t o r y "] t h e n e c h o" D i r e c t o r i e sd on o tm a t c hu p ! " #T r i e dt ou s ef i l ef o rad i f f e r e n td i r e c t o r y . e x i t$ E _ D I R _ N O M A T C H f i i f[" $ n "g t0] #N o td i r e c t o r yn a m e . t h e n f i l e n a m e [ n ] = $ (e c h o$ { r e c o r d [ $ n ] }|a w k' {p r i n t$ 2} ') # m d 5 s u mw r i t e sr e c o r d sb a c k w a r d s , # +c h e c k s u mf i r s t ,t h e nf i l e n a m e . c h e c k s u m [ n ] = $ (m d 5 s u m" $ { f i l e n a m e [ n ] } ")

i f[" $ { r e c o r d [ n ] } "=" $ { c h e c k s u m [ n ] } "] t h e n e c h o" $ { f i l e n a m e [ n ] }u n c h a n g e d . " e l i f[" ` b a s e n a m e$ { f i l e n a m e [ n ] } ` "! =" $ d b f i l e "] # S k i po v e rc h e c k s u md a t a b a s ef i l e , # +a si tw i l lc h a n g ew i t he a c hi n v o c a t i o no fs c r i p t . # # T h i su n f o r t u n a t e l ym e a n st h a tw h e nr u n n i n g # +t h i ss c r i p to n$ P W D ,t a m p e r i n gw i t ht h e # +c h e c k s u md a t a b a s ef i l ew i l ln o tb ed e t e c t e d . # E x e r c i s e :F i xt h i s . t h e n e c h o" $ { f i l e n a m e [ n ] }:C H E C K S U ME R R O R ! " #F i l eh a sb e e nc h a n g e ds i n c el a s tc h e c k e d . f i f i

l e t" n + = 1 " d o n e< " $ d b f i l e " }

#R e a df r o mc h e c k s u md a t a b a s ef i l e .

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# #m a i n( ) i f[z " $ 1 "] t h e n d i r e c t o r y = " $ P W D " e l s e d i r e c t o r y = " $ 1 " f i

# I fn o ts p e c i f i e d , # +u s ec u r r e n tw o r k i n gd i r e c t o r y .

c l e a r #C l e a rs c r e e n . e c h o"R u n n i n gf i l ei n t e g r i t yc h e c ko n$ d i r e c t o r y " e c h o #-# i f[!r" $ d b f i l e "]#N e e dt oc r e a t ed a t a b a s ef i l e ? t h e n e c h o" S e t t i n gu pd a t a b a s ef i l e ,\ " " $ d i r e c t o r y " / " $ d b f i l e " \ " . " ;e c h o s e t _ u p _ d a t a b a s e f i

#-# c h e c k _ d a t a b a s e e c h o # Y o um a yw i s ht or e d i r e c tt h es t d o u to ft h i ss c r i p tt oaf i l e , # +e s p e c i a l l yi ft h ed i r e c t o r yc h e c k e dh a sm a n yf i l e si ni t . e x i t0 # F o ram u c hm o r et h o r o u g hf i l ei n t e g r i t yc h e c k , # +c o n s i d e rt h e" T r i p w i r e "p a c k a g e , # +h t t p : / / s o u r c e f o r g e . n e t / p r o j e c t s / t r i p w i r e / . #D ot h ea c t u a lw o r k .

Also see Example A-19, Example 36-14, and Example 10-2 for creative uses of the md5sum command. There have been reports that the 128-bit md5sum can be cracked, so the more secure 160-bit sha1sum is a welcome new addition to the checksum toolkit.
b a s h $m d 5 s u mt e s t f i l e e 1 8 1 e 2 c 8 7 2 0 c 6 0 5 2 2 c 4 c 4 c 9 8 1 1 0 8 e 3 6 7 t e s t f i l e

b a s h $s h a 1 s u mt e s t f i l e 5 d 7 4 2 5 a 9 c 0 8 a 6 6 c 3 1 7 7 f 1 e 3 1 2 8 6 f a 4 0 9 8 6 f f c 9 9 6 t e s t f i l e

Security consultants have demonstrated that even sha1sum can be compromised. Fortunately, newer Linux distros include longer bit-length sha224sum, sha256sum, sha384sum, and sha512sum commands. uuencode This utility encodes binary files (images, sound files, compressed files, etc.) into ASCII characters, making them suitable for transmission in the body of an e-mail message or in a newsgroup posting. This is especially useful where MIME (multimedia) encoding is not available. uudecode This reverses the encoding, decoding uuencoded files back into the original binaries. Example 16-39. Uudecoding encoded files
# ! / b i n / b a s h #U u d e c o d e sa l lu u e n c o d e df i l e si nc u r r e n tw o r k i n gd i r e c t o r y . l i n e s = 3 5 #A l l o w3 5l i n e sf o rt h eh e a d e r( v e r yg e n e r o u s ) .

f o rF i l ei n* #T e s ta l lt h ef i l e si n$ P W D . d o s e a r c h 1 = ` h e a dn$ l i n e s$ F i l e|g r e pb e g i n|w cw ` s e a r c h 2 = ` t a i ln$ l i n e s$ F i l e|g r e pe n d|w cw ` # U u e n c o d e df i l e sh a v ea" b e g i n "n e a rt h eb e g i n n i n g , # +a n da n" e n d "n e a rt h ee n d . i f[" $ s e a r c h 1 "g t0] t h e n i f[" $ s e a r c h 2 "g t0] t h e n e c h o" u u d e c o d i n g-$ F i l e" u u d e c o d e$ F i l e f i f i d o n e # N o t et h a tr u n n i n gt h i ss c r i p tu p o ni t s e l ff o o l si t

# +i n t ot h i n k i n gi ti sau u e n c o d e df i l e , # +b e c a u s ei tc o n t a i n sb o t h" b e g i n "a n d" e n d " . # E x e r c i s e : # # M o d i f yt h i ss c r i p tt oc h e c ke a c hf i l ef o ran e w s g r o u ph e a d e r , # +a n ds k i pt on e x ti fn o tf o u n d . e x i t0

The fold -s command may be useful (possibly in a pipe) to process long uudecoded text messages downloaded from Usenet newsgroups. mimencode , mmencode The mimencode and mmencode commands process multimedia-encoded e-mail attachments. Although mail user agents (such as pine or kmail) normally handle this automatically, these particular utilities permit manipulating such attachments manually from the command-line or in batch processing mode by means of a shell script. crypt At one time, this was the standard UNIX file encryption utility. [79] Politically-motivated government regulations prohibiting the export of encryption software resulted in the disappearance of crypt from much of the UNIX world, and it is still missing from most Linux distributions. Fortunately, programmers have come up with a number of decent alternatives to it, among them the author's very own cruft (see Example A-4). openssl This is an Open Source implementation of Secure Sockets Layer encryption.
#T oe n c r y p taf i l e : o p e n s s la e s 1 2 8 e c bs a l ti nf i l e . t x to u tf i l e . e n c r y p t e d\ p a s sp a s s : m y _ p a s s w o r d # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ U s e r s e l e c t e dp a s s w o r d . # a e s 1 2 8 e c b i st h ee n c r y p t i o nm e t h o dc h o s e n . #T od e c r y p ta no p e n s s l e n c r y p t e df i l e : o p e n s s la e s 1 2 8 e c bds a l ti nf i l e . e n c r y p t e do u tf i l e . t x t\ p a s sp a s s : m y _ p a s s w o r d # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ U s e r s e l e c t e dp a s s w o r d .

Piping openssl to/from tar makes it possible to encrypt an entire directory tree.
#T oe n c r y p tad i r e c t o r y : s o u r c e d i r = " / h o m e / b o z o / t e s t f i l e s " e n c r f i l e = " e n c r d i r . t a r . g z " p a s s w o r d = m y _ s e c r e t _ p a s s w o r d t a rc z v f-" $ s o u r c e d i r "| o p e n s s ld e s 3s a l to u t" $ e n c r f i l e "p a s sp a s s : " $ p a s s w o r d " # ^ ^ ^ ^ U s e sd e s 3e n c r y p t i o n . #W r i t e se n c r y p t e df i l e" e n c r d i r . t a r . g z "i nc u r r e n tw o r k i n gd i r e c t o r y . #T od e c r y p tt h er e s u l t i n gt a r b a l l : o p e n s s ld e s 3ds a l ti n" $ e n c r f i l e "p a s sp a s s : " $ p a s s w o r d "| t a rx z v #D e c r y p t sa n du n p a c k si n t oc u r r e n tw o r k i n gd i r e c t o r y .

Of course, openssl has many other uses, such as obtaining signed certificates for Web sites. See the info page. shred Securely erase a file by overwriting it multiple times with random bit patterns before deleting it. This command has the same effect as Example 16-60, but does it in a more thorough and elegant manner.

This is one of the GNU fileutils. Advanced forensic technology may still be able to recover the contents of a file, even after application of shred. Miscellaneous mktemp Create a temporary file [80] with a "unique" filename. When invoked from the command-line without additional arguments, it creates a zero-length file in the / t m pdirectory.
b a s h $m k t e m p / t m p / t m p . z z s v q l 3 1 5 4

P R E F I X = f i l e n a m e t e m p f i l e = ` m k t e m p$ P R E F I X . X X X X X X ` # ^ ^ ^ ^ ^ ^N e e da tl e a s t6p l a c e h o l d e r s # + i nt h ef i l e n a m et e m p l a t e . # I fn of i l e n a m et e m p l a t es u p p l i e d , # +" t m p . X X X X X X X X X X "i st h ed e f a u l t . e c h o" t e m p f i l en a m e=$ t e m p f i l e " #t e m p f i l en a m e=f i l e n a m e . Q A 2 Z p Y # o rs o m e t h i n gs i m i l a r . . . # C r e a t e saf i l eo ft h a tn a m ei nt h ec u r r e n tw o r k i n gd i r e c t o r y # +w i t h6 0 0f i l ep e r m i s s i o n s . # A" u m a s k1 7 7 "i st h e r e f o r eu n n e c e s s a r y , # +b u ti t ' sg o o dp r o g r a m m i n gp r a c t i c en e v e r t h e l e s s .

make Utility for building and compiling binary packages. This can also be used for any set of operations triggered by incremental changes in source files. The make command checks a M a k e f i l e , a list of file dependencies and operations to be carried out. The make utility is, in effect, a powerful scripting language similar in many ways to Bash, but with the capability of recognizing dependencies. For in-depth coverage of this useful tool set, see the GNU software documentation site. install Special purpose file copying command, similar to cp, but capable of setting permissions and attributes of the copied files. This command seems tailormade for installing software packages, and as such it shows up frequently in M a k e f i l e s(in the m a k ei n s t a l l :section). It could likewise prove useful in installation scripts. dos2unix This utility, written by Benjamin Lin and collaborators, converts DOS-formatted text files (lines terminated by CR-LF) to UNIX format (lines terminated by LF only), and vice-versa. ptx The ptx [targetfile] command outputs a permuted index (cross-reference list) of the targetfile. This may be further filtered and formatted in a pipe, if necessary. more , less Pagers that display a text file or stream to s t d o u t , one screenful at a time. These may be used to filter the output of

s t d o u t.

. . or of a script.

An interesting application of more is to "test drive" a command sequence, to forestall potentially unpleasant consequences.
l s/ h o m e / b o z o|a w k' { p r i n t" r mr f"$ 1 } '|m o r e # ^ ^ ^ ^ #T e s t i n gt h ee f f e c to ft h ef o l l o w i n g( d i s a s t r o u s )c o m m a n d l i n e : # l s/ h o m e / b o z o|a w k' { p r i n t" r mr f"$ 1 } '|s h # H a n do f ft ot h es h e l lt oe x e c u t e... ^ ^

The less pager has the interesting property of doing a formatted display of man page source. See Example A-39.

16.6. Communications Commands


Certain of the following commands find use in network data transfer and analysis, as well as in chasing spammers. Information and Statistics host Searches for information about an Internet host by name or IP address, using DNS.
b a s h $h o s ts u r f a c e m a i l . c o m s u r f a c e m a i l . c o m .h a sa d d r e s s2 0 2 . 9 2 . 4 2 . 2 3 6

ipcalc Displays IP information for a host. With the hoption, ipcalc does a reverse DNS lookup, finding the name of the host (server) from the IP address.
b a s h $i p c a l ch2 0 2 . 9 2 . 4 2 . 2 3 6 H O S T N A M E = s u r f a c e m a i l . c o m

nslookup Do an Internet "name server lookup" on a host by IP address. This is essentially equivalent to ipcalc -h or dig -x . The command may be run either interactively or noninteractively, i.e., from within a script. The nslookup command has allegedly been "deprecated," but it is still useful.
b a s h $n s l o o k u ps i l6 6 . 9 7 . 1 0 4 . 1 8 0 n s l o o k u pk u h l e e r s p a r n i s . c h S e r v e r : 1 3 5 . 1 1 6 . 1 3 7 . 2 A d d r e s s : 1 3 5 . 1 1 6 . 1 3 7 . 2 # 5 3 N o n a u t h o r i t a t i v ea n s w e r : N a m e : k u h l e e r s p a r n i s . c h

dig Domain Information Groper. Similar to nslookup, dig does an Internet name server lookup on a host. May be run from the command-line or from within a script. Some interesting options to dig are + t i m e = Nfor setting a query timeout to Nseconds, + n o f a i lfor continuing to query servers until a reply is received, and xfor doing a reverse address lookup.

Compare the output of dig -x with ipcalc -h and nslookup.


b a s h $d i gx8 1 . 9 . 6 . 2 ; ;G o ta n s w e r : ; ;> > H E A D E R < < -o p c o d e :Q U E R Y ,s t a t u s :N X D O M A I N ,i d :1 1 6 4 9 ; ;f l a g s :q rr dr a ;Q U E R Y :1 ,A N S W E R :0 ,A U T H O R I T Y :1 ,A D D I T I O N A L :0 ; ;Q U E S T I O NS E C T I O N : ; 2 . 6 . 9 . 8 1 . i n a d d r . a r p a . ; ;A U T H O R I T YS E C T I O N : 6 . 9 . 8 1 . i n a d d r . a r p a . 3 6 0 0 2 0 0 2 0 3 1 7 0 59 0 06 0 08 6 4 0 03 6 0 0

I N

P T R

I N

S O A

n s . e l t e l . n e t .n o c . e l t e l . n e t .

; ;Q u e r yt i m e :5 3 7m s e c ; ;S E R V E R :1 3 5 . 1 1 6 . 1 3 7 . 2 # 5 3 ( 1 3 5 . 1 1 6 . 1 3 7 . 2 ) ; ;W H E N :W e dJ u n2 60 8 : 3 5 : 2 42 0 0 2 ; ;M S GS I Z E r c v d :9 1

Example 16-40. Finding out where to report a spammer


# ! / b i n / b a s h #s p a m l o o k u p . s h :L o o ku pa b u s ec o n t a c tt or e p o r tas p a m m e r . #T h a n k s ,M i c h a e lZ i c k . #C h e c kf o rc o m m a n d l i n ea r g . A R G C O U N T = 1 E _ W R O N G A R G S = 8 5 i f[$ #n e" $ A R G C O U N T "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `d o m a i n n a m e " e x i t$ E _ W R O N G A R G S f i

d i g+ s h o r t$ 1 . c o n t a c t s . a b u s e . n e tci ntt x t #A l s ot r y : # d i g+ n s s e a r c h$ 1 # T r i e st of i n d" a u t h o r i t a t i v en a m es e r v e r s "a n dd i s p l a yS O Ar e c o r d s . #T h ef o l l o w i n ga l s ow o r k s : # w h o i shw h o i s . a b u s e . n e t$ 1 # ^ ^^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ S p e c i f yh o s t . # C a ne v e nl o o k u pm u l t i p l es p a m m e r sw i t ht h i s ,i . e . " # w h o i shw h o i s . a b u s e . n e t$ s p a m d o m a i n 1$ s p a m d o m a i n 2...

# E x e r c i s e : # # E x p a n dt h ef u n c t i o n a l i t yo ft h i ss c r i p t # +s ot h a ti ta u t o m a t i c a l l ye m a i l san o t i f i c a t i o n # +t ot h er e s p o n s i b l eI S P ' sc o n t a c ta d d r e s s ( e s ) . # H i n t :u s et h e" m a i l "c o m m a n d . e x i t$ ? #s p a m l o o k u p . s hc h i n a t i e t o n g . c o m # Ak n o w ns p a md o m a i n . #" c r n e t _ m g r @ c h i n a t i e t o n g . c o m " #" c r n e t _ t e c @ c h i n a t i e t o n g . c o m " #" p o s t m a s t e r @ c h i n a t i e t o n g . c o m "

# F o ram o r ee l a b o r a t ev e r s i o no ft h i ss c r i p t , # +s e et h eS p a m V i zh o m ep a g e ,h t t p : / / w w w . s p a m v i z . n e t / i n d e x . h t m l .

Example 16-41. Analyzing a spam domain


# !/ b i n / b a s h #i s s p a m m e r . s h :I d e n t i f y i n gs p a md o m a i n s #$ I d :i s s p a m m e r ,v1 . 42 0 0 4 / 0 9 / 0 11 9 : 3 7 : 5 2m s z i c kE x p$ #A b o v el i n ei sR C SI Di n f o . # # T h i si sas i m p l i f i e dv e r s i o no ft h e" i s _ s p a m m e r . b a s h # +s c r i p ti nt h eC o n t r i b u t e dS c r i p t sa p p e n d i x . #i s s p a m m e r< d o m a i n . n a m e > #U s e sa ne x t e r n a lp r o g r a m :' d i g ' #T e s t e dw i t hv e r s i o n :9 . 2 . 4 r c 5 #U s e sf u n c t i o n s . #U s e sI F St op a r s es t r i n g sb ya s s i g n m e n ti n t oa r r a y s . #A n de v e nd o e ss o m e t h i n gu s e f u l :c h e c k se m a i lb l a c k l i s t s . #U s et h ed o m a i n . n a m e ( s )f r o mt h et e x tb o d y : #h t t p : / / w w w . g o o d _ s t u f f . s p a m m e r . b i z / j u s t _ i g n o r e _ e v e r y t h i n g _ e l s e # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ #O rt h ed o m a i n . n a m e ( s )f r o ma n ye m a i la d d r e s s : #R e a l l y _ G o o d _ O f f e r @ s p a m m e r . b i z # #a st h eo n l ya r g u m e n tt ot h i ss c r i p t . # ( P S :h a v ey o u rI n e tc o n n e c t i o nr u n n i n g ) # #S o ,t oi n v o k et h i ss c r i p ti nt h ea b o v et w oi n s t a n c e s : # i s s p a m m e r . s hs p a m m e r . b i z

#W h i t e s p a c e= =: S p a c e : T a b : L i n eF e e d : C a r r i a g eR e t u r n : W S P _ I F S = $ ' \ x 2 0 ' $ ' \ x 0 9 ' $ ' \ x 0 A ' $ ' \ x 0 D ' #N oW h i t e s p a c e= =L i n eF e e d : C a r r i a g eR e t u r n N o _ W S P = $ ' \ x 0 A ' $ ' \ x 0 D ' #F i e l ds e p a r a t o rf o rd o t t e dd e c i m a li pa d d r e s s e s A D R _ I F S = $ { N o _ W S P } ' . ' #G e tt h ed n st e x tr e s o u r c er e c o r d . #g e t _ t x t< e r r o r _ c o d e >< l i s t _ q u e r y > g e t _ t x t ( ){ #P a r s e$ 1b ya s s i g n m e n ta tt h ed o t s . l o c a lad n s I F S = $ A D R _ I F S d n s = ($ 1) I F S = $ W S P _ I F S i f[" $ { d n s [ 0 ] } "= =' 1 2 7 '] t h e n #S e ei ft h e r ei sar e a s o n . e c h o$ ( d i g+ s h o r t$ 2tt x t ) f i } #G e tt h ed n sa d d r e s sr e s o u r c er e c o r d . #c h k _ a d r< r e v _ d n s >< l i s t _ s e r v e r > c h k _ a d r ( ){ l o c a lr e p l y l o c a ls e r v e r l o c a lr e a s o n s e r v e r = $ { 1 } $ { 2 } r e p l y = $ (d i g+ s h o r t$ { s e r v e r }) #I fr e p l ym i g h tb ea ne r r o rc o d e...

i f[$ { # r e p l y }g t6] t h e n r e a s o n = $ ( g e t _ t x t$ { r e p l y }$ { s e r v e r }) r e a s o n = $ { r e a s o n : $ { r e p l y } } f i e c h o$ { r e a s o n : 'n o tb l a c k l i s t e d . ' } } #N e e dt og e tt h eI Pa d d r e s sf r o mt h en a m e . e c h o' G e ta d d r e s so f :' $ 1 i p _ a d r = $ ( d i g+ s h o r t$ 1 ) d n s _ r e p l y = $ { i p _ a d r : 'n oa n s w e r' } e c h o'F o u n da d d r e s s :' $ { d n s _ r e p l y } #Av a l i dr e p l yi sa tl e a s t4d i g i t sp l u s3d o t s . i f[$ { # i p _ a d r }g t6] t h e n e c h o d e c l a r eq u e r y #P a r s eb ya s s i g n m e n ta tt h ed o t s . d e c l a r ead n s I F S = $ A D R _ I F S d n s = ($ { i p _ a d r }) I F S = $ W S P _ I F S #R e o r d e ro c t e t si n t od n sq u e r yo r d e r . r e v _ d n s = " $ { d n s [ 3 ] } " ' . ' " $ { d n s [ 2 ] } " ' . ' " $ { d n s [ 1 ] } " ' . ' " $ { d n s [ 0 ] } " ' . ' #S e e :h t t p : / / w w w . s p a m h a u s . o r g( C o n s e r v a t i v e ,w e l lm a i n t a i n e d ) e c h on' s p a m h a u s . o r gs a y s :' e c h o$ ( c h k _ a d r$ { r e v _ d n s }' s b l x b l . s p a m h a u s . o r g ' ) #S e e :h t t p : / / o r d b . o r g( O p e nm a i lr e l a y s ) e c h on' o r d b . o r g s a y s :' e c h o$ ( c h k _ a d r$ { r e v _ d n s }' r e l a y s . o r d b . o r g ' ) #S e e :h t t p : / / w w w . s p a m c o p . n e t /( Y o uc a nr e p o r ts p a m m e r sh e r e ) e c h on's p a m c o p . n e ts a y s :' e c h o$ ( c h k _ a d r$ { r e v _ d n s }' b l . s p a m c o p . n e t ' ) ###o t h e rb l a c k l i s to p e r a t i o n s### #S e e :h t t p : / / c b l . a b u s e a t . o r g . e c h on'a b u s e a t . o r gs a y s :' e c h o$ ( c h k _ a d r$ { r e v _ d n s }' c b l . a b u s e a t . o r g ' ) #S e e :h t t p : / / d s b l . o r g / u s a g e( V a r i o u sm a i lr e l a y s ) e c h o e c h o' D i s t r i b u t e dS e r v e rL i s t i n g s ' e c h on' l i s t . d s b l . o r gs a y s :' e c h o$ ( c h k _ a d r$ { r e v _ d n s }' l i s t . d s b l . o r g ' ) e c h on' m u l t i h o p . d s b l . o r gs a y s :' e c h o$ ( c h k _ a d r$ { r e v _ d n s }' m u l t i h o p . d s b l . o r g ' ) e c h on' u n c o n f i r m e d . d s b l . o r gs a y s :' e c h o$ ( c h k _ a d r$ { r e v _ d n s }' u n c o n f i r m e d . d s b l . o r g ' ) e l s e e c h o e c h o' C o u l dn o tu s et h a ta d d r e s s . ' f i e x i t0 #E x e r c i s e s : #-

#1 )C h e c ka r g u m e n t st os c r i p t , # a n de x i tw i t ha p p r o p r i a t ee r r o rm e s s a g ei fn e c e s s a r y . #2 )C h e c ki fo n l i n ea ti n v o c a t i o no fs c r i p t , # a n de x i tw i t ha p p r o p r i a t ee r r o rm e s s a g ei fn e c e s s a r y . #3 )S u b s t i t u t eg e n e r i cv a r i a b l e sf o r" h a r d c o d e d "B H Ld o m a i n s . #4 )S e tat i m e o u tf o rt h es c r i p tu s i n gt h e" + t i m e = "o p t i o n t ot h e' d i g 'c o m m a n d .

For a much more elaborate version of the above script, see Example A-28. traceroute Trace the route taken by packets sent to a remote host. This command works within a LAN, WAN, or over the Internet. The remote host may be specified by an IP address. The output of this command may be filtered by grep or sed in a pipe.
b a s h $t r a c e r o u t e8 1 . 9 . 6 . 2 t r a c e r o u t et o8 1 . 9 . 6 . 2( 8 1 . 9 . 6 . 2 ) ,3 0h o p sm a x ,3 8b y t ep a c k e t s 1 t c 4 3 . x j b n n b r b . c o m( 1 3 6 . 3 0 . 1 7 8 . 8 ) 1 9 1 . 3 0 3m s 1 7 9 . 4 0 0m s 1 7 9 . 7 6 7m s 2 o r 0 . x j b n n b r b . c o m( 1 3 6 . 3 0 . 1 7 8 . 1 ) 1 7 9 . 5 3 6m s 1 7 9 . 5 3 4m s 1 6 9 . 6 8 5m s 3 1 9 2 . 1 6 8 . 1 1 . 1 0 1( 1 9 2 . 1 6 8 . 1 1 . 1 0 1 ) 1 8 9 . 4 7 1m s 1 8 9 . 5 5 6m s* . . .

ping Broadcast an I C M PE C H O _ R E Q U E S Tpacket to another machine, either on a local or remote network. This is a diagnostic tool for testing network connections, and it should be used with caution.
b a s h $p i n gl o c a l h o s t P I N Gl o c a l h o s t . l o c a l d o m a i n( 1 2 7 . 0 . 0 . 1 )f r o m1 2 7 . 0 . 0 . 1:5 6 ( 8 4 )b y t e so fd a t a . 6 4b y t e sf r o ml o c a l h o s t . l o c a l d o m a i n( 1 2 7 . 0 . 0 . 1 ) :i c m p _ s e q = 0t t l = 2 5 5t i m e = 7 0 9u s e c 6 4b y t e sf r o ml o c a l h o s t . l o c a l d o m a i n( 1 2 7 . 0 . 0 . 1 ) :i c m p _ s e q = 1t t l = 2 5 5t i m e = 2 8 6u s e c -l o c a l h o s t . l o c a l d o m a i np i n gs t a t i s t i c s2p a c k e t st r a n s m i t t e d ,2p a c k e t sr e c e i v e d ,0 %p a c k e tl o s s r o u n d t r i pm i n / a v g / m a x / m d e v=0 . 2 8 6 / 0 . 4 9 7 / 0 . 7 0 9 / 0 . 2 1 2m s

A successful ping returns an exit status of 0. This can be tested for in a script.
H N A M E = n e w s 1 5 . n e t #N o t o r i o u ss p a m m e r . #H N A M E = $ H O S T #D e b u g :t e s tf o rl o c a l h o s t . c o u n t = 2 #S e n do n l yt w op i n g s . i f[ [` p i n gc$ c o u n t" $ H N A M E " `] ] t h e n e c h o" " $ H N A M E "s t i l lu pa n db r o a d c a s t i n gs p a my o u rw a y . " e l s e e c h o" " $ H N A M E "s e e m st ob ed o w n .P i t y . " f i

whois Perform a DNS (Domain Name System) lookup. The hoption permits specifying which particular whois server to query. See Example 4-6 and Example 16-40. finger Retrieve information about users on a network. Optionally, this command can display a user's ~ / . p l a n ,

~ / . p r o j e c t , and ~ / . f o r w a r dfiles,

if present.
I d l e L o g i nT i m e O f f i c e 8 J u n2 51 6 : 5 9 J u n2 51 6 : 5 9 J u n2 51 7 : 0 7 O f f i c eP h o n e ( : 0 ) ( : 0 . 0 ) ( : 0 . 0 )

b a s h $f i n g e r L o g i n N a m e T t y b o z o B o z oB o z e m a n t t y 1 b o z o B o z oB o z e m a n t t y p 0 b o z o B o z oB o z e m a n t t y p 1

b a s h $f i n g e rb o z o L o g i n :b o z o N a m e :B o z oB o z e m a n D i r e c t o r y :/ h o m e / b o z o S h e l l :/ b i n / b a s h O f f i c e :2 3 5 5C l o w nS t . ,5 4 3 1 2 3 4 O ns i n c eF r iA u g3 12 0 : 1 3( M S T )o nt t y 1 1h o u r3 8m i n u t e si d l e O ns i n c eF r iA u g3 12 0 : 1 3( M S T )o np t s / 0 1 2s e c o n d si d l e O ns i n c eF r iA u g3 12 0 : 1 3( M S T )o np t s / 1 O ns i n c eF r iA u g3 12 0 : 3 1( M S T )o np t s / 2 1h o u r1 6m i n u t e si d l e M a i ll a s tr e a dT u eJ u l 31 0 : 0 82 0 0 7( M S T ) N oP l a n .

Out of security considerations, many networks disable finger and its associated daemon. [81] chfn Change information disclosed by the finger command. vrfy Verify an Internet e-mail address. This command seems to be missing from newer Linux distros. Remote Host Access sx, rx The sx and rx command set serves to transfer files to and from a remote host using the xmodem protocol. These are generally part of a communications package, such as minicom. sz, rz The sz and rz command set serves to transfer files to and from a remote host using the zmodem protocol. Zmodem has certain advantages over xmodem, such as faster transmission rate and resumption of interrupted file transfers. Like sx and rx, these are generally part of a communications package. ftp Utility and protocol for uploading / downloading files to or from a remote host. An ftp session can be automated in a script (see Example 19-6 and Example A-4). uucp, uux, cu uucp: UNIX to UNIX copy. This is a communications package for transferring files between UNIX servers. A shell script is an effective way to handle a uucp command sequence. Since the advent of the Internet and e-mail, uucp seems to have faded into obscurity, but it still exists and remains perfectly workable in situations where an Internet connection is not available or appropriate. The advantage of uucp is that it is fault-tolerant, so even if there is a service interruption the copy operation will resume where it left off when the connection is restored.

--uux: UNIX to UNIX execute. Execute a command on a remote system. This command is part of the uucp package. --cu: Call Up a remote system and connect as a simple terminal. It is a sort of dumbed-down version of telnet. This command is part of the uucp package. telnet Utility and protocol for connecting to a remote host. The telnet protocol contains security holes and should therefore probably be avoided. Its use within a shell script is not recommended. wget The wget utility noninteractively retrieves or downloads files from a Web or ftp site. It works well in a script.
w g e tph t t p : / / w w w . x y z 2 3 . c o m / f i l e 0 1 . h t m l # T h epo rp a g e r e q u i s i t eo p t i o nc a u s e sw g e tt of e t c ha l lf i l e s # +r e q u i r e dt od i s p l a yt h es p e c i f i e dp a g e . w g e trf t p : / / f t p . x y z 2 4 . n e t / ~ b o z o / p r o j e c t _ f i l e s /O$ S A V E F I L E # T h ero p t i o nr e c u r s i v e l yf o l l o w sa n dr e t r i e v e sa l ll i n k s # +o nt h es p e c i f i e ds i t e . w g e tcf t p : / / f t p . x y z 2 5 . n e t / b o z o f i l e s / f i l e n a m e . t a r . b z 2 # T h eco p t i o nl e t sw g e tr e s u m ea ni n t e r r u p t e dd o w n l o a d . # T h i sw o r k sw i t hf t ps e r v e r sa n dm a n yH T T Ps i t e s .

Example 16-42. Getting a stock quote


# ! / b i n / b a s h #q u o t e f e t c h . s h :D o w n l o a das t o c kq u o t e .

E _ N O P A R A M S = 8 6 i f[z" $ 1 "] #M u s ts p e c i f yas t o c k( s y m b o l )t of e t c h . t h e ne c h o" U s a g e :` b a s e n a m e$ 0 `s t o c k s y m b o l " e x i t$ E _ N O P A R A M S f i s t o c k _ s y m b o l = $ 1 f i l e _ s u f f i x = . h t m l #F e t c h e sa nH T M Lf i l e ,s on a m ei ta p p r o p r i a t e l y . U R L = ' h t t p : / / f i n a n c e . y a h o o . c o m / q ? s = ' #Y a h o of i n a n c eb o a r d ,w i t hs t o c kq u e r ys u f f i x . #w g e tO$ { s t o c k _ s y m b o l } $ { f i l e _ s u f f i x }" $ { U R L } $ { s t o c k _ s y m b o l } " #-

#T ol o o ku ps t u f fo nh t t p : / / s e a r c h . y a h o o . c o m : ##U R L = " h t t p : / / s e a r c h . y a h o o . c o m / s e a r c h ? f r = u s h n e w s & p = $ { q u e r y } " #w g e tO" $ s a v e f i l e n a m e "" $ { U R L } " ##S a v e sal i s to fr e l e v a n tU R L s . e x i t$ ?

#E x e r c i s e s : ## #1 )A d dat e s tt oe n s u r et h eu s e rr u n n i n gt h es c r i p ti so n l i n e . # ( H i n t :p a r s et h eo u t p u to f' p sa x 'f o r" p p p "o r" c o n n e c t . " # #2 )M o d i f yt h i ss c r i p tt of e t c ht h el o c a lw e a t h e rr e p o r t , # + t a k i n gt h eu s e r ' sz i pc o d ea sa na r g u m e n t .

See also Example A-30 and Example A-31. lynx The lynx Web and file browser can be used inside a script (with the d u m poption) to retrieve a file from a Web or ftp site noninteractively.
l y n xd u m ph t t p : / / w w w . x y z 2 3 . c o m / f i l e 0 1 . h t m l> $ S A V E F I L E

With the t r a v e r s a loption, lynx starts at the HTTP URL specified as an argument, then "crawls" through all links located on that particular server. Used together with the c r a w loption, outputs page text to a log file. rlogin
R e m o t el o g i n , initates a session on a remote host.

This command has security issues, so use ssh instead.

rsh
R e m o t es h e l l , executes command(s) on a remote host.

This has security issues, so use ssh instead.

rcp
R e m o t ec o p y , copies files between two

different networked machines.

rsync
R e m o t es y n c h r o n i z e , updates (synchronizes) files between two

different networked machines.

b a s h $r s y n ca~ / s o u r c e d i r / * t x t/ n o d e 1 / s u b d i r e c t o r y /

Example 16-43. Updating FC4


# ! / b i n / b a s h #f c 4 u p d . s h #S c r i p ta u t h o r :F r a n kW a n g . #S l i g h ts t y l i s t i cm o d i f i c a t i o n sb yA B SG u i d ea u t h o r . #U s e di nA B SG u i d ew i t hp e r m i s s i o n .

# D o w n l o a dF e d o r aC o r e4u p d a t ef r o mm i r r o rs i t eu s i n gr s y n c . # S h o u l da l s ow o r kf o rn e w e rF e d o r aC o r e s-5 ,6 ,... # O n l yd o w n l o a dl a t e s tp a c k a g ei fm u l t i p l ev e r s i o n se x i s t , # +t os a v es p a c e . U R L = r s y n c : / / d i s t r o . i b i b l i o . o r g / f e d o r a l i n u x c o r e / u p d a t e s / #U R L = r s y n c : / / f t p . k d d i l a b s . j p / f e d o r a / c o r e / u p d a t e s / #U R L = r s y n c : / / r s y n c . p l a n e t m i r r o r . c o m / f e d o r a l i n u x c o r e / u p d a t e s / D E S T = $ { 1 : / v a r / w w w / h t m l / f e d o r a / u p d a t e s / } L O G = / t m p / r e p o u p d a t e $ ( / b i n / d a t e+ % Y % m % d ) . t x t P I D _ F I L E = / v a r / r u n / $ { 0 # # * / } . p i d E _ R E T U R N = 8 5 #S o m e t h i n gu n e x p e c t e dh a p p e n e d .

#G e n e r a lr s y n co p t i o n s #r :r e c u r s i v ed o w n l o a d #t :r e s e r v et i m e #v :v e r b o s e O P T S = " r t vd e l e t e e x c l u d e dd e l e t e a f t e rp a r t i a l " #r s y n ci n c l u d ep a t t e r n #L e a d i n gs l a s hc a u s e sa b s o l u t ep a t hn a m em a t c h . I N C L U D E = ( " / 4 / i 3 8 6 / k d e i 1 8 n C h i n e s e * " # ^ ^ #Q u o t i n gi sn e c e s s a r yt op r e v e n tg l o b b i n g . )

#r s y n ce x c l u d ep a t t e r n #T e m p o r a r i l yc o m m e n to u tu n w a n t e dp k g su s i n g" # "... E X C L U D E = ( / 1 / 2 / 3 / t e s t i n g / 4 / S R P M S / 4 / p p c / 4 / x 8 6 _ 6 4 / 4 / i 3 8 6 / d e b u g " / 4 / i 3 8 6 / k d e i 1 8 n * " " / 4 / i 3 8 6 / o p e n o f f i c e . o r g l a n g p a c k * " " / 4 / i 3 8 6 / * i 5 8 6 . r p m " " / 4 / i 3 8 6 / G F S * " " / 4 / i 3 8 6 / c m a n * " " / 4 / i 3 8 6 / d l m * " " / 4 / i 3 8 6 / g n b d * " " / 4 / i 3 8 6 / k e r n e l s m p * " # " / 4 / i 3 8 6 / k e r n e l x e n * " # " / 4 / i 3 8 6 / x e n * " )

i n i t( ){ #L e tp i p ec o m m a n dr e t u r np o s s i b l er s y n ce r r o r ,e . g . ,s t a l l e dn e t w o r k . s e top i p e f a i l #N e w l yi n t r o d u c e di nB a s h ,v e r s i o n3 . T M P = $ { T M P D I R : / t m p } / $ { 0 # # * / } . $ $ #S t o r er e f i n e dd o w n l o a dl i s t . t r a p" { r mf$ T M P2 > / d e v / n u l l } "E X I T #C l e a rt e m p o r a r yf i l eo ne x i t . }

c h e c k _ p i d( ){ #C h e c ki fp r o c e s se x i s t s . i f[s" $ P I D _ F I L E "] ;t h e n e c h o" P I Df i l ee x i s t s .C h e c k i n g. . . " P I D = $ ( / b i n / e g r e po" ^ [ [ : d i g i t : ] ] + "$ P I D _ F I L E ) i f/ b i n / p sp i d$ P I D& > / d e v / n u l l ;t h e n e c h o" P r o c e s s$ P I Df o u n d .$ { 0 # # * / }s e e m st ob er u n n i n g ! " / u s r / b i n / l o g g e rt$ { 0 # # * / }\ " P r o c e s s$ P I Df o u n d .$ { 0 # # * / }s e e m st ob er u n n i n g ! " e x i t$ E _ R E T U R N f i e c h o" P r o c e s s$ P I Dn o tf o u n d .S t a r tn e wp r o c e s s... " f i }

# S e to v e r a l lf i l eu p d a t er a n g es t a r t i n gf r o mr o o to r$ U R L , # +a c c o r d i n gt oa b o v ep a t t e r n s . s e t _ r a n g e( ){ i n c l u d e = e x c l u d e = f o rpi n" $ { I N C L U D E [ @ ] } " ;d o i n c l u d e = " $ i n c l u d ei n c l u d e\ " $ p \ " " d o n e f o rpi n" $ { E X C L U D E [ @ ] } " ;d o e x c l u d e = " $ e x c l u d ee x c l u d e\ " $ p \ " " d o n e }

#R e t r i e v ea n dr e f i n er s y n cu p d a t el i s t . g e t _ l i s t( ){ e c h o$ $>$ P I D _ F I L E| |{ e c h o" C a n ' tw r i t et op i df i l e$ P I D _ F I L E " e x i t$ E _ R E T U R N } e c h on" R e t r i e v i n ga n dr e f i n i n gu p d a t el i s t... " #R e t r i e v el i s t-' e v a l 'i sn e e d e dt or u nr s y n ca sas i n g l ec o m m a n d . #$ 3a n d$ 4i st h ed a t ea n dt i m eo ff i l ec r e a t i o n . #$ 5i st h ef u l lp a c k a g en a m e . p r e v i o u s = p r e _ f i l e = p r e _ d a t e = 0 e v a l/ b i n / n i c e/ u s r / b i n / r s y n c\ r$ i n c l u d e$ e x c l u d e$ U R L|\ e g r e p' ^ d r . x | ^ r '|\ a w k' { p r i n t$ 3 ,$ 4 ,$ 5 } '|\ s o r tk 3|\ {w h i l er e a dl i n e ;d o #G e ts e c o n d ss i n c ee p o c h ,t of i l t e ro u to b s o l e t ep k g s . c u r _ d a t e = $ ( d a t ed" $ ( e c h o$ l i n e|a w k' { p r i n t$ 1 ,$ 2 } ' ) "+ % s ) # e c h o$ c u r _ d a t e #G e tf i l en a m e . c u r _ f i l e = $ ( e c h o$ l i n e|a w k' { p r i n t$ 3 } ' ) # e c h o$ c u r _ f i l e #G e tr p mp k gn a m ef r o mf i l en a m e ,i fp o s s i b l e . i f[ [$ c u r _ f i l e= =* r p m] ] ;t h e n p k g _ n a m e = $ ( e c h o$ c u r _ f i l e|s e dre\ ' s / ( ^ ( [ ^ _ ] + [ _ ] ) + ) [ [ : d i g i t : ] ] + \ . . * [ _ ] . * $ / \ 1 / ' ) e l s e p k g _ n a m e = f i #e c h o$ p k g _ n a m e i f[z" $ p k g _ n a m e "] ;t h e n # I fn o tar p mf i l e , e c h o$ c u r _ f i l e> >$ T M P # +t h e na p p e n dt od o w n l o a dl i s t . e l i f[" $ p k g _ n a m e "! =" $ p r e v i o u s "] ;t h e n #An e wp k gf o u n d . e c h o$ p r e _ f i l e> >$ T M P #O u t p u tl a t e s tf i l e . p r e v i o u s = $ p k g _ n a m e #S a v ec u r r e n t . p r e _ d a t e = $ c u r _ d a t e p r e _ f i l e = $ c u r _ f i l e e l i f[" $ c u r _ d a t e "g t" $ p r e _ d a t e "] ;t h e n # I fs a m ep k g ,b u tn e w e r , p r e _ d a t e = $ c u r _ d a t e # +t h e nu p d a t el a t e s tp o i n t e r . p r e _ f i l e = $ c u r _ f i l e f i d o n e e c h o$ p r e _ f i l e> >$ T M P # T M Pc o n t a i n sA L L # +o fr e f i n e dl i s tn o w . #e c h o" s u b s h e l l = $ B A S H _ S U B S H E L L "

#B r a c k e tr e q u i r e dh e r et ol e tf i n a l" e c h o$ p r e _ f i l e> >$ T M P " #R e m a i n e di nt h es a m es u b s h e l l(1)w i t ht h ee n t i r el o o p .

R E T = $ ? #G e tr e t u r nc o d eo ft h ep i p ec o m m a n d . [" $ R E T "n e0]& &{ e c h o" L i s tr e t r i e v i n gf a i l e dw i t hc o d e$ R E T " e x i t$ E _ R E T U R N } e c h o" d o n e " ;e c h o } #R e a lr s y n cd o w n l o a dp a r t . g e t _ f i l e( ){ e c h o" D o w n l o a d i n g . . . " / b i n / n i c e/ u s r / b i n / r s y n c\ $ O P T S\ f i l t e r" m e r g e , + /$ T M P "\ e x c l u d e' * ' \ $ U R L$ D E S T \ |/ u s r / b i n / t e e$ L O G R E T = $ ? # f i l t e rm e r g e , + /i sc r u c i a lf o rt h ei n t e n t i o n . # +m o d i f i e rm e a n si n c l u d ea n d/m e a n sa b s o l u t ep a t h . # T h e ns o r t e dl i s ti n$ T M Pw i l lc o n t a i na s c e n d i n gd i rn a m ea n d # +p r e v e n tt h ef o l l o w i n ge x c l u d e' * 'f r o m" s h o r t c u t t i n gt h ec i r c u i t . " e c h o" D o n e " r mf$ P I D _ F I L E2 > / d e v / n u l l r e t u r n$ R E T } ##M a i n i n i t c h e c k _ p i d s e t _ r a n g e g e t _ l i s t g e t _ f i l e R E T = $ ? #i f[" $ R E T "e q0] ;t h e n / u s r / b i n / l o g g e rt$ { 0 # # * / }" F e d o r au p d a t em i r r o r e ds u c c e s s f u l l y . " e l s e / u s r / b i n / l o g g e rt$ { 0 # # * / }\ " F e d o r au p d a t em i r r o r e dw i t hf a i l u r ec o d e :$ R E T " f i e x i t$ R E T

See also Example A-32. Using rcp, rsync, and similar utilities with security implications in a shell script may not be advisable. Consider, instead, using ssh, scp, or an expect script. ssh
S e c u r es h e l l , logs onto

a remote host and executes commands there. This secure replacement for telnet, rlogin, rcp, and rsh uses identity authentication and encryption. See its manpage for details.

Example 16-44. Using ssh


# ! / b i n / b a s h #r e m o t e . b a s h :U s i n gs s h . #T h i se x a m p l eb yM i c h a e lZ i c k . #U s e dw i t hp e r m i s s i o n .

# # # # # # # # +

P r e s u m p t i o n s : f d 2i s n ' tb e i n gc a p t u r e d(' 2 > / d e v / n u l l ') . s s h / s s h dp r e s u m e ss t d e r r( ' 2 ' )w i l ld i s p l a yt ou s e r . s s h di sr u n n i n go ny o u rm a c h i n e . F o ra n y' s t a n d a r d 'd i s t r i b u t i o n ,i tp r o b a b l yi s , a n dw i t h o u ta n yf u n k ys s h k e y g e nh a v i n gb e e nd o n e .

#T r ys s ht oy o u rm a c h i n ef r o mt h ec o m m a n d l i n e : # #$s s h$ H O S T N A M E #W i t h o u te x t r as e t u py o u ' l lb ea s k e df o ry o u rp a s s w o r d . # e n t e rp a s s w o r d # w h e nd o n e , $e x i t # #D i dt h a tw o r k ?I fs o ,y o u ' r er e a d yf o rm o r ef u n . #T r ys s ht oy o u rm a c h i n ea s' r o o t ' : # # $ s s hlr o o t$ H O S T N A M E # W h e na s k e df o rp a s s w o r d ,e n t e rr o o t ' s ,n o ty o u r s . # L a s tl o g i n :T u eA u g1 02 0 : 2 5 : 4 92 0 0 4f r o ml o c a l h o s t . l o c a l d o m a i n # E n t e r' e x i t 'w h e nd o n e . # T h ea b o v eg i v e sy o ua ni n t e r a c t i v es h e l l . # I ti sp o s s i b l ef o rs s h dt ob es e tu pi na' s i n g l ec o m m a n d 'm o d e , # +b u tt h a ti sb e y o n dt h es c o p eo ft h i se x a m p l e . # T h eo n l yt h i n gt on o t ei st h a tt h ef o l l o w i n gw i l lw o r ki n # +' s i n g l ec o m m a n d 'm o d e .

#Ab a s i c ,w r i t es t d o u t( l o c a l )c o m m a n d . l sl #N o wt h es a m eb a s i cc o m m a n do nar e m o t em a c h i n e . #P a s sad i f f e r e n t' U S E R N A M E '' H O S T N A M E 'i fd e s i r e d : U S E R = $ { U S E R N A M E : $ ( w h o a m i ) } H O S T = $ { H O S T N A M E : $ ( h o s t n a m e ) } # N o we x c u t et h ea b o v ec o m m a n d l i n eo nt h er e m o t eh o s t , # +w i t ha l lt r a n s m i s s i o n se n c r y p t e d . s s hl$ { U S E R }$ { H O S T }"l sl" # T h ee x p e c t e dr e s u l ti sal i s t i n go fy o u ru s e r n a m e ' sh o m e # +d i r e c t o r yo nt h er e m o t em a c h i n e . # T os e ea n yd i f f e r e n c e ,r u nt h i ss c r i p tf r o ms o m e w h e r e # +o t h e rt h a ny o u rh o m ed i r e c t o r y . # I no t h e rw o r d s ,t h eB a s hc o m m a n di sp a s s e da saq u o t e dl i n e # +t ot h er e m o t es h e l l ,w h i c he x e c u t e si to nt h er e m o t em a c h i n e . # I nt h i sc a s e ,s s h dd o e s 'b a s hc" l sl "' o ny o u rb e h a l f . # F o ri n f o r m a t i o no nt o p i c ss u c ha sn o th a v i n gt oe n t e ra # +p a s s w o r d / p a s s p h r a s ef o re v e r yc o m m a n d l i n e ,s e e # + m a ns s h # + m a ns s h k e y g e n # + m a ns s h d _ c o n f i g .

e x i t0

Within a loop, ssh may cause unexpected behavior. According to a Usenet post in the comp.unix shell archives, ssh inherits the loop's s t d i n . To remedy this, pass ssh either the nor foption. Thanks, Jason Bechtel, for pointing this out. scp
S e c u r ec o p y , similar in function to

rcp, copies files between two different networked machines, but does so using authentication, and with a security level similar to ssh. Local Network write This is a utility for terminal-to-terminal communication. It allows sending lines from your terminal (console or xterm) to that of another user. The mesg command may, of course, be used to disable write access to a terminal Since write is interactive, it would not normally find use in a script. netconfig A command-line utility for configuring a network adapter (using DHCP). This command is native to Red Hat centric Linux distros. Mail mail Send or read e-mail messages. This stripped-down command-line mail client works fine as a command embedded in a script. Example 16-45. A script that mails itself
# ! / b i n / s h #s e l f m a i l e r . s h :S e l f m a i l i n gs c r i p t a d r = $ { 1 : ` w h o a m i ` } #D e f a u l tt oc u r r e n tu s e r ,i fn o ts p e c i f i e d . # T y p i n g' s e l f m a i l e r . s hw i s e g u y @ s u p e r d u p e r g e n i u s . c o m ' # +s e n d st h i ss c r i p tt ot h a ta d d r e s s e e . # J u s t' s e l f m a i l e r . s h '( n oa r g u m e n t )s e n d st h es c r i p t # +t ot h ep e r s o ni n v o k i n gi t ,f o re x a m p l e ,b o z o @ l o c a l h o s t . l o c a l d o m a i n . # # F o rm o r eo nt h e$ { p a r a m e t e r : d e f a u l t }c o n s t r u c t , # +s e et h e" P a r a m e t e rS u b s t i t u t i o n "s e c t i o n # +o ft h e" V a r i a b l e sR e v i s i t e d "c h a p t e r . #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = c a t$ 0|m a i ls" S c r i p t\ " ` b a s e n a m e$ 0 ` \ "h a sm a i l e di t s e l ft oy o u . "" $ a d r " #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ## G r e e t i n g sf r o mt h es e l f m a i l i n gs c r i p t . # Am i s c h i e v o u sp e r s o nh a sr u nt h i ss c r i p t , # +w h i c hh a sc a u s e di tt om a i li t s e l ft oy o u . # A p p a r e n t l y ,s o m ep e o p l eh a v en o t h i n gb e t t e r # +t od ow i t ht h e i rt i m e . #e c h o" A t` d a t e ` ,s c r i p t\ " ` b a s e n a m e$ 0 ` \ "m a i l e dt o" $ a d r " . "

e x i t0 # N o t et h a tt h e" m a i l x "c o m m a n d( i n" s e n d "m o d e )m a yb es u b s t i t u t e d # +f o r" m a i l ". . .b u tw i t hs o m e w h a td i f f e r e n to p t i o n s .

mailto Similar to the mail command, mailto sends e-mail messages from the command-line or in a script. However, mailto also permits sending MIME (multimedia) messages. mailstats Show mail statistics. This command may be invoked only by root .
r o o t #m a i l s t a t s S t a t i s t i c sf r o mT u eJ a n 12 0 : 3 2 : 0 82 0 0 8 M m s g s f r b y t e s _ f r o m m s g s t o b y t e s _ t o m s g s r e jm s g s d i sm s g s q u r M a i l e r 4 1 6 8 2 2 4 1 1 8 K 0 0 K 0 0 0 e s m t p 9 2 1 2 6 4 0 K 1 8 9 4 2 5 1 3 1 K 0 0 0 l o c a l = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = T 1 8 9 4 2 4 7 5 8 K 1 8 9 4 2 5 1 3 1 K 0 0 0 C 4 1 4 0

vacation This utility automatically replies to e-mails that the intended recipient is on vacation and temporarily unavailable. It runs on a network, in conjunction with sendmail, and is not applicable to a dial-up POPmail account.

16.7. Terminal Control Commands


Command affecting the console or terminal tput Initialize terminal and/or fetch information about it from terminfo data. Various options permit certain terminal operations: tput clear is the equivalent of clear; tput reset is the equivalent of reset.
b a s h $t p u tl o n g n a m e x t e r mt e r m i n a le m u l a t o r( XW i n d o wS y s t e m )

Issuing a tput cup X Y moves the cursor to the (X,Y) coordinates in the current terminal. A clear to erase the terminal screen would normally precede this. Some interesting options to tput are:
b o l d , for high-intensity text s m u l , to s m s o , to s g r 0 , to

underline text in the terminal render text in reverse reset the terminal parameters (to normal), without clearing the screen

Example scripts using tput : 1. Example 36-13 2. Example 36-11

3. Example A-44 4. Example A-42 5. Example 27-2 Note that stty offers a more powerful command set for controlling a terminal. infocmp This command prints out extensive information about the current terminal. It references the terminfo database.
b a s h $i n f o c m p # R e c o n s t r u c t e dv i ai n f o c m pf r o mf i l e : / u s r / s h a r e / t e r m i n f o / r / r x v t r x v t | r x v tt e r m i n a le m u l a t o r( XW i n d o wS y s t e m ) , a m ,b c e ,e o ,k m ,m i r ,m s g r ,x e n l ,x o n , c o l o r s # 8 ,c o l s # 8 0 ,i t # 8 ,l i n e s # 2 4 ,p a i r s # 6 4 , a c s c = ` ` a a f f g g j j k k l l m m n n o o p p q q r r s s t t u u v v w w x x y y z z { { | | } } ~ ~ , b e l = ^ G ,b l i n k = \ E [ 5 m ,b o l d = \ E [ 1 m , c i v i s = \ E [ ? 2 5 l , c l e a r = \ E [ H \ E [ 2 J ,c n o r m = \ E [ ? 2 5 h ,c r = ^ M , . . .

reset Reset terminal parameters and clear text screen. As with clear, the cursor and prompt reappear in the upper lefthand corner of the terminal. clear The clear command simply clears the text screen at the console or in an xterm. The prompt and cursor reappear at the upper lefthand corner of the screen or xterm window. This command may be used either at the command line or in a script. See Example 11-25. resize Echoes commands necessary to set $ T E R Mand $ T E R M C A Pto duplicate the size (dimensions) of the current terminal.
b a s h $r e s i z e s e tn o g l o b ; s e t e n vC O L U M N S' 8 0 ' ; s e t e n vL I N E S' 2 4 ' ; u n s e tn o g l o b ;

script This utility records (saves to a file) all the user keystrokes at the command-line in a console or an xterm window. This, in effect, creates a record of a session.

16.8. Math Commands


"Doing the numbers" factor Decompose an integer into prime factors.

b a s h $f a c t o r2 7 4 1 7 2 7 4 1 7 :31 31 93 7

Example 16-46. Generating prime numbers


# ! / b i n / b a s h #p r i m e s 2 . s h # G e n e r a t i n gp r i m en u m b e r st h eq u i c k a n d e a s yw a y , # +w i t h o u tr e s o r t i n gt of a n c ya l g o r i t h m s . C E I L I N G = 1 0 0 0 0 P R I M E = 0 E _ N O T P R I M E = #1t o1 0 0 0 0

i s _ p r i m e( ) { l o c a lf a c t o r s f a c t o r s = ($ ( f a c t o r$ 1 )) #L o a do u t p u to f` f a c t o r `i n t oa r r a y . i f[z" $ { f a c t o r s [ 2 ] } "] # T h i r de l e m e n to f" f a c t o r s "a r r a y : # +$ { f a c t o r s [ 2 ] }i s2 n df a c t o ro fa r g u m e n t . # I fi ti sb l a n k ,t h e nt h e r ei sn o2 n df a c t o r , # +a n dt h ea r g u m e n ti st h e r e f o r ep r i m e . t h e n r e t u r n$ P R I M E #0 e l s e r e t u r n$ E _ N O T P R I M E #n u l l f i } e c h o f o rni n$ ( s e q$ C E I L I N G ) d o i fi s _ p r i m e$ n t h e n p r i n t f% 5 d$ n f i # ^ F i v ep o s i t i o n sp e rn u m b e rs u f f i c e s . d o n e # F o rah i g h e r$ C E I L I N G ,a d j u s tu p w a r d ,a sn e c e s s a r y . e c h o e x i t

bc Bash can't handle floating point calculations, and it lacks operators for certain important mathematical functions. Fortunately, bc gallops to the rescue. Not just a versatile, arbitrary precision calculation utility, bc offers many of the facilities of a programming language. It has a syntax vaguely resembling C. Since it is a fairly well-behaved UNIX utility, and may therefore be used in a pipe, bc comes in handy in scripts. Here is a simple template for using bc to calculate a script variable. This uses command substitution.
v a r i a b l e = $ ( e c h o" O P T I O N S ;O P E R A T I O N S "|b c )

Example 16-47. Monthly Payment on a Mortgage


# ! / b i n / b a s h #m o n t h l y p m t . s h :C a l c u l a t e sm o n t h l yp a y m e n to nam o r t g a g e .

# T h i si sam o d i f i c a t i o no fc o d ei nt h e # +" m c a l c "( m o r t g a g ec a l c u l a t o r )p a c k a g e , # +b yJ e f fS c h m i d t # +a n d # +M e n d e lC o o p e r( y o u r st r u l y ,t h eA B SG u i d ea u t h o r ) . # h t t p : / / w w w . i b i b l i o . o r g / p u b / L i n u x / a p p s / f i n a n c i a l / m c a l c 1 . 6 . t a r . g z e c h o e c h o" G i v e nt h ep r i n c i p a l ,i n t e r e s tr a t e ,a n dt e r mo fam o r t g a g e , " e c h o" c a l c u l a t et h em o n t h l yp a y m e n t . " b o t t o m = 1 . 0 e c h o e c h on" E n t e rp r i n c i p a l( n oc o m m a s )" r e a dp r i n c i p a l e c h on" E n t e ri n t e r e s tr a t e( p e r c e n t )" #I f1 2 % ,e n t e r" 1 2 " ,n o t" . 1 2 " . r e a di n t e r e s t _ r e c h on" E n t e rt e r m( m o n t h s )" r e a dt e r m

i n t e r e s t _ r = $ ( e c h o" s c a l e = 9 ;$ i n t e r e s t _ r / 1 0 0 . 0 "|b c )#C o n v e r tt od e c i m a l . # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ D i v i d eb y1 0 0 . #" s c a l e "d e t e r m i n e sh o wm a n yd e c i m a lp l a c e s . i n t e r e s t _ r a t e = $ ( e c h o" s c a l e = 9 ;$ i n t e r e s t _ r / 1 2+1 . 0 "|b c )

t o p = $ ( e c h o" s c a l e = 9 ;$ p r i n c i p a l * $ i n t e r e s t _ r a t e ^ $ t e r m "|b c ) # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # S t a n d a r df o r m u l af o rf i g u r i n gi n t e r e s t . e c h o ;e c h o" P l e a s eb ep a t i e n t .T h i sm a yt a k eaw h i l e . " l e t" m o n t h s=$ t e r m-1 " #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = f o r( ( x = $ m o n t h s ;x>0 ;x ) ) d o b o t = $ ( e c h o" s c a l e = 9 ;$ i n t e r e s t _ r a t e ^ $ x "|b c ) b o t t o m = $ ( e c h o" s c a l e = 9 ;$ b o t t o m + $ b o t "|b c ) # b o t t o m=$ ( ( $ b o t t o m+$ b o t " ) ) d o n e #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ## R i c kB o i v i ep o i n t e do u tam o r ee f f i c i e n ti m p l e m e n t a t i o n # +o ft h ea b o v el o o p ,w h i c hd e c r e a s e sc o m p u t a t i o nt i m eb y2 / 3 . #f o r( ( x = 1 ;x< =$ m o n t h s ;x + + ) ) #d o # b o t t o m = $ ( e c h o" s c a l e = 9 ;$ b o t t o m*$ i n t e r e s t _ r a t e+1 "|b c ) #d o n e

# A n dt h e nh ec a m eu pw i t ha ne v e nm o r ee f f i c i e n ta l t e r n a t i v e , # +o n et h a tc u t sd o w nt h er u nt i m eb ya b o u t9 5 % ! #b o t t o m = ` { # e c h o" s c a l e = 9 ;b o t t o m = $ b o t t o m ;i n t e r e s t _ r a t e = $ i n t e r e s t _ r a t e " # f o r( ( x = 1 ;x< =$ m o n t h s ;x + + ) ) # d o # e c h o' b o t t o m=b o t t o m*i n t e r e s t _ r a t e+1 ' # d o n e # e c h o' b o t t o m ' # }|b c ` #E m b e d sa' f o rl o o p 'w i t h i nc o m m a n ds u b s t i t u t i o n . ## O nt h eo t h e rh a n d ,F r a n kW a n gs u g g e s t s :

# b o t t o m = $ ( e c h o" s c a l e = 9 ;( $ i n t e r e s t _ r a t e ^ $ t e r m 1 ) / ( $ i n t e r e s t _ r a t e 1 ) "|b c ) # B e c a u s e... # T h ea l g o r i t h mb e h i n dt h el o o p # +i sa c t u a l l yas u mo fg e o m e t r i cp r o p o r t i o ns e r i e s . # T h es u mf o r m u l ai se 0 ( 1 q ^ n ) / ( 1 q ) , # +w h e r ee 0i st h ef i r s te l e m e n ta n dq = e ( n + 1 ) / e ( n ) # +a n dni st h en u m b e ro fe l e m e n t s . #-

#l e t" p a y m e n t=$ t o p / $ b o t t o m " p a y m e n t = $ ( e c h o" s c a l e = 2 ;$ t o p / $ b o t t o m "|b c ) #U s et w od e c i m a lp l a c e sf o rd o l l a r sa n dc e n t s . e c h o e c h o" m o n t h l yp a y m e n t=\ $ $ p a y m e n t " #E c h oad o l l a rs i g ni nf r o n to fa m o u n t . e c h o

e x i t0

#E x e r c i s e s : # 1 )F i l t e ri n p u tt op e r m i tc o m m a si np r i n c i p a la m o u n t . # 2 )F i l t e ri n p u tt op e r m i ti n t e r e s tt ob ee n t e r e da sp e r c e n to rd e c i m a l . # 3 )I fy o ua r er e a l l ya m b i t i o u s , # + e x p a n dt h i ss c r i p tt op r i n tc o m p l e t ea m o r t i z a t i o nt a b l e s .

Example 16-48. Base Conversion


# ! / b i n / b a s h # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #S h e l l s c r i p t : b a s e . s h-p r i n tn u m b e rt od i f f e r e n tb a s e s( B o u r n eS h e l l ) #A u t h o r : H e i n e rS t e v e n( h e i n e r . s t e v e n @ o d n . d e ) #D a t e : 0 7 0 3 9 5 #C a t e g o r y : D e s k t o p #$ I d :b a s e . s h , v1 . 22 0 0 0 / 0 2 / 0 61 9 : 5 5 : 3 5h e i n e rE x p$ #= = >A b o v el i n ei sR C SI Di n f o . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #D e s c r i p t i o n # #C h a n g e s #2 1 0 3 9 5s t v f i x e de r r o ro c c u r i n gw i t h0 x ba si n p u t( 0 . 2 ) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #= = >U s e di nA B SG u i d ew i t ht h es c r i p ta u t h o r ' sp e r m i s s i o n . #= = >C o m m e n t sa d d e db yA B SG u i d ea u t h o r . N O A R G S = 8 5 P N = ` b a s e n a m e" $ 0 " ` #P r o g r a mn a m e V E R = ` e c h o' $ R e v i s i o n :1 . 2$ '|c u td ''f 2 ` #= = >V E R = 1 . 2 U s a g e( ){ e c h o" $ P N-p r i n tn u m b e rt od i f f e r e n tb a s e s ,$ V E R( s t v' 9 5 ) u s a g e :$ P N[ n u m b e r. . . ] I fn on u m b e ri sg i v e n ,t h en u m b e r sa r er e a df r o ms t a n d a r di n p u t . An u m b e rm a yb e b i n a r y( b a s e2 ) s t a r t i n gw i t h0 b( i . e .0 b 1 1 0 0 ) o c t a l( b a s e8 ) s t a r t i n gw i t h0 ( i . e .0 1 4 ) h e x a d e c i m a l( b a s e1 6 ) s t a r t i n gw i t h0 x( i . e .0 x c ) d e c i m a l o t h e r w i s e( i . e .1 2 ) "> & 2 e x i t$ N O A R G S } #= = >P r i n t su s a g em e s s a g e . M s g( ){ f o ri

#= = >i n[ l i s t ]m i s s i n g .W h y ?

d oe c h o" $ P N :$ i "> & 2 d o n e } F a t a l( ){M s g" $ @ " ;e x i t6 6 ;} P r i n t B a s e s( ){ #D e t e r m i n eb a s eo ft h en u m b e r f o ri #= = >i n[ l i s t ]m i s s i n g . . . d o #= = >s oo p e r a t e so nc o m m a n d l i n ea r g ( s ) . c a s e" $ i "i n 0 b * ) i b a s e = 2 ; ; #b i n a r y 0 x * | [ a f ] * | [ A F ] * ) i b a s e = 1 6 ; ; #h e x a d e c i m a l 0 * ) i b a s e = 8 ; ; #o c t a l [ 1 9 ] * ) i b a s e = 1 0 ; ; #d e c i m a l * ) M s g" i l l e g a ln u m b e r$ i-i g n o r e d " c o n t i n u e ; ; e s a c #R e m o v ep r e f i x ,c o n v e r th e xd i g i t st ou p p e r c a s e( b cn e e d st h i s ) . n u m b e r = ` e c h o" $ i "|s e de' s : ^ 0 [ b B x X ] : : '|t r' [ a f ] '' [ A F ] ' ` #= = >U s e s" : "a ss e ds e p a r a t o r ,r a t h e rt h a n" / " . #C o n v e r tn u m b e rt od e c i m a l d e c = ` e c h o" i b a s e = $ i b a s e ;$ n u m b e r "|b c ` #= = >' b c 'i sc a l c u l a t o ru t i l i t y . c a s e" $ d e c "i n [ 0 9 ] * ) ; ; #n u m b e ro k * ) c o n t i n u e ; ; #e r r o r :i g n o r e e s a c #P r i n ta l lc o n v e r s i o n si no n el i n e . #= = >' h e r ed o c u m e n t 'f e e d sc o m m a n dl i s tt o' b c ' . e c h o` b c< < ! o b a s e = 1 6 ;" h e x = " ;$ d e c o b a s e = 1 0 ;" d e c = " ;$ d e c o b a s e = 8 ; " o c t = " ;$ d e c o b a s e = 2 ; " b i n = " ;$ d e c ! `|s e de' s :: d o n e } w h i l e[$ #g t0] #= = > I sa" w h i l el o o p "r e a l l yn e c e s s a r yh e r e , #= = > +s i n c ea l lt h ec a s e se i t h e rb r e a ko u to ft h el o o p #= = > +o rt e r m i n a t et h es c r i p t . #= = >( A b o v ec o m m e n tb yP a u l oM a r c e lC o e l h oA r a g a o . ) d o c a s e" $ 1 "i n ) s h i f t ;b r e a k ; ; h ) U s a g e ; ; #= = >H e l pm e s s a g e . * ) U s a g e ; ; * ) b r e a k ; ; #F i r s tn u m b e r e s a c #= = >E r r o rc h e c k i n gf o ri l l e g a li n p u tm i g h tb ea p p r o p r i a t e . s h i f t d o n e i f[$ #g t0] t h e n P r i n t B a s e s" $ @ " e l s e w h i l er e a dl i n e d o P r i n t B a s e s$ l i n e d o n e f i : g '

#R e a df r o ms t d i n .

e x i t

An alternate method of invoking bc involves using a here document embedded within a command substitution block. This is especially appropriate when a script needs to pass a list of options and commands to bc.
v a r i a b l e = ` b c< <L I M I T _ S T R I N G o p t i o n s s t a t e m e n t s o p e r a t i o n s L I M I T _ S T R I N G ` . . . o r . . .

v a r i a b l e = $ ( b c< <L I M I T _ S T R I N G o p t i o n s s t a t e m e n t s o p e r a t i o n s L I M I T _ S T R I N G )

Example 16-49. Invoking bc using a here document


# ! / b i n / b a s h #I n v o k i n g' b c 'u s i n gc o m m a n ds u b s t i t u t i o n #i nc o m b i n a t i o nw i t ha' h e r ed o c u m e n t ' .

v a r 1 = ` b c< <E O F 1 8 . 3 3*1 9 . 7 8 E O F ` e c h o$ v a r 1 #3 6 2 . 5 6

# $ (. . .)n o t a t i o na l s ow o r k s . v 1 = 2 3 . 5 3 v 2 = 1 7 . 8 8 1 v 3 = 8 3 . 5 0 1 v 4 = 1 7 1 . 6 3 v a r 2 = $ ( b c< <E O F s c a l e=4 a=($ v 1+$ v 2) b=($ v 3*$ v 4) a*b+1 5 . 3 5 E O F ) e c h o$ v a r 2 #5 9 3 4 8 7 . 8 4 5 2

v a r 3 = $ ( b cl< <E O F s c a l e=9 s(1 . 7) E O F ) #R e t u r n st h es i n eo f1 . 7r a d i a n s . #T h e" l "o p t i o nc a l l st h e' b c 'm a t hl i b r a r y . e c h o$ v a r 3 #. 9 9 1 6 6 4 8 1 0

#N o w ,t r yi ti naf u n c t i o n . . . h y p o t e n u s e( ) #C a l c u l a t eh y p o t e n u s eo far i g h tt r i a n g l e . { #c=s q r t (a ^ 2+b ^ 2) h y p = $ ( b cl< <E O F s c a l e=9

s q r t($ 1*$ 1+$ 2*$ 2) E O F ) #C a n ' td i r e c t l yr e t u r nf l o a t i n gp o i n tv a l u e sf r o maB a s hf u n c t i o n . #B u t ,c a ne c h o a n d c a p t u r e : e c h o" $ h y p " } h y p = $ ( h y p o t e n u s e3 . 6 87 . 3 1 ) e c h o" h y p o t e n u s e=$ h y p " #8 . 1 8 4 0 3 9 3 4 4

e x i t0

Example 16-50. Calculating PI


# ! / b i n / b a s h #c a n n o n . s h :A p p r o x i m a t i n gP Ib yf i r i n gc a n n o n b a l l s . #A u t h o r :M e n d e lC o o p e r #L i c e n s e :P u b l i cD o m a i n #V e r s i o n2 . 2 ,r e l d a t e1 3 o c t 0 8 . #T h i si sav e r ys i m p l ei n s t a n c eo fa" M o n t eC a r l o "s i m u l a t i o n : # +am a t h e m a t i c a lm o d e lo far e a l l i f ee v e n t , # +u s i n gp s e u d o r a n d o mn u m b e r st oe m u l a t er a n d o mc h a n c e . # C o n s i d e rap e r f e c t l ys q u a r ep l o to fl a n d ,1 0 0 0 0u n i t so nas i d e . # T h i sl a n dh a sap e r f e c t l yc i r c u l a rl a k ei ni t sc e n t e r , # +w i t had i a m e t e ro f1 0 0 0 0u n i t s . # T h ep l o ti sa c t u a l l ym o s t l yw a t e r ,e x c e p tf o rl a n di nt h ef o u rc o r n e r s . # ( T h i n ko fi ta sas q u a r ew i t ha ni n s c r i b e dc i r c l e . ) # # W ew i l lf i r ei r o nc a n n o n b a l l sf r o ma no l d s t y l ec a n n o n # +a tt h es q u a r e . # A l lt h es h o t si m p a c ts o m e w h e r eo nt h es q u a r e , # +e i t h e ri nt h el a k eo ro nt h ed r yc o r n e r s . # S i n c et h el a k et a k e su pm o s to ft h ea r e a , # +m o s to ft h es h o t sw i l lS P L A S H !i n t ot h ew a t e r . # J u s taf e ws h o t sw i l lT H U D !i n t os o l i dg r o u n d # +i nt h ef o u rc o r n e r so ft h es q u a r e . # # I fw et a k ee n o u g hr a n d o m ,u n a i m e ds h o t sa tt h es q u a r e , # +T h e nt h er a t i oo fS P L A S H E St ot o t a ls h o t sw i l la p p r o x i m a t e # +t h ev a l u eo fP I / 4 . # # T h es i m p l i f i e de x p l a n a t i o ni st h a tt h ec a n n o ni sa c t u a l l y # +s h o o t i n go n l ya tt h eu p p e rr i g h t h a n dq u a d r a n to ft h es q u a r e , # +i . e . ,Q u a d r a n tIo ft h eC a r t e s i a nc o o r d i n a t ep l a n e . # # # T h e o r e t i c a l l y ,t h em o r es h o t st a k e n ,t h eb e t t e rt h ef i t . # H o w e v e r ,as h e l ls c r i p t ,a so p p o s e dt oac o m p i l e dl a n g u a g e # +w i t hf l o a t i n g p o i n tm a t hb u i l ti n ,r e q u i r e ss o m ec o m p r o m i s e s . # T h i sd e c r e a s e st h ea c c u r a c yo ft h es i m u l a t i o n .

D I M E N S I O N = 1 0 0 0 0 #L e n g t ho fe a c hs i d eo ft h ep l o t . #A l s os e t sc e i l i n gf o rr a n d o mi n t e g e r sg e n e r a t e d . M A X S H O T S = 1 0 0 0 #F i r et h i sm a n ys h o t s . #1 0 0 0 0o rm o r ew o u l db eb e t t e r ,b u tw o u l dt a k et o ol o n g . P M U L T I P L I E R = 4 . 0 #S c a l i n gf a c t o r . d e c l a r erM _ P I = 3 . 1 4 1 5 9 2 6 5 4 #A c t u a l9 p l a c ev a l u eo fP I ,f o rc o m p a r i s o np u r p o s e s . g e t _ r a n d o m( )

{ S E E D = $ ( h e a dn1/ d e v / u r a n d o m|o dN1|a w k' {p r i n t$ 2} ' ) R A N D O M = $ S E E D # F r o m" s e e d i n g r a n d o m . s h " # +e x a m p l es c r i p t . l e t" r n u m=$ R A N D O M%$ D I M E N S I O N " # R a n g el e s st h a n1 0 0 0 0 . e c h o$ r n u m } d i s t a n c e = #D e c l a r eg l o b a lv a r i a b l e . h y p o t e n u s e( ) #C a l c u l a t eh y p o t e n u s eo far i g h tt r i a n g l e . { #F r o m" a l t b c . s h "e x a m p l e . d i s t a n c e = $ ( b cl< <E O F s c a l e=0 s q r t($ 1*$ 1+$ 2*$ 2) E O F ) # S e t t i n g" s c a l e "t oz e r or o u n d sd o w nr e s u l tt oi n t e g e rv a l u e , # +an e c e s s a r yc o m p r o m i s ei nt h i ss c r i p t . # I td e c r e a s e st h ea c c u r a c yo ft h i ss i m u l a t i o n . }

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #m a i n ( ){ #" M a i n "c o d eb l o c k ,m i m i c k i n gaC l a n g u a g em a i n ( )f u n c t i o n . #I n i t i a l i z ev a r i a b l e s . s h o t s = 0 s p l a s h e s = 0 t h u d s = 0 P i = 0 e r r o r = 0 w h i l e[" $ s h o t s "l t " $ M A X S H O T S "] d o x C o o r d = $ ( g e t _ r a n d o m ) y C o o r d = $ ( g e t _ r a n d o m ) h y p o t e n u s e$ x C o o r d$ y C o o r d ( ( s h o t s + + ) ) p r i n t f" # % 4 d "$ s h o t s p r i n t f" X c=% 4 d "$ x C o o r d p r i n t f" Y c=% 4 d "$ y C o o r d p r i n t f" D i s t a n c e=% 5 d "$ d i s t a n c e #M a i nl o o p .

#G e tr a n d o mXa n dYc o o r d s . # H y p o t e n u s eo f # +r i g h t t r i a n g l e=d i s t a n c e .

# # + # + # +

D i s t a n c ef r o m c e n t e ro fl a k e -t h e" o r i g i n "c o o r d i n a t e( 0 , 0 ) .

i f[" $ d i s t a n c e "l e" $ D I M E N S I O N "] t h e n e c h on" S P L A S H ! " ( ( s p l a s h e s + + ) ) e l s e e c h on" T H U D ! " ( ( t h u d s + + ) ) f i P i = $ ( e c h o" s c a l e = 9 ;$ P M U L T I P L I E R * $ s p l a s h e s / $ s h o t s "|b c ) #M u l t i p l yr a t i ob y4 . 0 . e c h on" P I~$ P i " e c h o d o n e e c h o e c h o" A f t e r$ s h o t ss h o t s ,P Il o o k sl i k ea p p r o x i m a t e l y # T e n d st or u nab i th i g h ,

$ P i "

# +p o s s i b l yd u et or o u n d o f fe r r o ra n di m p e r f e c tr a n d o m n e s so f$ R A N D O M . # B u ts t i l lu s u a l l yw i t h i np l u s o r m i n u s5 %... # +ap r e t t yf a i rr o u g ha p p r o x i m a t i o n . e r r o r = $ ( e c h o" s c a l e = 9 ;$ P i-$ M _ P I "|b c ) p c t _ e r r o r = $ ( e c h o" s c a l e = 2 ;1 0 0 . 0*$ e r r o r/$ M _ P I "|b c ) e c h on" D e v i a t i o nf r o mm a t h e m a t i c a lv a l u eo fP I= $ e r r o r " e c h o"( $ p c t _ e r r o r %e r r o r ) " e c h o #E n do f" m a i n "c o d eb l o c k . #} #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = e x i t0 # O n em i g h tw e l lw o n d e rw h e t h e ras h e l ls c r i p ti sa p p r o p r i a t ef o r # +a na p p l i c a t i o na sc o m p l e xa n dc o m p u t a t i o n i n t e n s i v ea sas i m u l a t i o n . # # T h e r ea r ea tl e a s tt w oj u s t i f i c a t i o n s . # 1 )A sap r o o fo fc o n c e p t :t os h o wi tc a nb ed o n e . # 2 )T op r o t o t y p ea n dt e s tt h ea l g o r i t h m sb e f o r er e w r i t i n g # + i ti nac o m p i l e dh i g h l e v e ll a n g u a g e .

See also Example A-37. dc The dc (desk calculator) utility is stack-oriented and uses RPN (Reverse Polish Notation). Like bc, it has much of the power of a programming language. Similar to the procedure with bc, echo a command-string to dc.
e c h o" [ P r i n t i n gas t r i n g. . .] P "|d c #T h ePc o m m a n dp r i n t st h es t r i n gb e t w e e nt h ep r e c e d i n gb r a c k e t s . #A n dn o wf o rs o m es i m p l ea r i t h m e t i c . e c h o" 78*p "|d c #5 6 # P u s h e s7 ,t h e n8o n t ot h es t a c k , # +m u l t i p l i e s( " * "o p e r a t o r ) ,t h e np r i n t st h er e s u l t( " p "o p e r a t o r ) .

Most persons avoid dc, because of its non-intuitive input and rather cryptic operators. Yet, it has its uses. Example 16-51. Converting a decimal number to hexadecimal
# ! / b i n / b a s h #h e x c o n v e r t . s h :C o n v e r tad e c i m a ln u m b e rt oh e x a d e c i m a l . E _ N O A R G S = 8 5#C o m m a n d l i n ea r gm i s s i n g . B A S E = 1 6 #H e x a d e c i m a l . i f[z" $ 1 "] t h e n #N e e dac o m m a n d l i n ea r g u m e n t . e c h o" U s a g e :$ 0n u m b e r " e x i t$ E _ N O A R G S f i #E x e r c i s e :a d da r g u m e n tv a l i d i t yc h e c k i n g .

h e x c v t( ) { i f[z" $ 1 "] t h e n e c h o0 r e t u r n #" R e t u r n "0i fn oa r gp a s s e dt of u n c t i o n . f i e c h o" " $ 1 "" $ B A S E "op "|d c # o s e t sr a d i x( n u m e r i c a lb a s e )o fo u t p u t .

# p p r i n t st h et o po fs t a c k . #F o ro t h e ro p t i o n s :' m a nd c '. . . r e t u r n } h e x c v t" $ 1 " e x i t

Studying the info page for dc is a painful path to understanding its intricacies. There seems to be a small, select group of dc wizards who delight in showing off their mastery of this powerful, but arcane utility.
b a s h $e c h o" 1 6 i [ q ] s a [ l n 0 = a l n 1 0 0 % P l n 1 0 0 / s n l b x ] s b A 0 D 6 8 7 3 6 1 4 2 s n l b x q "|d c B a s h

d c< < <1 0 k 5 v 1 + 2 / p#1 . 6 1 8 0 3 3 9 8 8 7 # ^ ^ ^ F e e do p e r a t i o n st od cu s i n gaH e r eS t r i n g . # ^ ^ ^ P u s h e s1 0a n ds e t st h a ta st h ep r e c i s i o n( 1 0 k ) . # ^ ^ P u s h e s5a n dt a k e si t ss q u a r er o o t # ( 5 v ,v=s q u a r er o o t ) . # ^ ^ P u s h e s1a n da d d si tt ot h er u n n i n gt o t a l( 1 + ) . # ^ ^ P u s h e s2a n dd i v i d e st h er u n n i n gt o t a lb yt h a t( 2 / ) . # ^P o p sa n dp r i n t st h er e s u l t( p ) # T h er e s u l ti s 1 . 6 1 8 0 3 3 9 8 8 7. . . # . . .w h i c hh a p p e n st ob et h eP y t h a g o r e a nG o l d e nR a t i o ,t o1 0p l a c e s .

Example 16-52. Factoring


# ! / b i n / b a s h #f a c t r . s h :F a c t o ran u m b e r M I N = 2 #W i l ln o tw o r kf o rn u m b e rs m a l l e rt h a nt h i s . E _ N O A R G S = 8 5 E _ T O O S M A L L = 8 6 i f[z$ 1] t h e n e c h o" U s a g e :$ 0n u m b e r " e x i t$ E _ N O A R G S f i i f[" $ 1 "l t" $ M I N "] t h e n e c h o" N u m b e rt of a c t o rm u s tb e$ M I No rg r e a t e r . " e x i t$ E _ T O O S M A L L f i #E x e r c i s e :A d dt y p ec h e c k i n g( t or e j e c tn o n i n t e g e ra r g ) . e c h o" F a c t o r so f$ 1 : " #e c h o " $ 1 [ p ] s 2 [ l i p / d l i % 0 = 1 d v s r ] s 1 2 s i d 2 % 0 = 1 3 s i d v s r [ d l i % 0 = \ 1 l r l i 2 + d s i ! > . ] d s . x d 1 < 2 "|d c ## A b o v ec o d ew r i t t e nb yM i c h e lC h a r p e n t i e r< c h a r p o v @ c s . u n h . e d u > # ( a sao n e l i n e r ,h e r eb r o k e ni n t ot w ol i n e sf o rd i s p l a yp u r p o s e s ) . # U s e di nA B SG u i d ew i t hp e r m i s s i o n( t h a n k s ! ) . e x i t #$s hf a c t r . s h2 7 0 1 3 8 #2 #3 #1 1 #4 0 9 3

awk Yet another way of doing floating point math in a script is using awk's built-in math functions in a shell wrapper. Example 16-53. Calculating the hypotenuse of a triangle
# ! / b i n / b a s h #h y p o t e n u s e . s h :R e t u r n st h e" h y p o t e n u s e "o far i g h tt r i a n g l e . # ( s q u a r er o o to fs u mo fs q u a r e so ft h e" l e g s " ) A R G S = 2 E _ B A D A R G S = 8 5 #S c r i p tn e e d ss i d e so ft r i a n g l ep a s s e d . #W r o n gn u m b e ro fa r g u m e n t s .

i f[$ #n e" $ A R G S "]#T e s tn u m b e ro fa r g u m e n t st os c r i p t . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `s i d e _ 1s i d e _ 2 " e x i t$ E _ B A D A R G S f i

A W K S C R I P T = '{p r i n t f (" % 3 . 7 f \ n " ,s q r t ( $ 1 * $ 1+$ 2 * $ 2 ))}' # c o m m a n d ( s )/p a r a m e t e r sp a s s e dt oa w k

#N o w ,p i p et h ep a r a m e t e r st oa w k . e c h on" H y p o t e n u s eo f$ 1a n d$ 2=" e c h o$ 1$ 2|a w k" $ A W K S C R I P T " # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ #A ne c h o a n d p i p ei sa ne a s yw a yo fp a s s i n gs h e l lp a r a m e t e r st oa w k . e x i t #E x e r c i s e :R e w r i t et h i ss c r i p tu s i n g' b c 'r a t h e rt h a na w k . # W h i c hm e t h o di sm o r ei n t u i t i v e ?

16.9. Miscellaneous Commands


Command that fit in no special category jot, seq These utilities emit a sequence of integers, with a user-selectable increment. The default separator character between each integer is a newline, but this can be changed with the soption.
b a s h $s e q5 1 2 3 4 5

b a s h $s e qs:5 1 : 2 : 3 : 4 : 5

Both jot and seq come in handy in a for loop. Example 16-54. Using seq to generate loop arguments

# ! / b i n / b a s h #U s i n g" s e q " e c h o f o rai n` s e q8 0 ` #o r f o rai n$ (s e q8 0) #S a m ea s f o rai n12345. . .8 0 ( s a v e sm u c ht y p i n g ! ) . #M a ya l s ou s e' j o t '( i fp r e s e n to ns y s t e m ) . d o e c h on" $ a" d o n e #12345. . .8 0 #E x a m p l eo fu s i n gt h eo u t p u to fac o m m a n dt og e n e r a t e #t h e[ l i s t ]i na" f o r "l o o p . e c h o ;e c h o

C O U N T = 8 0 #Y e s ,' s e q 'a l s oa c c e p t sar e p l a c e a b l ep a r a m e t e r . f o rai n` s e q$ C O U N T ` #o r f o rai n$ (s e q$ C O U N T) d o e c h on" $ a" d o n e #12345. . .8 0 e c h o ;e c h o B E G I N = 7 5 E N D = 8 0 f o rai n` s e q$ B E G I N$ E N D ` # G i v i n g" s e q "t w oa r g u m e n t ss t a r t st h ec o u n ta tt h ef i r s to n e , # +a n dc o n t i n u e su n t i li tr e a c h e st h es e c o n d . d o e c h on" $ a" d o n e #7 57 67 77 87 98 0 e c h o ;e c h o B E G I N = 4 5 I N T E R V A L = 5 E N D = 8 0 f o rai n` s e q$ B E G I N$ I N T E R V A L$ E N D ` # G i v i n g" s e q "t h r e ea r g u m e n t ss t a r t st h ec o u n ta tt h ef i r s to n e , # +u s e st h es e c o n df o ras t e pi n t e r v a l , # +a n dc o n t i n u e su n t i li tr e a c h e st h et h i r d . d o e c h on" $ a" d o n e #4 55 05 56 06 57 07 58 0 e c h o ;e c h o e x i t0

A simpler example:
# C r e a t eas e to f1 0f i l e s , # +n a m e df i l e . 1 ,f i l e . 2...f i l e . 1 0 . C O U N T = 1 0 P R E F I X = f i l e f o rf i l e n a m ei n` s e q$ C O U N T ` d o t o u c h$ P R E F I X . $ f i l e n a m e # O r ,c a nd oo t h e ro p e r a t i o n s , # +s u c ha sr m ,g r e p ,e t c . d o n e

Example 16-55. Letter Count"


# ! / b i n / b a s h #l e t t e r c o u n t . s h :C o u n t i n gl e t t e ro c c u r r e n c e si nat e x tf i l e . #W r i t t e nb yS t e f a n oP a l m e r i . #U s e di nA B SG u i d ew i t hp e r m i s s i o n . #S l i g h t l ym o d i f i e db yd o c u m e n ta u t h o r . M I N A R G S = 2 E _ B A D A R G S = 6 5 F I L E = $ 1 l e tL E T T E R S = $ # 1 #S c r i p tr e q u i r e sa tl e a s tt w oa r g u m e n t s .

#H o wm a n yl e t t e r ss p e c i f i e d( a sc o m m a n d l i n ea r g s ) . #( S u b t r a c t1f r o mn u m b e ro fc o m m a n d l i n ea r g s . )

s h o w _ h e l p ( ) { e c h o e c h oU s a g e :` b a s e n a m e$ 0 `f i l el e t t e r s e c h oN o t e :` b a s e n a m e$ 0 `a r g u m e n t sa r ec a s es e n s i t i v e . e c h oE x a m p l e :` b a s e n a m e$ 0 `f o o b a r . t x tGnULiNUx . e c h o } #C h e c k sn u m b e ro fa r g u m e n t s . i f[$ #l t$ M I N A R G S] ;t h e n e c h o e c h o" N o te n o u g ha r g u m e n t s . " e c h o s h o w _ h e l p e x i t$ E _ B A D A R G S f i

#C h e c k si ff i l ee x i s t s . i f[!f$ F I L E] ;t h e n e c h o" F i l e\ " $ F I L E \ "d o e sn o te x i s t . " e x i t$ E _ B A D A R G S f i

#C o u n t sl e t t e ro c c u r r e n c e s. f o rni n` s e q$ L E T T E R S ` ;d o s h i f t i f[ [` e c h on" $ 1 "|w cc `e q1] ] ;t h e n # C h e c k sa r g . e c h o" $ 1 "\ >` c a t$ F I L E|t rc d " $ 1 "|w cc `# C o u n t i n g . e l s e e c h o" $ 1i sn o ta s i n g l ec h a r . " f i d o n e e x i t$ ? # T h i ss c r i p th a se x a c t l yt h es a m ef u n c t i o n a l i t ya sl e t t e r c o u n t 2 . s h , # +b u te x e c u t e sf a s t e r . # W h y ?

Somewhat more capable than seq, jot is a classic UNIX utility that is not normally included in a standard Linux distro. However, the source rpm is available for download from the MIT repository. Unlike seq, jot can generate a sequence of random numbers, using the roption.
b a s h $j o tr39 9 9 1 0 6 9 1 2 7 2

1 4 2 8

getopt The getopt command parses command-line options preceded by a dash. This external command corresponds to the getopts Bash builtin. Using getopt permits handling long options by means of the lflag, and this also allows parameter reshuffling. Example 16-56. Using getopt to parse command-line options
# ! / b i n / b a s h #U s i n gg e t o p t #T r yt h ef o l l o w i n gw h e ni n v o k i n gt h i ss c r i p t : # s he x 3 3 a . s ha # s he x 3 3 a . s ha b c # s he x 3 3 a . s habc # s he x 3 3 a . s hd # s he x 3 3 a . s hd X Y Z # s he x 3 3 a . s hdX Y Z # s he x 3 3 a . s ha b c d # s he x 3 3 a . s ha b c d Z # s he x 3 3 a . s hz # s he x 3 3 a . s ha #E x p l a i nt h er e s u l t so fe a c ho ft h ea b o v e . E _ O P T E R R = 6 5 i f[" $ # "e q0] t h e n #S c r i p tn e e d sa tl e a s to n ec o m m a n d l i n ea r g u m e n t . e c h o" U s a g e$ 0[ o p t i o n sa , b , c ] " e x i t$ E _ O P T E R R f i s e t-` g e t o p t" a b c d : "" $ @ " ` #S e t sp o s i t i o n a lp a r a m e t e r st oc o m m a n d l i n ea r g u m e n t s . #W h a th a p p e n si fy o uu s e" $ * "i n s t e a do f" $ @ " ? w h i l e[!z" $ 1 "] d o c a s e" $ 1 "i n a )e c h o" O p t i o n\ " a \ " " ; ; b )e c h o" O p t i o n\ " b \ " " ; ; c )e c h o" O p t i o n\ " c \ " " ; ; d )e c h o" O p t i o n\ " d \ "$ 2 " ; ; * )b r e a k ; ; e s a c s h i f t d o n e # I ti su s u a l l yb e t t e rt ou s et h e' g e t o p t s 'b u i l t i ni nas c r i p t . # S e e" e x 3 3 . s h . " e x i t0

As Peggy Russell points out: It is often necessary to include an eval to correctly process whitespace and quotes.
a r g s = $ ( g e t o p toa : b c : d-" $ @ " ) e v a ls e t-" $ a r g s "

See Example 10-5 for a simplified emulation of getopt.

run-parts The run-parts command [82] executes all the scripts in a target directory, sequentially in ASCII-sorted filename order. Of course, the scripts need to have execute permission. The cron daemon invokes run-parts to run the scripts in the / e t c / c r o n . *directories. yes In its default behavior the yes command feeds a continuous string of the character yfollowed by a line feed to s t d o u t . A control- C terminates the run. A different output string may be specified, as in y e sd i f f e r e n ts t r i n g , which would continually output d i f f e r e n ts t r i n gto s t d o u t . One might well ask the purpose of this. From the command-line or in a script, the output of yes can be redirected or piped into a program expecting user input. In effect, this becomes a sort of poor man's version of expect .
y e s|f s c k/ d e v / h d a 1runs fsck

non-interactively (careful!).

y e s|r mrd i r n a m ehas same effect as r mr fd i r n a m e(careful!).

Caution advised when piping yes to a potentially dangerous system command, such as fsck or fdisk. It might have unintended consequences. The yes command parses variables, or more accurately, it echoes parsed variables. For example:
b a s h $y e s$ B A S H _ V E R S I O N 3 . 1 . 1 7 ( 1 ) r e l e a s e 3 . 1 . 1 7 ( 1 ) r e l e a s e 3 . 1 . 1 7 ( 1 ) r e l e a s e 3 . 1 . 1 7 ( 1 ) r e l e a s e 3 . 1 . 1 7 ( 1 ) r e l e a s e ...

This particular "feature" may be used to create a very large ASCII file on the fly:
b a s h $y e s$ P A T H>h u g e _ f i l e . t x t C t l C

Hit C t l Cvery quickly, or you just might get more than you bargained for. . . . The yes command may be emulated in a very simple script function.
y e s( ) {#T r i v i a le m u l a t i o no f" y e s ". . . l o c a lD E F A U L T _ T E X T = " y " w h i l e[t r u e] #E n d l e s sl o o p . d o i f[z" $ 1 "] t h e n e c h o" $ D E F A U L T _ T E X T " e l s e #I fa r g u m e n t. . . e c h o" $ 1 " #. . .e x p a n da n de c h oi t . f i d o n e # T h eo n l yt h i n g sm i s s i n ga r et h e } # +h e l pa n dv e r s i o no p t i o n s .

banner Prints arguments as a large vertical banner to s t d o u t , using an ASCII character (default '#'). This may be redirected to a printer for hardcopy.

Note that banner has been dropped from many Linux distros, presumably because it is no longer considered useful. printenv Show all the environmental variables set for a particular user.
b a s h $p r i n t e n v|g r e pH O M E H O M E = / h o m e / b o z o

lp The lp and lpr commands send file(s) to the print queue, to be printed as hard copy. [83] These commands trace the origin of their names to the line printers of another era. [84]
b a s h $l pf i l e 1 . t x tor b a s hl p< f i l e 1 . t x t

It is often useful to pipe the formatted output from pr to lp.


b a s h $p ro p t i o n sf i l e 1 . t x t|l p

Formatting packages, such as groff and Ghostscript may send their output directly to lp.
b a s h $g r o f fT a s c i if i l e . t r|l p b a s h $g so p t i o n s|l pf i l e . p s

Related commands are lpq, for viewing the print queue, and lprm, for removing jobs from the print queue. tee [UNIX borrows an idea from the plumbing trade.] This is a redirection operator, but with a difference. Like the plumber's tee, it permits "siphoning off" to a file the output of a command or commands within a pipe, but without affecting the result. This is useful for printing an ongoing process to a file or paper, perhaps to keep track of it for debugging purposes.
( r e d i r e c t i o n ) | >t of i l e | = = = = = = = = = = = = = = = = = = = = = = = = = = | = = = = = = = = = = = = = = = = = = = = c o m m a n d>c o m m a n d>| t e e>c o m m a n d>>o u t p u to fp i p e = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

c a tl i s t f i l e *|s o r t|t e ec h e c k . f i l e|u n i q>r e s u l t . f i l e # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # T h ef i l e" c h e c k . f i l e "c o n t a i n st h ec o n c a t e n a t e ds o r t e d" l i s t f i l e s , " # +b e f o r et h ed u p l i c a t el i n e sa r er e m o v e db y' u n i q . '

mkfifo This obscure command creates a named pipe, a temporary first-in-first-out buffer for transferring data between processes. [85] Typically, one process writes to the FIFO, and the other reads from it. See Example A-14.
# ! / b i n / b a s h #T h i ss h o r ts c r i p tb yO m a i rE s h k e n a z i . #U s e di nA B SG u i d ew i t hp e r m i s s i o n( t h a n k s ! ) . m k f i f op i p e 1 m k f i f op i p e 2 #Y e s ,p i p e sc a nb eg i v e nn a m e s . #H e n c et h ed e s i g n a t i o n" n a m e dp i p e . "

( c u td ''f 1|t r" a z "" A Z " )> p i p e 2< p i p e 1& l sl|t rs''|c u td ''f 3 , 9 -|t e ep i p e 1| c u td ''f 2|p a s t e-p i p e 2 r mfp i p e 1 r mfp i p e 2 #N on e e dt ok i l lb a c k g r o u n dp r o c e s s e sw h e ns c r i p tt e r m i n a t e s( w h yn o t ? ) . e x i t$ ? N o w ,i n v o k et h es c r i p ta n de x p l a i nt h eo u t p u t : s hm k f i f o e x a m p l e . s h 4 8 3 0 . t a r . g z p i p e 1 B O Z O p i p e 2 B O Z O m k f i f o e x a m p l e . s h M i x e d . m s gB O Z O B O Z O

B O Z O

pathchk This command checks the validity of a filename. If the filename exceeds the maximum allowable length (255 characters) or one or more of the directories in its path is not searchable, then an error message results. Unfortunately, pathchk does not return a recognizable error code, and it is therefore pretty much useless in a script. Consider instead the file test operators. dd Though this somewhat obscure and much feared data duplicator command originated as a utility for exchanging data on magnetic tapes between UNIX minicomputers and IBM mainframes, it still has its uses. The dd command simply copies a file (or s t d i n / s t d o u t ), but with conversions. Possible conversions include ASCII/EBCDIC, [86] upper/lower case, swapping of byte pairs between input and output, and skipping and/or truncating the head or tail of the input file.
#C o n v e r t i n gaf i l et oa l lu p p e r c a s e : d di f = $ f i l e n a m ec o n v = u c a s e>$ f i l e n a m e . u p p e r c a s e # l c a s e #F o rl o w e rc a s ec o n v e r s i o n

Some basic options to dd are: if=INFILE INFILE is the source file. of=OUTFILE OUTFILE is the target file, the file that will have the data written to it. bs=BLOCKSIZE This is the size of each block of data being read and written, usually a power of 2. skip=BLOCKS How many blocks of data to skip in INFILE before starting to copy. This is useful when the INFILE has "garbage" or garbled data in its header or when it is desirable to copy only a portion of the INFILE. seek=BLOCKS How many blocks of data to skip in OUTFILE before starting to copy, leaving blank data at beginning of

OUTFILE. count=BLOCKS Copy only this many blocks of data, rather than the entire INFILE. conv=CONVERSION Type of conversion to be applied to INFILE data before copying operation. Ad dh e l plists all the options this powerful utility takes. Example 16-57. A script that copies itself
# ! / b i n / b a s h #s e l f c o p y . s h #T h i ss c r i p tc o p i e si t s e l f . f i l e _ s u b s c r i p t = c o p y d di f = $ 0o f = $ 0 . $ f i l e _ s u b s c r i p t2 > / d e v / n u l l #S u p p r e s sm e s s a g e sf r o md d : ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ e x i t$ ? # Ap r o g r a mw h o s eo n l yo u t p u ti si t so w ns o u r c ec o d e # +i sc a l l e da" q u i n e "p e rW i l l a r dQ u i n e . # D o e st h i ss c r i p tq u a l i f ya saq u i n e ?

Example 16-58. Exercising dd


# ! / b i n / b a s h #e x e r c i s i n g d d . s h #S c r i p tb yS t e p h a n eC h a z e l a s . #S o m e w h a tm o d i f i e db yA B SG u i d ea u t h o r . i n f i l e = $ 0 o u t f i l e = l o g . t x t n = 8 p = 1 1 #T h i ss c r i p t . #O u t p u tf i l el e f tb e h i n d .

d di f = $ i n f i l eo f = $ o u t f i l eb s = 1s k i p = $ ( ( n 1 ) )c o u n t = $ ( ( p n + 1 ) )2 >/ d e v / n u l l #E x t r a c t sc h a r a c t e r snt op( 8t o1 1 )f r o mt h i ss c r i p t( " b a s h " ) . #e c h on" h e l l ov e r t i c a lw o r l d "|d dc b s = 1c o n v = u n b l o c k2 >/ d e v / n u l l #E c h o e s" h e l l ov e r t i c a lw o r l d "v e r t i c a l l yd o w n w a r d . #W h y ?An e w l i n ef o l l o w se a c hc h a r a c t e rd de m i t s . e x i t$ ?

To demonstrate just how versatile dd is, let's use it to capture keystrokes. Example 16-59. Capturing Keystrokes
# ! / b i n / b a s h #d d k e y p r e s s . s h :C a p t u r ek e y s t r o k e sw i t h o u tn e e d i n gt op r e s sE N T E R .

k e y p r e s s e s = 4

#N u m b e ro fk e y p r e s s e st oc a p t u r e .

o l d _ t t y _ s e t t i n g = $ ( s t t yg )

#S a v eo l dt e r m i n a ls e t t i n g s .

e c h o" P r e s s$ k e y p r e s s e sk e y s . " s t t yi c a n o ne c h o

#D i s a b l ec a n o n i c a lm o d e . #D i s a b l el o c a le c h o . k e y s = $ ( d db s = 1c o u n t = $ k e y p r e s s e s2 >/ d e v / n u l l ) #' d d 'u s e ss t d i n ,i f" i f "( i n p u tf i l e )n o ts p e c i f i e d . s t t y" $ o l d _ t t y _ s e t t i n g " #R e s t o r eo l dt e r m i n a ls e t t i n g s .

e c h o" Y o up r e s s e dt h e\ " $ k e y s \ "k e y s . " #T h a n k s ,S t e p h a n eC h a z e l a s ,f o rs h o w i n gt h ew a y . e x i t0

The dd command can do random access on a data stream.


e c h on.|d db s = 1s e e k = 4o f = f i l ec o n v = n o t r u n c # T h e" c o n v = n o t r u n c "o p t i o nm e a n st h a tt h eo u t p u tf i l e # +w i l ln o tb et r u n c a t e d . #T h a n k s ,S . C .

The dd command can copy raw data and disk images to and from devices, such as floppies and tape drives (Example A-5). A common use is creating boot floppies.
d di f = k e r n e l i m a g eo f = / d e v / f d 0 H 1 4 4 0

Similarly, dd can copy the entire contents of a floppy, even one formatted with a "foreign" OS, to the hard drive as an image file.
d di f = / d e v / f d 0o f = / h o m e / b o z o / p r o j e c t s / f l o p p y . i m g

Likewise, dd can create bootable flash drives. d di f = i m a g e . i s oo f = / d e v / s d bSee Marlow's Bootable USB Keys site. Other applications of dd include initializing temporary swap files (Example 31-2) and ramdisks (Example 31-3). It can even do a low-level copy of an entire hard drive partition, although this is not necessarily recommended. People (with presumably nothing better to do with their time) are constantly thinking of interesting applications of dd. Example 16-60. Securely deleting a file
# ! / b i n / b a s h #b l o t o u t . s h :E r a s e" a l l "t r a c e so faf i l e . # T h i ss c r i p to v e r w r i t e sat a r g e tf i l ea l t e r n a t e l y # +w i t hr a n d o mb y t e s ,t h e nz e r o sb e f o r ef i n a l l yd e l e t i n gi t . # A f t e rt h a t ,e v e ne x a m i n i n gt h er a wd i s ks e c t o r sb yc o n v e n t i o n a lm e t h o d s # +w i l ln o tr e v e a lt h eo r i g i n a lf i l ed a t a . P A S S E S = 7 # N u m b e ro ff i l e s h r e d d i n gp a s s e s . # I n c r e a s i n gt h i ss l o w ss c r i p te x e c u t i o n , # +e s p e c i a l l yo nl a r g et a r g e tf i l e s . # I / Ow i t h/ d e v / u r a n d o mr e q u i r e su n i tb l o c ks i z e , # +o t h e r w i s ey o ug e tw e i r dr e s u l t s . # V a r i o u se r r o re x i tc o d e s .

B L O C K S I Z E = 1

E _ B A D A R G S = 7 0 E _ N O T _ F O U N D = 7 1 E _ C H A N G E D _ M I N D = 7 2

i f[z" $ 1 "] #N of i l e n a m es p e c i f i e d . t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ B A D A R G S f i f i l e = $ 1

i f[!e" $ f i l e "] t h e n e c h o" F i l e\ " $ f i l e \ "n o tf o u n d . " e x i t$ E _ N O T _ F O U N D f i e c h o ;e c h on" A r ey o ua b s o l u t e l ys u r ey o uw a n tt ob l o to u t\ " $ f i l e \ "( y / n ) ?" r e a da n s w e r c a s e" $ a n s w e r "i n [ n N ] )e c h o" C h a n g e dy o u rm i n d ,h u h ? " e x i t$ E _ C H A N G E D _ M I N D ; ; * ) e c h o" B l o t t i n go u tf i l e\ " $ f i l e \ " . " ; ; e s a c

f l e n g t h = $ ( l sl" $ f i l e "|a w k' { p r i n t$ 5 } ' ) #F i e l d5i sf i l el e n g t h . p a s s _ c o u n t = 1 c h m o du + w" $ f i l e " e c h o w h i l e[" $ p a s s _ c o u n t "l e" $ P A S S E S "] d o e c h o" P a s s# $ p a s s _ c o u n t " s y n c #F l u s hb u f f e r s . d di f = / d e v / u r a n d o mo f = $ f i l eb s = $ B L O C K S I Z Ec o u n t = $ f l e n g t h #F i l lw i t hr a n d o mb y t e s . s y n c #F l u s hb u f f e r sa g a i n . d di f = / d e v / z e r oo f = $ f i l eb s = $ B L O C K S I Z Ec o u n t = $ f l e n g t h #F i l lw i t hz e r o s . s y n c #F l u s hb u f f e r sy e ta g a i n . l e t" p a s s _ c o u n t+ =1 " e c h o d o n e #A l l o wo v e r w r i t i n g / d e l e t i n gt h ef i l e .

r mf$ f i l e s y n c

#F i n a l l y ,d e l e t es c r a m b l e da n ds h r e d d e df i l e . #F l u s hb u f f e r saf i n a lt i m e .

e c h o" F i l e\ " $ f i l e \ "b l o t t e do u ta n dd e l e t e d . " ;e c h o

e x i t0 # T h i si saf a i r l ys e c u r e ,i fi n e f f i c i e n ta n ds l o wm e t h o d # +o ft h o r o u g h l y" s h r e d d i n g "af i l e . # T h e" s h r e d "c o m m a n d ,p a r to ft h eG N U" f i l e u t i l s "p a c k a g e , # +d o e st h es a m et h i n g ,a l t h o u g hm o r ee f f i c i e n t l y . # T h ef i l ec a n n o tn o tb e" u n d e l e t e d "o rr e t r i e v e db yn o r m a lm e t h o d s . # H o w e v e r... # +t h i ss i m p l em e t h o dw o u l d* n o t *l i k e l yw i t h s t a n d # +s o p h i s t i c a t e df o r e n s i ca n a l y s i s . # T h i ss c r i p tm a yn o tp l a yw e l lw i t haj o u r n a l e df i l es y s t e m . # E x e r c i s e( d i f f i c u l t ) :F i xi ts oi td o e s .

# T o mV i e r ' s" w i p e "f i l e d e l e t i o np a c k a g ed o e sam u c hm o r et h o r o u g hj o b # +o ff i l es h r e d d i n gt h a nt h i ss i m p l es c r i p t . # h t t p : / / w w w . i b i b l i o . o r g / p u b / L i n u x / u t i l s / f i l e / w i p e 2 . 0 . 0 . t a r . b z 2 # F o ra ni n d e p t ha n a l y s i so nt h et o p i co ff i l ed e l e t i o na n ds e c u r i t y , # +s e eP e t e rG u t m a n n ' sp a p e r , # + " S e c u r eD e l e t i o no fD a t aF r o mM a g n e t i ca n dS o l i d S t a t eM e m o r y " . # h t t p : / / w w w . c s . a u c k l a n d . a c . n z / ~ p g u t 0 0 1 / p u b s / s e c u r e _ d e l . h t m l

See also the dd thread entry in the bibliography. od The od, or octal dump filter converts input (or files) to octal (base-8) or other bases. This is useful for viewing or processing binary data files or otherwise unreadable system device files, such as / d e v / u r a n d o m , and as a filter for binary data.
h e a dc 4/ d e v / u r a n d o m|o dN 4t u 4|s e dn e' 1 s / . */ / p ' #S a m p l eo u t p u t :1 3 2 4 7 2 5 7 1 9 ,3 9 1 8 1 6 6 4 5 0 ,2 9 8 9 2 3 1 4 2 0 ,e t c . #F r o mr n d . s he x a m p l es c r i p t ,b yS t p h a n eC h a z e l a s

See also Example 9-16 and Example A-36. hexdump Performs a hexadecimal, octal, decimal, or ASCII dump of a binary file. This command is the rough equivalent of od, above, but not nearly as useful. May be used to view the contents of a binary file, in combination with dd and less.
d di f = / b i n / l s|h e x d u m pC|l e s s #T h eCo p t i o nn i c e l yf o r m a t st h eo u t p u ti nt a b u l a rf o r m .

objdump Displays information about an object file or binary executable in either hexadecimal form or as a disassembled listing (with the doption).
b a s h $o b j d u m pd/ b i n / l s / b i n / l s : f i l ef o r m a te l f 3 2 i 3 8 6 D i s a s s e m b l yo fs e c t i o n. i n i t : 0 8 0 4 9 0 b c< . i n i t > : 8 0 4 9 0 b c : 5 5 8 0 4 9 0 b d : 8 9e 5 ...

p u s h m o v

% e b p % e s p , % e b p

mcookie This command generates a "magic cookie," a 128-bit (32-character) pseudorandom hexadecimal number, normally used as an authorization "signature" by the X server. This also available for use in a script as a "quick 'n dirty" random number.
r a n d o m 0 0 0 = $ ( m c o o k i e )

Of course, a script could use md5sum for the same purpose.


#G e n e r a t em d 5c h e c k s u mo nt h es c r i p ti t s e l f . r a n d o m 0 0 1 = ` m d 5 s u m$ 0|a w k' { p r i n t$ 1 } ' ` #U s e s' a w k 't os t r i po f ft h ef i l e n a m e .

The mcookie command gives yet another way to generate a "unique" filename. Example 16-61. Filename generator
# ! / b i n / b a s h #t e m p f i l e n a m e . s h : t e m pf i l e n a m eg e n e r a t o r B A S E _ S T R = ` m c o o k i e ` P O S = 1 1 #3 2 c h a r a c t e rm a g i cc o o k i e . #A r b i t r a r yp o s i t i o ni nm a g i cc o o k i es t r i n g .

L E N = 5 p r e f i x = t e m p

#G e t$ L E Nc o n s e c u t i v ec h a r a c t e r s . # T h i si s ,a f t e ra l l ,a" t e m p "f i l e . # F o rm o r e" u n i q u e n e s s , "g e n e r a t et h e # +f i l e n a m ep r e f i xu s i n gt h es a m em e t h o d # +a st h es u f f i x ,b e l o w .

s u f f i x = $ { B A S E _ S T R : P O S : L E N } # E x t r a c ta5 c h a r a c t e rs t r i n g , # +s t a r t i n ga tp o s i t i o n1 1 . t e m p _ f i l e n a m e = $ p r e f i x . $ s u f f i x #C o n s t r u c tt h ef i l e n a m e . e c h o" T e m pf i l e n a m e=" $ t e m p _ f i l e n a m e " " #s ht e m p f i l e n a m e . s h #T e m pf i l e n a m e=t e m p . e 1 9 e a # C o m p a r et h i sm e t h o do fg e n e r a t i n g" u n i q u e "f i l e n a m e s # +w i t ht h e' d a t e 'm e t h o di ne x 5 1 . s h . e x i t0

units This utility converts between different units of measure. While normally invoked in interactive mode, units may find use in a script. Example 16-62. Converting meters to miles
# ! / b i n / b a s h #u n i t c o n v e r s i o n . s h #M u s th a v e' u n i t s 'u t i l i t yi n s t a l l e d .

c o n v e r t _ u n i t s( ) #T a k e sa sa r g u m e n t st h eu n i t st oc o n v e r t . { c f = $ ( u n i t s" $ 1 "" $ 2 "|s e ds i l e n te' 1 p '|a w k' { p r i n t$ 2 } ' ) #S t r i po f fe v e r y t h i n ge x c e p tt h ea c t u a lc o n v e r s i o nf a c t o r . e c h o" $ c f " } U n i t 1 = m i l e s U n i t 2 = m e t e r s c f a c t o r = ` c o n v e r t _ u n i t s$ U n i t 1$ U n i t 2 ` q u a n t i t y = 3 . 7 3 r e s u l t = $ ( e c h o$ q u a n t i t y * $ c f a c t o r|b c ) e c h o" T h e r ea r e$ r e s u l t$ U n i t 2i n$ q u a n t i t y$ U n i t 1 . " # W h a th a p p e n si fy o up a s si n c o m p a t i b l eu n i t s , # +s u c ha s" a c r e s "a n d" m i l e s "t ot h ef u n c t i o n ? e x i t0 #E x e r c i s e :E d i tt h i ss c r i p tt oa c c e p tc o m m a n d l i n ep a r a m e t e r s , # w i t ha p p r o p r i a t ee r r o rc h e c k i n g ,o fc o u r s e .

m4 A hidden treasure, m4 is a powerful macro [87] processing filter, virtually a complete language. Although originally written as a pre-processor for RatFor, m4 turned out to be useful as a stand-alone utility. In fact, m4 combines some of the functionality of eval, tr, and awk, in addition to its extensive macro expansion facilities. The April, 2002 issue of Linux Journal has a very nice article on m4 and its uses.

Example 16-63. Using m4


# ! / b i n / b a s h #m 4 . s h :U s i n gt h em 4m a c r op r o c e s s o r #S t r i n g s s t r i n g = a b c d A 0 1 e c h o" l e n ( $ s t r i n g ) "|m 4 e c h o" s u b s t r ( $ s t r i n g , 4 ) "|m 4 e c h o" r e g e x p ( $ s t r i n g , [ 0 1 ] [ 0 1 ] , \ & Z ) "|m 4 #A r i t h m e t i c v a r = 9 9 e c h o" i n c r ( $ v a r ) "|m 4 e c h o" e v a l ( $ v a r/3 ) "|m 4 e x i t

# 7 #A 0 1 #0 1 Z

# 1 0 0 # 3 3

xmessage This X-based variant of echo pops up a message/query window on the desktop.
x m e s s a g eL e f tc l i c kt oc o n t i n u eb u t t o no k a y

zenity The zenity utility is adept at displaying GTK+ dialog widgets and very suitable for scripting purposes. doexec The doexec command enables passing an arbitrary list of arguments to a binary executable. In particular, passing a r g v [ 0 ](which corresponds to $0 in a script) lets the executable be invoked by various names, and it can then carry out different sets of actions, according to the name by which it was called. What this amounts to is roundabout way of passing options to an executable. For example, the / u s r / l o c a l / b i ndirectory might contain a binary called "aaa". Invoking doexec /usr/local/bin/aaa list would list all those files in the current working directory beginning with an "a", while invoking (the same executable with) doexec /usr/local/bin/aaa delete would delete those files. The various behaviors of the executable must be defined within the code of the executable itself, analogous to something like the following in a shell script:
c a s e` b a s e n a m e$ 0 `i n " n a m e 1 ")d o _ s o m e t h i n g ; ; " n a m e 2 ")d o _ s o m e t h i n g _ e l s e ; ; " n a m e 3 ")d o _ y e t _ a n o t h e r _ t h i n g ; ; * )b a i l _ o u t ; ; e s a c

dialog The dialog family of tools provide a method of calling interactive "dialog" boxes from a script. The more elaborate variations of dialog -- gdialog, Xdialog, and kdialog -- actually invoke X-Windows widgets. sox The sox, or "sound exchange" command plays and performs transformations on sound files. In fact, the / u s r / b i n / p l a yexecutable (now deprecated) is nothing but a shell wrapper for sox . For example, sox soundfile.wav soundfile.au changes a WAV sound file into a (Sun audio format) AU sound file. Shell scripts are ideally suited for batch-processing sox operations on sound files. For examples, see the Linux Radio Timeshift HOWTO and the MP3do Project.

Chapter 17. System and Administrative Commands


The startup and shutdown scripts in / e t c / r c . dillustrate the uses (and usefulness) of many of these comands. These are usually invoked by root and used for system maintenance or emergency filesystem repairs. Use with caution, as some of these commands may damage your system if misused. Users and Groups users Show all logged on users. This is the approximate equivalent of who -q. groups Lists the current user and the groups she belongs to. This corresponds to the $GROUPS internal variable, but gives the group names, rather than the numbers.
b a s h $g r o u p s b o z i t ac d r o mc d w r i t e ra u d i ox g r p b a s h $e c h o$ G R O U P S 5 0 1

chown, chgrp The chown command changes the ownership of a file or files. This command is a useful method that root can use to shift file ownership from one user to another. An ordinary user may not change the ownership of files, not even her own files. [88]
r o o t #c h o w nb o z o* . t x t

The chgrp command changes the g r o u pownership of a file or files. You must be owner of the file(s) as well as a member of the destination group (or root ) to use this operation.
c h g r pr e c u r s i v ed u n d e r h e a d s* . d a t a # T h e" d u n d e r h e a d s "g r o u pw i l ln o wo w na l lt h e" * . d a t a "f i l e s # +a l lt h ew a yd o w nt h e$ P W Dd i r e c t o r yt r e e( t h a t ' sw h a t" r e c u r s i v e "m e a n s ) .

useradd, userdel The useradd administrative command adds a user account to the system and creates a home directory for that particular user, if so specified. The corresponding userdel command removes a user account from the system [89] and deletes associated files. The adduser command is a synonym for useradd and is usually a symbolic link to it. usermod Modify a user account. Changes may be made to the password, group membership, expiration date, and other attributes of a given user's account. With this command, a user's password may be locked, which has the effect of disabling the account. groupmod Modify a given group. The group name and/or ID number may be changed using this command. id

The id command lists the real and effective user IDs and the group IDs of the user associated with the current process. This is the counterpart to the $UID, $EUID, and $GROUPS internal Bash variables.
b a s h $i d u i d = 5 0 1 ( b o z o )g i d = 5 0 1 ( b o z o )g r o u p s = 5 0 1 ( b o z o ) , 2 2 ( c d r o m ) , 8 0 ( c d w r i t e r ) , 8 1 ( a u d i o ) b a s h $e c h o$ U I D 5 0 1

The id command shows the effective IDs only when they differ from the real ones. Also see Example 9-5. lid The lid (list ID) command shows the group(s) that a given user belongs to, or alternately, the users belonging to a given group. May be invoked only by root.
r o o t #l i db o z o b o z o ( g i d = 5 0 0 )

r o o t #l i dd a e m o n b i n ( g i d = 1 ) d a e m o n ( g i d = 2 ) a d m ( g i d = 4 ) l p ( g i d = 7 )

who Show all users logged on to the system.


b a s h $w h o b o z o t t y 1 b o z o p t s / 0 b o z o p t s / 1 b o z o p t s / 2 A p r2 71 7 : 4 5 A p r2 71 7 : 4 6 A p r2 71 7 : 4 7 A p r2 71 7 : 4 9

The mgives detailed information about only the current user. Passing any two arguments to who is the equivalent of who -m, as in who am i or who The Man.
b a s h $w h om l o c a l h o s t . l o c a l d o m a i n ! b o z o p t s / 2 A p r2 71 7 : 4 9

whoami is similar to who -m, but only lists the user name.
b a s h $w h o a m i b o z o

w Show all logged on users and the processes belonging to them. This is an extended version of who. The output of w may be piped to grep to find a specific user and/or process.
b a s h $w|g r e ps t a r t x b o z o t t y 1 4 : 2 2 p m 6 : 4 1 4 . 4 7 s 0 . 4 5 s s t a r t x

logname

Show current user's login name (as found in / v a r / r u n / u t m p ). This is a near-equivalent to whoami, above.
b a s h $l o g n a m e b o z o b a s h $w h o a m i b o z o

However . . .
b a s h $s u P a s s w o r d :. . . . . . b a s h #w h o a m i r o o t b a s h #l o g n a m e b o z o

While logname prints the name of the logged in user, whoami gives the name of the user attached to the current process. As we have just seen, sometimes these are not the same. su Runs a program or script as a s ubstitute user. su rjones starts a shell as user rjones. A naked su defaults to root . See Example A-14. sudo Runs a command as root (or another user). This may be used in a script, thus permitting a regular user to run the script.
# ! / b i n / b a s h #S o m ec o m m a n d s . s u d oc p/ r o o t / s e c r e t f i l e/ h o m e / b o z o / s e c r e t #S o m em o r ec o m m a n d s .

The file / e t c / s u d o e r sholds the names of users permitted to invoke sudo. passwd Sets, changes, or manages a user's password. The passwd command can be used in a script, but probably should not be. Example 17-1. Setting a new password
# ! / b i n / b a s h # s e t n e w p a s s w o r d . s h :F o rd e m o n s t r a t i o np u r p o s e so n l y . # N o tag o o di d e at oa c t u a l l yr u nt h i ss c r i p t . # T h i ss c r i p tm u s tb er u na sr o o t . R O O T _ U I D = 0 E _ W R O N G _ U S E R = 6 5 E _ N O S U C H U S E R = 7 0 S U C C E S S = 0 #R o o th a s$ U I D0 . #N o tr o o t ?

i f[" $ U I D "n e" $ R O O T _ U I D "] t h e n e c h o ;e c h o" O n l yr o o tc a nr u nt h i ss c r i p t . " ;e c h o e x i t$ E _ W R O N G _ U S E R e l s e

e c h o e c h o" Y o us h o u l dk n o wb e t t e rt h a nt or u nt h i ss c r i p t ,r o o t . " e c h o" E v e nr o o tu s e r sg e tt h eb l u e s . . ." e c h o f i

u s e r n a m e = b o z o N E W P A S S W O R D = s e c u r i t y _ v i o l a t i o n #C h e c ki fb o z ol i v e sh e r e . g r e pq" $ u s e r n a m e "/ e t c / p a s s w d i f[$ ?n e$ S U C C E S S] t h e n e c h o" U s e r$ u s e r n a m ed o e sn o te x i s t . " e c h o" N op a s s w o r dc h a n g e d . " e x i t$ E _ N O S U C H U S E R f i e c h o" $ N E W P A S S W O R D "|p a s s w ds t d i n" $ u s e r n a m e " # T h e' s t d i n 'o p t i o nt o' p a s s w d 'p e r m i t s # +g e t t i n gan e wp a s s w o r df r o ms t d i n( o rap i p e ) . e c h o ;e c h o" U s e r$ u s e r n a m e ' sp a s s w o r dc h a n g e d ! " #U s i n gt h e' p a s s w d 'c o m m a n di nas c r i p ti sd a n g e r o u s . e x i t0

The passwd command's l ,u , and doptions permit locking, unlocking, and deleting a user's password. Only root may use these options. ac Show users' logged in time, as read from / v a r / l o g / w t m p . This is one of the GNU accounting utilities.
b a s h $a c t o t a l 6 8 . 0 8

last List last logged in users, as read from / v a r / l o g / w t m p . This command can also show remote logins. For example, to show the last few times the system rebooted:
b a s h $l a s tr e b o o t r e b o o t s y s t e mb o o t 2 . 6 . 9 1 . 6 6 7 r e b o o t s y s t e mb o o t 2 . 6 . 9 1 . 6 6 7 r e b o o t s y s t e mb o o t 2 . 6 . 9 1 . 6 6 7 r e b o o t s y s t e mb o o t 2 . 6 . 9 1 . 6 6 7 ... w t m pb e g i n sT u eF e b 11 2 : 5 0 : 0 92 0 0 5 F r iF e b 41 8 : 1 8 F r iF e b 41 5 : 2 0 F r iF e b 41 2 : 5 6 T h uF e b 32 1 : 0 8 ( 0 0 : 0 2 ) ( 0 1 : 2 7 ) ( 0 0 : 4 9 ) ( 0 2 : 1 7 )

newgrp Change user's group ID without logging out. This permits access to the new group's files. Since users may be members of multiple groups simultaneously, this command finds only limited use. Kurt Glaesemann points out that the newgrp command could prove helpful in setting the default group permissions for files a user writes. However, the chgrp command might be more convenient for this purpose. Terminals

tty Echoes the name (filename) of the current user's terminal. Note that each separate xterm window counts as a different terminal.
b a s h $t t y / d e v / p t s / 1

stty Shows and/or changes terminal settings. This complex command, used in a script, can control terminal behavior and the way output displays. See the info page, and study it carefully. Example 17-2. Setting an erase character
# ! / b i n / b a s h #e r a s e . s h :U s i n g" s t t y "t os e ta ne r a s ec h a r a c t e rw h e nr e a d i n gi n p u t . e c h on" W h a ti sy o u rn a m e ?" r e a dn a m e # T r yt ob a c k s p a c e # +t oe r a s ec h a r a c t e r so fi n p u t . # P r o b l e m s ? e c h o" Y o u rn a m ei s$ n a m e . " s t t ye r a s e' # ' # S e t" h a s h m a r k "( # )a se r a s ec h a r a c t e r . e c h on" W h a ti sy o u rn a m e ?" r e a dn a m e # U s e#t oe r a s el a s tc h a r a c t e rt y p e d . e c h o" Y o u rn a m ei s$ n a m e . " e x i t0 #E v e na f t e rt h es c r i p te x i t s ,t h en e wk e yv a l u er e m a i n ss e t . #E x e r c i s e :H o ww o u l dy o ur e s e tt h ee r a s ec h a r a c t e rt ot h ed e f a u l tv a l u e ?

Example 17-3. secret password: Turning off terminal echoing


# ! / b i n / b a s h #s e c r e t p w . s h :s e c r e tp a s s w o r d e c h o e c h on" E n t e rp a s s w o r d" r e a dp a s s w d e c h o" p a s s w o r di s$ p a s s w d " e c h on" I fs o m e o n eh a db e e nl o o k i n go v e ry o u rs h o u l d e r ," e c h o" y o u rp a s s w o r dw o u l dh a v eb e e nc o m p r o m i s e d . " e c h o& &e c h o #T w ol i n e f e e d si na n" a n dl i s t . "

s t t ye c h o

#T u r n so f fs c r e e ne c h o .

e c h on" E n t e rp a s s w o r da g a i n" r e a dp a s s w d e c h o e c h o" p a s s w o r di s$ p a s s w d " e c h o s t t ye c h o e x i t0 #D oa n' i n f os t t y 'f o rm o r eo nt h i su s e f u l b u t t r i c k yc o m m a n d . #R e s t o r e ss c r e e ne c h o .

A creative use of stty is detecting a user keypress (without hitting ENTER). Example 17-4. Keypress detection

# ! / b i n / b a s h #k e y p r e s s . s h :D e t e c tau s e rk e y p r e s s( " h o tk e y s " ) . e c h o o l d _ t t y _ s e t t i n g s = $ ( s t t yg ) s t t yi c a n o n K e y p r e s s = $ ( h e a dc 1 ) #S a v eo l ds e t t i n g s( w h y ? ) . #o r$ ( d db s = 1c o u n t = 12 >/ d e v / n u l l ) #o nn o n G N Us y s t e m s

e c h o e c h o" K e yp r e s s e dw a s\ " " $ K e y p r e s s " \ " . " e c h o s t t y" $ o l d _ t t y _ s e t t i n g s " #T h a n k s ,S t e p h a n eC h a z e l a s . e x i t0 #R e s t o r eo l ds e t t i n g s .

Also see Example 9-3 and Example A-43. terminals and modes Normally, a terminal works in the canonical mode. When a user hits a key, the resulting character does not immediately go to the program actually running in this terminal. A buffer local to the terminal stores keystrokes. When the user hits the ENTER key, this sends all the stored keystrokes to the program running. There is even a basic line editor inside the terminal.
b a s h $s t t ya s p e e d9 6 0 0b a u d ;r o w s3 6 ;c o l u m n s9 6 ;l i n e=0 ; i n t r=^ C ;q u i t=^ \ ;e r a s e=^ H ;k i l l=^ U ;e o f=^ D ;e o l=< u n d e f > ;e o l 2=< u n d e f > ; s t a r t=^ Q ;s t o p=^ S ;s u s p=^ Z ;r p r n t=^ R ;w e r a s e=^ W ;l n e x t=^ V ;f l u s h=^ O ; . . . i s i gi c a n o ni e x t e ne c h oe c h o ee c h o ke c h o n ln o f l s hx c a s et o s t o pe c h o p r t

Using canonical mode, it is possible to redefine the special keys for the local terminal line editor.
b a s h $c a t>f i l e x x x w h a < c t l W > I < c t l H > f o ob a r < c t l U > h e l l ow o r l d < E N T E R > < c t l D > b a s h $c a tf i l e x x x h e l l ow o r l d b a s h $w cc<f i l e x x x 1 2

The process controlling the terminal receives only 12 characters (11 alphabetic ones, plus a newline), although the user hit 26 keys. In non-canonical ("raw") mode, every key hit (including special editing keys such as ctl-H) sends a character immediately to the controlling process. The Bash prompt disables both i c a n o nand e c h o , since it replaces the basic terminal line editor with its own more elaborate one. For example, when you hit ctl-A at the Bash prompt, there's no ^A echoed by the terminal, but Bash gets a \1 character, interprets it, and moves the cursor to the begining of the line. Stphane Chazelas setterm Set certain terminal attributes. This command writes to its terminal's s t d o u ta string that changes the behavior of that

terminal.
b a s h $s e t t e r mc u r s o ro f f b a s h $

The setterm command can be used within a script to change the appearance of text written to s t d o u t , although there are certainly better tools available for this purpose.
s e t t e r mb o l do n e c h ob o l dh e l l o s e t t e r mb o l do f f e c h on o r m a lh e l l o

tset Show or initialize terminal settings. This is a less capable version of stty.
b a s h $t s e tr T e r m i n a lt y p ei sx t e r m x f r e e 8 6 . K i l li sc o n t r o l U( ^ U ) . I n t e r r u p ti sc o n t r o l C( ^ C ) .

setserial Set or display serial port parameters. This command must be run by root and is usually found in a system setup script.
#F r o m/ e t c / p c m c i a / s e r i a ls c r i p t : I R Q = ` s e t s e r i a l/ d e v / $ D E V I C E|s e de' s / . * I R Q :/ / ' ` s e t s e r i a l/ d e v / $ D E V I C Ei r q0;s e t s e r i a l/ d e v / $ D E V I C Ei r q$ I R Q

getty, agetty The initialization process for a terminal uses getty or agetty to set it up for login by a user. These commands are not used within user shell scripts. Their scripting counterpart is stty. mesg Enables or disables write access to the current user's terminal. Disabling access would prevent another user on the network to write to the terminal. It can be quite annoying to have a message about ordering pizza suddenly appear in the middle of the text file you are editing. On a multi-user network, you might therefore wish to disable write access to your terminal when you need to avoid interruptions. wall This is an acronym for "write all," i.e., sending a message to all users at every terminal logged into the network. It is primarily a system administrator's tool, useful, for example, when warning everyone that the system will shortly go down due to a problem (see Example 19-1).
b a s h $w a l lS y s t e mg o i n gd o w nf o rm a i n t e n a n c ei n5m i n u t e s ! B r o a d c a s tm e s s a g ef r o mb o z o( p t s / 1 )S u nJ u l 81 3 : 5 3 : 2 72 0 0 1 . . . S y s t e mg o i n gd o w nf o rm a i n t e n a n c ei n5m i n u t e s !

If write access to a particular terminal has been disabled with mesg, then wall cannot send a

message to that terminal. Information and Statistics uname Output system specifications (OS, kernel version, etc.) to s t d o u t . Invoked with the aoption, gives verbose system info (see Example 16-5). The soption shows only the OS type.
b a s h $u n a m e L i n u x b a s h $u n a m es L i n u x

b a s h $u n a m ea L i n u xi r o n . b o z o2 . 6 . 1 5 1 . 2 0 5 4 _ F C 5# 1T u eM a r1 41 5 : 4 8 : 3 3E S T2 0 0 6 i 6 8 6i 6 8 6i 3 8 6G N U / L i n u x

arch Show system architecture. Equivalent to uname -m. See Example 11-26.
b a s h $a r c h i 6 8 6 b a s h $u n a m em i 6 8 6

lastcomm Gives information about previous commands, as stored in the / v a r / a c c o u n t / p a c c tfile. Command name and user name can be specified by options. This is one of the GNU accounting utilities. lastlog List the last login time of all system users. This references the / v a r / l o g / l a s t l o gfile.
b a s h $l a s t l o g r o o t t t y 1 b i n d a e m o n . . . b o z o t t y 1 F r iD e c 71 8 : 4 3 : 2 10 7 0 02 0 0 1 * * N e v e rl o g g e di n * * * * N e v e rl o g g e di n * * S a tD e c 82 1 : 1 4 : 2 90 7 0 02 0 0 1

b a s h $l a s t l o g|g r e pr o o t r o o t t t y 1

F r iD e c 71 8 : 4 3 : 2 10 7 0 02 0 0 1

This command will fail if the user invoking it does not have read permission for the / v a r / l o g / l a s t l o gfile. lsof List open files. This command outputs a detailed table of all currently open files and gives information about their owner, size, the processes associated with them, and more. Of course, lsof may be piped to grep and/or awk to parse and analyze its results.
b a s h $l s o f C O M M A N D P I D i n i t 1 i n i t 1 U S E R F D T Y P E r o o t m e m R E G r o o t m e m R E G D E V I C E 3 , 5 3 , 5 S I Z E 3 0 7 4 8 7 3 1 2 0 N O D EN A M E 3 0 3 0 3/ s b i n / i n i t 8 0 6 9/ l i b / l d 2 . 1 . 3 . s o

i n i t c a r d m g r . . .

1 2 1 3

r o o t m e m r o o t m e m

R E G R E G

3 , 5 9 3 1 6 6 8 3 , 5 3 6 9 5 6

8 0 7 5/ l i b / l i b c 2 . 1 . 3 . s o 3 0 3 5 7/ s b i n / c a r d m g r

The lsof command is a useful, if complex administrative tool. If you are unable to dismount a filesystem and get an error message that it is still in use, then running lsof helps determine which files are still open on that filesystem. The i option lists open network socket files, and this can help trace intrusion or hack attempts.
b a s h $l s o fa nit c p C O M M A N D P I DU S E R F D T Y P ED E V I C ES I Z EN O D EN A M E f i r e f o x2 3 3 0b o z o 3 2 uI P v 4 9 9 5 6 T C P6 6 . 0 . 1 1 8 . 1 3 7 : 5 7 5 9 6 > 6 7 . 1 1 2 . 7 . 1 0 4 : h t t p. . . f i r e f o x2 3 3 0b o z o 3 8 uI P v 4 1 0 5 3 5 T C P6 6 . 0 . 1 1 8 . 1 3 7 : 5 7 7 0 8 > 2 1 6 . 7 9 . 4 8 . 2 4 : h t t p. . .

See Example 30-2 for an effective use of lsof. strace System trace : diagnostic and debugging tool for tracing system calls and signals. This command and ltrace , following, are useful for diagnosing why a given program or package fails to run . . . perhaps due to missing libraries or related causes.
b a s h $s t r a c ed f e x e c v e ( " / b i n / d f " ,[ " d f " ] ,[ / *4 5v a r s* / ] )=0 u n a m e ( { s y s = " L i n u x " ,n o d e = " b o z o . l o c a l d o m a i n " ,. . . } )=0 b r k ( 0 ) =0 x 8 0 4 f 5 e 4 . . .

This is the Linux equivalent of the Solaris truss command. ltrace Library trace : diagnostic and debugging tool that traces library calls invoked by a given command.
b a s h $l t r a c ed f _ _ l i b c _ s t a r t _ m a i n ( 0 x 8 0 4 a 9 1 0 ,1 ,0 x b f b 5 8 9 a 4 ,0 x 8 0 4 f b 7 0 ,0 x 8 0 4 f b 6 8< u n f i n i s h e d. . . > : s e t l o c a l e ( 6 ," " ) =" e n _ U S . U T F 8 " b i n d t e x t d o m a i n ( " c o r e u t i l s " ," / u s r / s h a r e / l o c a l e " )=" / u s r / s h a r e / l o c a l e " t e x t d o m a i n ( " c o r e u t i l s " ) =" c o r e u t i l s " _ _ c x a _ a t e x i t ( 0 x 8 0 4 b 6 5 0 ,0 ,0 ,0 x 8 0 5 2 b f 0 ,0 x b f b 5 8 9 0 8 )=0 g e t e n v ( " D F _ B L O C K _ S I Z E " ) =N U L L . . .

nc The nc (netcat ) utility is a complete toolkit for connecting to and listening to TCP and UDP ports. It is useful as a diagnostic and testing tool and as a component in simple script-based HTTP clients and servers.
b a s h $n cl o c a l h o s t . l o c a l d o m a i n2 5 2 2 0l o c a l h o s t . l o c a l d o m a i nE S M T PS e n d m a i l8 . 1 3 . 1 / 8 . 1 3 . 1 ; T h u ,3 1M a r2 0 0 51 5 : 4 1 : 3 50 7 0 0

A real-life usage example. Example 17-5. Checking a remote server for identd
# !/ b i n / s h

# #D u p l i c a t eD a v e G ' si d e n t s c a nt h i n g i eu s i n gn e t c a t .O o o h ,h e ' l lb ep * s s e d . # #A r g s :t a r g e tp o r t[ p o r tp o r tp o r t. . . ] # #H o s es t d o u t_ a n d _s t d e r rt o g e t h e r . # # # # A d v a n t a g e s :r u n ss l o w e rt h a ni d e n t s c a n ,g i v i n gr e m o t ei n e t dl e s sc a u s e # # +f o ra l a r m ,a n do n l yh i t st h ef e wk n o w nd a e m o np o r t sy o us p e c i f y . # # D i s a d v a n t a g e s :r e q u i r e sn u m e r i c o n l yp o r ta r g s ,t h eo u t p u ts l e a z i t u d e , # # +a n dw o n ' tw o r kf o rr s e r v i c e sw h e nc o m i n gf r o mh i g hs o u r c ep o r t s . #S c r i p ta u t h o r :H o b b i t< h o b b i t @ a v i a n . o r g > #U s e di nA B SG u i d ew i t hp e r m i s s i o n . #E _ B A D A R G S = 6 5 #N e e da tl e a s tt w oa r g s . T W O _ W I N K S = 2 #H o wl o n gt os l e e p . T H R E E _ W I N K S = 3 I D P O R T = 1 1 3 #A u t h e n t i c a t i o n" t a pi d e n t "p o r t . R A N D 1 = 9 9 9 R A N D 2 = 3 1 3 3 7 T I M E O U T 0 = 9 T I M E O U T 1 = 8 T I M E O U T 2 = 4 #c a s e" $ { 2 } "i n " ")e c h o" N e e dH O S Ta n da tl e a s to n eP O R T . ";e x i t$ E _ B A D A R G S; ; e s a c #P i n g' e mo n c ea n ds e ei ft h e y* a r e *r u n n i n gi d e n t d . n czw$ T I M E O U T 0" $ 1 "$ I D P O R T| |\ {e c h o" O o p s ,$ 1i s n ' tr u n n i n gi d e n t d . ";e x i t0;} # zs c a n sf o rl i s t e n i n gd a e m o n s . # w$ T I M E O U T=H o wl o n gt ot r yt oc o n n e c t . #G e n e r a t ear a n d o m i s hb a s ep o r t . R P = ` e x p r$ $%$ R A N D 1+$ R A N D 2 ` T R G = " $ 1 " s h i f t w h i l et e s t" $ 1 ";d o n cvw$ T I M E O U T 1p$ { R P }" $ T R G "$ { 1 }</ d e v / n u l l>/ d e v / n u l l& P R O C = $ ! s l e e p$ T H R E E _ W I N K S e c h o" $ { 1 } , $ { R P } "|n cw$ T I M E O U T 2r" $ T R G "$ I D P O R T2 > & 1 s l e e p$ T W O _ W I N K S #D o e st h i sl o o kl i k eal a m e rs c r i p to rw h a t...? #A B SG u i d ea u t h o rc o m m e n t s :" A i n ' tr e a l l ya l lt h a tb a d... # + k i n d ac l e v e r ,a c t u a l l y . " k i l lH U P$ P R O C R P = ` e x p r$ { R P }+1 ` s h i f t d o n e e x i t$ ? # N o t e s : # # T r yc o m m e n t i n go u tl i n e3 0a n dr u n n i n gt h i ss c r i p t # +w i t h" l o c a l h o s t . l o c a l d o m a i n2 5 "a sa r g u m e n t s . # F o rm o r eo fH o b b i t ' s' n c 'e x a m p l es c r i p t s , # +l o o ki nt h ed o c u m e n t a t i o n : # +t h e/ u s r / s h a r e / d o c / n c X . X X / s c r i p t sd i r e c t o r y .

And, of course, there's Dr. Andrew Tridgell's notorious one-line script in the BitKeeper Affair:

e c h oc l o n e|n ct h u n k . o r g5 0 0 0>e 2 f s p r o g s . d a t

free Shows memory and cache usage in tabular form. The output of this command lends itself to parsing, using grep, awk or Perl. The procinfo command shows all the information that free does, and much more.
b a s h $f r e e t o t a l M e m : 3 0 5 0 4 / +b u f f e r s / c a c h e : S w a p : 6 8 5 4 0 u s e d 2 8 6 2 4 1 0 6 4 0 3 1 2 8 f r e e 1 8 8 0 1 9 8 6 4 6 5 4 1 2 s h a r e d 1 5 8 2 0 b u f f e r s 1 6 0 8 c a c h e d 1 6 3 7 6

To show unused RAM memory:


b a s h $f r e e|g r e pM e m|a w k' {p r i n t$ 4} ' 1 8 8 0

procinfo Extract and list information and statistics from the / p r o cpseudo-filesystem. This gives a very extensive and detailed listing.
b a s h $p r o c i n f o|g r e pB o o t u p B o o t u p :W e dM a r2 11 5 : 1 5 : 5 02 0 0 1 L o a da v e r a g e :0 . 0 40 . 2 10 . 3 43 / 4 76 8 2 9

lsdev List devices, that is, show installed hardware.


b a s h $l s d e v D e v i c e D M A I R Q I / OP o r t s c a s c a d e 4 2 d m a 0 0 8 0 0 0 8 f d m a 1 0 0 0 0 0 0 1 f d m a 2 0 0 c 0 0 0 d f f p u 0 0 f 0 0 0 f f i d e 0 1 4 0 1 f 0 0 1 f 70 3 f 6 0 3 f 6 . . .

du Show (disk) file usage, recursively. Defaults to current working directory, unless otherwise specified.
b a s h $d ua c h 1 . 0 k . / w i . s h 1 . 0 k . / t s t . s h 1 . 0 k . / r a n d o m . f i l e 6 . 0 k . 6 . 0 k t o t a l

df Shows filesystem usage in tabular form.


b a s h $d f F i l e s y s t e m / d e v / h d a 5 / d e v / h d a 8 / d e v / h d a 7 1 k b l o c k s 2 7 3 2 6 2 2 2 2 5 2 5 1 4 0 8 7 9 6 U s e dA v a i l a b l eU s e %M o u n t e do n 9 2 6 0 7 1 6 6 5 4 7 3 6 %/ 1 2 3 9 5 1 8 7 0 8 5 5 9 %/ h o m e 1 0 7 5 7 4 4 2 6 1 4 8 8 8 0 %/ u s r

dmesg

Lists all system bootup messages to s t d o u t . Handy for debugging and ascertaining which device drivers were installed and which system interrupts in use. The output of dmesg may, of course, be parsed with grep, sed, or awk from within a script.
b a s h $d m e s g|g r e ph d a K e r n e lc o m m a n dl i n e :r or o o t = / d e v / h d a 2 h d a :I B M D L G A 2 3 0 8 0 ,A T AD I S Kd r i v e h d a :6 0 1 5 7 4 4s e c t o r s( 3 0 8 0M B )w / 9 6 K i BC a c h e ,C H S = 7 4 6 / 1 2 8 / 6 3 h d a :h d a 1h d a 2h d a 3<h d a 5h d a 6h d a 7>h d a 4

stat Gives detailed and verbose stat istics on a given file (even a directory or device file) or set of files.
b a s h $s t a tt e s t . c r u F i l e :" t e s t . c r u " S i z e :4 9 9 7 0 A l l o c a t e dB l o c k s :1 0 0 F i l e t y p e :R e g u l a rF i l e M o d e :( 0 6 6 4 / r w r w r ) U i d :( 5 0 1 /b o z o ) G i d :( 5 0 1 /b o z o ) D e v i c e : 3 , 8 I n o d e :1 8 1 8 5 L i n k s :1 A c c e s s :S a tJ u n 21 6 : 4 0 : 2 42 0 0 1 M o d i f y :S a tJ u n 21 6 : 4 0 : 2 42 0 0 1 C h a n g e :S a tJ u n 21 6 : 4 0 : 2 42 0 0 1

If the target file does not exist, stat returns an error message.
b a s h $s t a tn o n e x i s t e n t f i l e n o n e x i s t e n t f i l e :N os u c hf i l eo rd i r e c t o r y

In a script, you can use stat to extract information about files (and filesystems) and set variables accordingly.
# ! / b i n / b a s h #f i l e i n f o 2 . s h #P e rs u g g e s t i o no fJ o lB o u r q u a r da n d... #h t t p : / / w w w . l i n u x q u e s t i o n s . o r g / q u e s t i o n s / s h o w t h r e a d . p h p ? t = 4 1 0 7 6 6

F I L E N A M E = t e s t f i l e . t x t f i l e _ n a m e = $ ( s t a tc % n" $ F I L E N A M E " ) #S a m ea s" $ F I L E N A M E "o fc o u r s e . f i l e _ o w n e r = $ ( s t a tc % U" $ F I L E N A M E " ) f i l e _ s i z e = $ ( s t a tc % s" $ F I L E N A M E " ) # C e r t a i n l ye a s i e rt h a nu s i n g" l sl$ F I L E N A M E " # +a n dt h e np a r s i n gw i t hs e d . f i l e _ i n o d e = $ ( s t a tc % i" $ F I L E N A M E " ) f i l e _ t y p e = $ ( s t a tc % F" $ F I L E N A M E " ) f i l e _ a c c e s s _ r i g h t s = $ ( s t a tc % A" $ F I L E N A M E " ) e c h o" F i l en a m e : $ f i l e _ n a m e " e c h o" F i l eo w n e r : $ f i l e _ o w n e r " e c h o" F i l es i z e : $ f i l e _ s i z e " e c h o" F i l ei n o d e : $ f i l e _ i n o d e " e c h o" F i l et y p e : $ f i l e _ t y p e " e c h o" F i l ea c c e s sr i g h t s :$ f i l e _ a c c e s s _ r i g h t s " e x i t0 s hf i l e i n f o 2 . s h F i l en a m e : F i l eo w n e r : F i l es i z e : F i l ei n o d e : t e s t f i l e . t x t b o z o 4 1 8 1 7 3 0 3 7 8

F i l et y p e : r e g u l a rf i l e F i l ea c c e s sr i g h t s :r w r w r -

vmstat Display virtual memory statistics.


b a s h $v m s t a t p r o c s r b w s w p d f r e e 0 0 0 0 1 1 0 4 0 m e m o r y s w a p b u f f c a c h e s i s o 2 6 3 6 3 8 9 5 2 0 0 i os y s t e m c p u b o i n c s u s s yi d 7 2 7 1 8 8 8 38 9

b i 3 3

uptime Shows how long the system has been running, along with associated statistics.
b a s h $u p t i m e 1 0 : 2 8 p m u p 1 : 5 7 , 3u s e r s , l o a da v e r a g e :0 . 1 7 ,0 . 3 4 ,0 . 2 7

A load average of 1 or less indicates that the system handles processes immediately. A load average greater than 1 means that processes are being queued. When the load average gets above 3 (on a single-core processor), then system performance is significantly degraded. hostname Lists the system's host name. This command sets the host name in an / e t c / r c . dsetup script (/ e t c / r c . d / r c . s y s i n i tor similar). It is equivalent to uname -n, and a counterpart to the $HOSTNAME internal variable.
b a s h $h o s t n a m e l o c a l h o s t . l o c a l d o m a i n b a s h $e c h o$ H O S T N A M E l o c a l h o s t . l o c a l d o m a i n

Similar to the hostname command are the domainname , dnsdomainname , nisdomainname , and ypdomainname commands. Use these to display or set the system DNS or NIS/YP domain name. Various options to hostname also perform these functions. hostid Echo a 32-bit hexadecimal numerical identifier for the host machine.
b a s h $h o s t i d 7 f 0 1 0 0

This command allegedly fetches a "unique" serial number for a particular system. Certain product registration procedures use this number to brand a particular user license. Unfortunately, hostid only returns the machine network address in hexadecimal, with pairs of bytes transposed. The network address of a typical non-networked Linux machine, is found in / e t c / h o s t s .
b a s h $c a t/ e t c / h o s t s 1 2 7 . 0 . 0 . 1 l o c a l h o s t . l o c a l d o m a i nl o c a l h o s t

As it happens, transposing the bytes of 1 2 7 . 0 . 0 . 1 , we get 0 . 1 2 7 . 1 . 0 , which translates in hex to 0 0 7 f 0 1 0 0 , the exact equivalent of what hostid returns, above. There exist only a few million other Linux machines with this identical hostid. sar

Invoking sar (System Activity Reporter) gives a very detailed rundown on system statistics. The Santa Cruz Operation ("Old" SCO) released sar as Open Source in June, 1999. This command is not part of the base Linux distribution, but may be obtained as part of the sysstat utilities package, written by Sebastien Godard.
b a s h $s a r L i n u x2 . 4 . 9( b r o o k s . s e r i n g a s . f r ) 1 0 : 3 0 : 0 0 1 0 : 4 0 : 0 0 1 0 : 5 0 : 0 0 1 1 : 0 0 : 0 0 A v e r a g e : 1 4 : 3 2 : 3 0 1 5 : 0 0 : 0 0 1 5 : 1 0 : 0 0 1 5 : 2 0 : 0 0 1 5 : 3 0 : 0 0 A v e r a g e : C P U a l l a l l a l l a l l % u s e r 2 . 2 1 3 . 3 6 1 . 1 2 2 . 2 3 0 9 / 2 6 / 0 3 % n i c e 1 0 . 9 0 0 . 0 0 0 . 0 0 3 . 6 3 % s y s t e m 6 5 . 4 8 7 2 . 3 6 8 0 . 7 7 7 2 . 8 7 % i o w a i t 0 . 0 0 0 . 0 0 0 . 0 0 0 . 0 0 % i d l e 2 1 . 4 1 2 4 . 2 8 1 8 . 1 1 2 1 . 2 7

L I N U XR E S T A R T C P U a l l a l l a l l a l l % u s e r 8 . 5 9 4 . 0 7 0 . 7 9 6 . 3 3 % n i c e 2 . 4 0 1 . 0 0 2 . 9 4 1 . 7 0 % s y s t e m 1 7 . 4 7 1 1 . 9 5 7 . 5 6 1 4 . 7 1 % i o w a i t 0 . 0 0 0 . 0 0 0 . 0 0 0 . 0 0 % i d l e 7 1 . 5 4 8 2 . 9 8 8 8 . 7 1 7 7 . 2 6

readelf Show information and statistics about a designated elf binary. This is part of the binutils package.
b a s h $r e a d e l fh/ b i n / b a s h E L FH e a d e r : M a g i c : 7 f4 54 c4 60 10 10 10 00 00 00 00 00 00 00 00 0 C l a s s : E L F 3 2 D a t a : 2 ' sc o m p l e m e n t ,l i t t l ee n d i a n V e r s i o n : 1( c u r r e n t ) O S / A B I : U N I X-S y s t e mV A B IV e r s i o n : 0 T y p e : E X E C( E x e c u t a b l ef i l e ) ...

size The size [/path/to/binary] command gives the segment sizes of a binary executable or archive file. This is mainly of use to programmers.
b a s h $s i z e/ b i n / b a s h t e x t d a t a b s s d e c 4 9 5 9 7 1 2 2 4 9 6 1 7 3 9 2 5 3 5 8 5 9 h e xf i l e n a m e 8 2 d 3 3/ b i n / b a s h

System Logs logger Appends a user-generated message to the system log (/ v a r / l o g / m e s s a g e s ). You do not have to be root to invoke logger.
l o g g e rE x p e r i e n c i n gi n s t a b i l i t yi nn e t w o r kc o n n e c t i o na t2 3 : 1 0 ,0 5 / 2 1 . #N o w ,d oa' t a i l/ v a r / l o g / m e s s a g e s ' .

By embedding a logger command in a script, it is possible to write debugging information to / v a r / l o g / m e s s a g e s .


l o g g e rt$ 0iL o g g i n ga tl i n e" $ L I N E N O " . #T h e" t "o p t i o ns p e c i f i e st h et a gf o rt h el o g g e re n t r y . #T h e" i "o p t i o nr e c o r d st h ep r o c e s sI D .

#t a i l/ v a r / l o g / m e s s a g e #. . . #J u l 72 0 : 4 8 : 5 8l o c a l h o s t. / t e s t . s h [ 1 7 1 2 ] :L o g g i n ga tl i n e3 .

logrotate This utility manages the system log files, rotating, compressing, deleting, and/or e-mailing them, as appropriate. This keeps the / v a r / l o gfrom getting cluttered with old log files. Usually cron runs logrotate on a daily basis. Adding an appropriate entry to / e t c / l o g r o t a t e . c o n fmakes it possible to manage personal log files, as well as system-wide ones. Stefano Falsetto has created rottlog, which he considers to be an improved version of logrotate . Job Control ps
P rocess S tatistics: lists currently executing processes by owner and

PID (process ID). This is usually invoked with a x or a u xoptions, and may be piped to grep or sed to search for a specific process (see Example 15-14 and Example 29-3).
b a s h $ p sa x|g r e ps e n d m a i l 2 9 5? S 0 : 0 0s e n d m a i l :a c c e p t i n gc o n n e c t i o n so np o r t2 5

To display system processes in graphical "tree" format: ps afjx or ps ax --forest. pgrep, pkill Combining the ps command with grep or kill.
b a s h $p sa|g r e pm i n g e t t y 2 2 1 2t t y 2 S s + 0 : 0 0/ s b i n / m i n g e t t yt t y 2 2 2 1 3t t y 3 S s + 0 : 0 0/ s b i n / m i n g e t t yt t y 3 2 2 1 4t t y 4 S s + 0 : 0 0/ s b i n / m i n g e t t yt t y 4 2 2 1 5t t y 5 S s + 0 : 0 0/ s b i n / m i n g e t t yt t y 5 2 2 1 6t t y 6 S s + 0 : 0 0/ s b i n / m i n g e t t yt t y 6 4 8 4 9p t s / 2 S + 0 : 0 0g r e pm i n g e t t y

b a s h $p g r e pm i n g e t t y 2 2 1 2m i n g e t t y 2 2 1 3m i n g e t t y 2 2 1 4m i n g e t t y 2 2 1 5m i n g e t t y 2 2 1 6m i n g e t t y

Compare the action of pkill with killall. pstree Lists currently executing processes in "tree" format. The poption shows the PIDs, as well as the process names. top Continuously updated display of most cpu-intensive processes. The boption displays in text mode, so that the output may be parsed or accessed from a script.
b a s h $t o pb 8 : 3 0 p m u p3m i n , 3u s e r s , l o a da v e r a g e :0 . 4 9 ,0 . 3 2 ,0 . 1 3 4 5p r o c e s s e s :4 4s l e e p i n g ,1r u n n i n g ,0z o m b i e ,0s t o p p e d

C P Us t a t e s :1 3 . 6 %u s e r , 7 . 3 %s y s t e m , 0 . 0 %n i c e ,7 8 . 9 %i d l e M e m : 7 8 3 9 6 Ka v , 6 5 4 6 8 Ku s e d , 1 2 9 2 8 Kf r e e , 0 Ks h r d , S w a p : 1 5 7 2 0 8 Ka v , 0 Ku s e d , 1 5 7 2 0 8 Kf r e e P I DU S E R 8 4 8b o z o 1r o o t 2r o o t . . . P R I N I S I Z E R S SS H A R ES T A T% C P U% M E M 1 7 0 9 9 6 9 9 6 8 0 0R 5 . 6 1 . 2 8 0 5 1 2 5 1 2 4 4 4S 0 . 0 0 . 6 9 0 0 0 0S W 0 . 0 0 . 0

2 3 5 2 Kb u f f 3 7 2 4 4 Kc a c h e d

T I M EC O M M A N D 0 : 0 0t o p 0 : 0 4i n i t 0 : 0 0k e v e n t d

nice Run a background job with an altered priority. Priorities run from 19 (lowest) to -20 (highest). Only root may set the negative (higher) priorities. Related commands are renice and snice , which change the priority of a running process or processes, and skill, which sends a kill signal to a process or processes. nohup Keeps a command running even after user logs off. The command will run as a foreground process unless followed by &. If you use nohup within a script, consider coupling it with a wait to avoid creating an orphan or zombie process. pidof Identifies process ID (PID) of a running job. Since job control commands, such as kill and renice act on the PID of a process (not its name), it is sometimes necessary to identify that PID. The pidof command is the approximate counterpart to the $PPID internal variable.
b a s h $p i d o fx c l o c k 8 8 0

Example 17-6. pidof helps kill a process


# ! / b i n / b a s h #k i l l p r o c e s s . s h N O P R O C E S S = 2 p r o c e s s = x x x y y y z z z #U s en o n e x i s t e n tp r o c e s s . #F o rd e m op u r p o s e so n l y . . . #. . .d o n ' tw a n tt oa c t u a l l yk i l la n ya c t u a lp r o c e s sw i t ht h i ss c r i p t . # #I f ,f o re x a m p l e ,y o uw a n t e dt ou s et h i ss c r i p tt ol o g o f ft h eI n t e r n e t , # p r o c e s s = p p p d t = ` p i d o f$ p r o c e s s ` #F i n dp i d( p r o c e s si d )o f$ p r o c e s s . #T h ep i di sn e e d e db y' k i l l '( c a n ' t' k i l l 'b yp r o g r a mn a m e ) . i f[z" $ t "] #I fp r o c e s sn o tp r e s e n t ,' p i d o f 'r e t u r n sn u l l . t h e n e c h o" P r o c e s s$ p r o c e s sw a sn o tr u n n i n g . " e c h o" N o t h i n gk i l l e d . " e x i t$ N O P R O C E S S f i k i l l$ t #M a yn e e d' k i l l9 'f o rs t u b b o r np r o c e s s .

#N e e dac h e c kh e r et os e ei fp r o c e s sa l l o w e di t s e l ft ob ek i l l e d . #P e r h a p sa n o t h e r"t = ` p i d o f$ p r o c e s s `"o r. . .

#T h i se n t i r es c r i p tc o u l db er e p l a c e db y # k i l l$ ( p i d o fxp r o c e s s _ n a m e ) #o r

# k i l l a l lp r o c e s s _ n a m e #b u ti tw o u l dn o tb ea si n s t r u c t i v e . e x i t0

fuser Identifies the processes (by PID) that are accessing a given file, set of files, or directory. May also be invoked with the koption, which kills those processes. This has interesting implications for system security, especially in scripts preventing unauthorized users from accessing system services.
b a s h $f u s e ru/ u s r / b i n / v i m / u s r / b i n / v i m : 3 2 0 7 e ( b o z o )

b a s h $f u s e ru/ d e v / n u l l / d e v / n u l l : 3 0 0 9 ( b o z o ) 3 0 1 0 ( b o z o ) 3 1 9 7 ( b o z o ) 3 1 9 9 ( b o z o )

One important application for fuser is when physically inserting or removing storage media, such as CD ROM disks or USB flash drives. Sometimes trying a umount fails with a device is busy error message. This means that some user(s) and/or process(es) are accessing the device. An fuser -um /dev/device_name will clear up the mystery, so you can kill any relevant processes.
b a s h $u m o u n t/ m n t / u s b d r i v e u m o u n t :/ m n t / u s b d r i v e :d e v i c ei sb u s y

b a s h $f u s e ru m/ d e v / u s b d r i v e / m n t / u s b d r i v e : 1 7 7 2 c ( b o z o ) b a s h $k i l l91 7 7 2 b a s h $u m o u n t/ m n t / u s b d r i v e

The fuser command, invoked with the noption identifies the processes accessing a port . This is especially useful in combination with nmap.
r o o t #n m a pl o c a l h o s t . l o c a l d o m a i n P O R T S T A T ES E R V I C E 2 5 / t c p o p e n s m t p

r o o t #f u s e ru nt c p2 5 2 5 / t c p : 2 0 9 5 ( r o o t ) r o o t #p sa x|g r e p2 0 9 5|g r e pvg r e p 2 0 9 5? S s 0 : 0 0s e n d m a i l :a c c e p t i n gc o n n e c t i o n s

cron Administrative program scheduler, performing such duties as cleaning up and deleting system log files and updating the slocate database. This is the superuser version of at (although each user may have their own c r o n t a bfile which can be changed with the crontab command). It runs as a daemon and executes scheduled entries from / e t c / c r o n t a b . Some flavors of Linux run crond, Matthew Dillon's version of cron. Process Control and Booting

init The init command is the parent of all processes. Called in the final step of a bootup, init determines the runlevel of the system from / e t c / i n i t t a b . Invoked by its alias telinit, and by root only. telinit Symlinked to init, this is a means of changing the system runlevel, usually done for system maintenance or emergency filesystem repairs. Invoked only by root . This command can be dangerous -- be certain you understand it well before using! runlevel Shows the current and last runlevel, that is, whether the system is halted (runlevel 0 ), in single-user mode (1 ), in multiuser mode (2or 3 ), in X Windows (5 ), or rebooting (6 ). This command accesses the / v a r / r u n / u t m pfile. halt, shutdown, reboot Command set to shut the system down, usually just prior to a power down. On some Linux distros, the halt command has 755 permissions, so it can be invoked by a nonroot user. A careless halt in a terminal or a script may shut down the system! service Starts or stops a system service. The startup scripts in / e t c / i n i t . dand / e t c / r c . duse this command to start services at bootup.
r o o t #/ s b i n / s e r v i c ei p t a b l e ss t o p F l u s h i n gf i r e w a l lr u l e s : S e t t i n gc h a i n st op o l i c yA C C E P T :f i l t e r U n l o a d i n gi p t a b l e sm o d u l e s : [ O K ] [ O K ] [ O K ]

Network nmap Network mapper and port scanner. This command scans a server to locate open ports and the services associated with those ports. It can also report information about packet filters and firewalls. This is an important security tool for locking down a network against hacking attempts.
# ! / b i n / b a s h S E R V E R = $ H O S T P O R T _ N U M B E R = 2 5 #l o c a l h o s t . l o c a l d o m a i n( 1 2 7 . 0 . 0 . 1 ) . #S M T Pp o r t .

n m a p$ S E R V E R|g r e pw" $ P O R T _ N U M B E R " #I st h a tp a r t i c u l a rp o r to p e n ? # g r e pwm a t c h e sw h o l ew o r d so n l y , # + s ot h i sw o u l d n ' tm a t c hp o r t1 0 2 5 ,f o re x a m p l e . e x i t0 #2 5 / t c p o p e n s m t p

ifconfig Network interface configuration and tuning utility.


b a s h $i f c o n f i ga l o L i n ke n c a p : L o c a lL o o p b a c k i n e ta d d r : 1 2 7 . 0 . 0 . 1 M a s k : 2 5 5 . 0 . 0 . 0

U PL O O P B A C KR U N N I N G M T U : 1 6 4 3 6 M e t r i c : 1 R Xp a c k e t s : 1 0e r r o r s : 0d r o p p e d : 0o v e r r u n s : 0f r a m e : 0 T Xp a c k e t s : 1 0e r r o r s : 0d r o p p e d : 0o v e r r u n s : 0c a r r i e r : 0 c o l l i s i o n s : 0t x q u e u e l e n : 0 R Xb y t e s : 7 0 0( 7 0 0 . 0b ) T Xb y t e s : 7 0 0( 7 0 0 . 0b )

The ifconfig command is most often used at bootup to set up the interfaces, or to shut them down when rebooting.
#C o d es n i p p e t sf r o m/ e t c / r c . d / i n i t . d / n e t w o r k #. . . #C h e c kt h a tn e t w o r k i n gi su p . [$ { N E T W O R K I N G }=" n o "]& &e x i t0 [x/ s b i n / i f c o n f i g]| |e x i t0 #. . . f o rii n$ i n t e r f a c e s;d o i fi f c o n f i g$ i2 > / d e v / n u l l|g r e pq" U P "> / d e v / n u l l2 > & 1;t h e n a c t i o n" S h u t t i n gd o w ni n t e r f a c e$ i :". / i f d o w n$ ib o o t f i # T h eG N U s p e c i f i c" q "o p t i o nt o" g r e p "m e a n s" q u i e t " ,i . e . , # +p r o d u c i n gn oo u t p u t . # R e d i r e c t i n go u t p u tt o/ d e v / n u l li st h e r e f o r en o ts t r i c t l yn e c e s s a r y . #. . . e c h o" C u r r e n t l ya c t i v ed e v i c e s : " e c h o` / s b i n / i f c o n f i g|g r e p^ [ a z ]|a w k' { p r i n t$ 1 } ' ` # ^ ^ ^ ^ ^ s h o u l db eq u o t e dt op r e v e n tg l o b b i n g . # T h ef o l l o w i n ga l s ow o r k . # e c h o$ ( / s b i n / i f c o n f i g|a w k' / ^ [ a z ] /{p r i n t$ 1} ) ' # e c h o$ ( / s b i n / i f c o n f i g|s e de' s /. * / / ' ) # T h a n k s ,S . C . ,f o ra d d i t i o n a lc o m m e n t s .

See also Example 32-6. netstat Show current network statistics and information, such as routing tables and active connections. This utility accesses information in / p r o c / n e t(Chapter 29). See Example 29-4. netstat -r is equivalent to route.
b a s h $n e t s t a t A c t i v eI n t e r n e tc o n n e c t i o n s( w / os e r v e r s ) P r o t oR e c v QS e n d QL o c a lA d d r e s s F o r e i g nA d d r e s s S t a t e A c t i v eU N I Xd o m a i ns o c k e t s( w / os e r v e r s ) P r o t oR e f C n tF l a g s T y p e S t a t e I N o d eP a t h u n i x 1 1 [] D G R A M 9 0 6 / d e v / l o g u n i x 3 [] S T R E A M C O N N E C T E D 4 5 1 4 / t m p / . X 1 1 u n i x / X 0 u n i x 3 [] S T R E A M C O N N E C T E D 4 5 1 3 ...

A netstat -lptu shows sockets that are listening to ports, and the associated processes. This can be useful for determining whether a computer has been hacked or compromised. iwconfig This is the command set for configuring a wireless network. It is the wireless equivalent of ifconfig, above. ip

General purpose utility for setting up, changing, and analyzing IP (Internet Protocol) networks and attached devices. This command is part of the iproute2 package.
b a s h $i pl i n ks h o w 1 :l o :< L O O P B A C K , U P >m t u1 6 4 3 6q d i s cn o q u e u e l i n k / l o o p b a c k0 0 : 0 0 : 0 0 : 0 0 : 0 0 : 0 0b r d0 0 : 0 0 : 0 0 : 0 0 : 0 0 : 0 0 2 :e t h 0 :< B R O A D C A S T , M U L T I C A S T >m t u1 5 0 0q d i s cp f i f o _ f a s tq l e n1 0 0 0 l i n k / e t h e r0 0 : d 0 : 5 9 : c e : a f : d ab r df f : f f : f f : f f : f f : f f 3 :s i t 0 :< N O A R P >m t u1 4 8 0q d i s cn o o p l i n k / s i t0 . 0 . 0 . 0b r d0 . 0 . 0 . 0

b a s h $i pr o u t el i s t 1 6 9 . 2 5 4 . 0 . 0 / 1 6d e vl o s c o p el i n k

Or, in a script:
# ! / b i n / b a s h #S c r i p tb yJ u a nN i c o l a sR u i z #U s e dw i t hh i sk i n dp e r m i s s i o n . #S e t t i n gu p( a n ds t o p p i n g )aG R Et u n n e l .

#-s t a r t t u n n e l . s hL O C A L _ I P = " 1 9 2 . 1 6 8 . 1 . 1 7 " R E M O T E _ I P = " 1 0 . 0 . 5 . 3 3 " O T H E R _ I F A C E = " 1 9 2 . 1 6 8 . 0 . 1 0 0 " R E M O T E _ N E T = " 1 9 2 . 1 6 8 . 3 . 0 / 2 4 " / s b i n / i pt u n n e la d dn e t bm o d eg r er e m o t e$ R E M O T E _ I P\ l o c a l$ L O C A L _ I Pt t l2 5 5 / s b i n / i pa d d ra d d$ O T H E R _ I F A C Ed e vn e t b / s b i n / i pl i n ks e tn e t bu p / s b i n / i pr o u t ea d d$ R E M O T E _ N E Td e vn e t b e x i t0 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #-s t o p t u n n e l . s hR E M O T E _ N E T = " 1 9 2 . 1 6 8 . 3 . 0 / 2 4 " / s b i n / i pr o u t ed e l$ R E M O T E _ N E Td e vn e t b / s b i n / i pl i n ks e tn e t bd o w n / s b i n / i pt u n n e ld e ln e t b e x i t0

route Show info about or make changes to the kernel routing table.
b a s h $r o u t e D e s t i n a t i o n G a t e w a y G e n m a s k F l a g s p m 3 6 7 . b o z o s i s p* 2 5 5 . 2 5 5 . 2 5 5 . 2 5 5U H 1 2 7 . 0 . 0 . 0 * 2 5 5 . 0 . 0 . 0 U d e f a u l t p m 3 6 7 . b o z o s i s p0 . 0 . 0 . 0 U G M S SW i n d o w i r t tI f a c e 4 00 0p p p 0 4 00 0l o 4 00 0p p p 0

iptables The iptables command set is a packet filtering tool used mainly for such security purposes as setting up network firewalls. This is a complex tool, and a detailed explanation of its use is beyond the scope of this document. Oskar

Andreasson's tutorial is a reasonable starting point. See also shutting down iptables and Example 30-2. chkconfig Check network and system configuration. This command lists and manages the network and system services started at bootup in the / e t c / r c ? . ddirectory. Originally a port from IRIX to Red Hat Linux, chkconfig may not be part of the core installation of some Linux flavors.
b a s h $c h k c o n f i gl i s t a t d 0 : o f f 1 : o f f 2 : o f f 3 : o n 4 : o n 5 : o n 6 : o f f r w h o d 0 : o f f 1 : o f f 2 : o f f 3 : o f f 4 : o f f 5 : o f f 6 : o f f . . .

tcpdump Network packet "sniffer." This is a tool for analyzing and troubleshooting traffic on a network by dumping packet headers that match specified criteria. Dump ip packet traffic between hosts bozoville and caduceus:
b a s h $t c p d u m pi ph o s tb o z o v i l l ea n dc a d u c e u s

Of course, the output of tcpdump can be parsed with certain of the previously discussed text processing utilities. Filesystem mount Mount a filesystem, usually on an external device, such as a floppy or CDROM. The file / e t c / f s t a bprovides a handy listing of available filesystems, partitions, and devices, including options, that may be automatically or manually mounted. The file / e t c / m t a bshows the currently mounted filesystems and partitions (including the virtual ones, such as / p r o c ). mount -a mounts all filesystems and partitions listed in / e t c / f s t a b , except those with a n o a u t ooption. At bootup, a startup script in / e t c / r c . d(r c . s y s i n i tor something similar) invokes this to get everything mounted.
m o u n tti s o 9 6 6 0/ d e v / c d r o m/ m n t / c d r o m #M o u n t sC DR O M .I S O9 6 6 0i sas t a n d a r dC DR O Mf i l e s y s t e m . m o u n t/ m n t / c d r o m #S h o r t c u t ,i f/ m n t / c d r o ml i s t e di n/ e t c / f s t a b

The versatile mount command can even mount an ordinary file on a block device, and the file will act as if it were a filesystem. Mount accomplishes that by associating the file with a loopback device. One application of this is to mount and examine an ISO9660 filesystem image before burning it onto a CDR. [90] Example 17-7. Checking a CD image
#A sr o o t . . . m k d i r/ m n t / c d t e s t #P r e p a r eam o u n tp o i n t ,i fn o ta l r e a d yt h e r e . m o u n trti s o 9 6 6 0ol o o pc d i m a g e . i s o/ m n t / c d t e s t #M o u n tt h ei m a g e . # " ol o o p "o p t i o ne q u i v a l e n tt o" l o s e t u p/ d e v / l o o p 0 " c d/ m n t / c d t e s t #N o w ,c h e c kt h ei m a g e . l sa l R #L i s tt h ef i l e si nt h ed i r e c t o r yt r e et h e r e .

#A n ds of o r t h .

umount Unmount a currently mounted filesystem. Before physically removing a previously mounted floppy or CDROM disk, the device must be umounted, else filesystem corruption may result.
u m o u n t/ m n t / c d r o m #Y o um a yn o wp r e s st h ee j e c tb u t t o na n ds a f e l yr e m o v et h ed i s k .

The automount utility, if properly installed, can mount and unmount floppies or CDROM disks as they are accessed or removed. On "multispindle" laptops with swappable floppy and optical drives, this can cause problems, however. gnome-mount The newer Linux distros have deprecated mount and umount. The successor, for command-line mounting of removable storage devices, is gnome-mount. It can take the doption to mount a device file by its listing in / d e v . For example, to mount a USB flash drive:
b a s h $g n o m e m o u n td/ d e v / s d a 1 g n o m e m o u n t0 . 4

b a s h $d f ... / d e v / s d a 1

6 3 5 8 4

1 2 0 3 4

5 1 5 5 0 1 9 %/ m e d i a / d i s k

sync Forces an immediate write of all updated data from buffers to hard drive (synchronize drive with buffers). While not strictly necessary, a sync assures the sys admin or user that the data just changed will survive a sudden power failure. In the olden days, a s y n c ;s y n c(twice, just to make absolutely sure) was a useful precautionary measure before a system reboot. At times, you may wish to force an immediate buffer flush, as when securely deleting a file (see Example 16-60) or when the lights begin to flicker. losetup Sets up and configures loopback devices. Example 17-8. Creating a filesystem in a file
S I Z E = 1 0 0 0 0 0 0 #1m e g h e a dc$ S I Z E</ d e v / z e r o>f i l e l o s e t u p/ d e v / l o o p 0f i l e m k e 2 f s/ d e v / l o o p 0 m o u n tol o o p/ d e v / l o o p 0/ m n t #T h a n k s ,S . C . #S e tu pf i l eo fd e s i g n a t e ds i z e . #S e ti tu pa sl o o p b a c kd e v i c e . #C r e a t ef i l e s y s t e m . #M o u n ti t .

mkswap Creates a swap partition or file. The swap area must subsequently be enabled with swapon. swapon, swapoff Enable / disable swap partitition or file. These commands usually take effect at bootup and shutdown. mke2fs

Create a Linux ext2 filesystem. This command must be invoked as root . Example 17-9. Adding a new hard drive
# ! / b i n / b a s h #A d d i n gas e c o n dh a r dd r i v et os y s t e m . #S o f t w a r ec o n f i g u r a t i o n .A s s u m e sh a r d w a r ea l r e a d ym o u n t e d . #F r o ma na r t i c l eb yt h ea u t h o ro ft h eA B SG u i d e . #I ni s s u e# 3 8o f_ L i n u xG a z e t t e _ ,h t t p : / / w w w . l i n u x g a z e t t e . c o m . R O O T _ U I D = 0 E _ N O T R O O T = 6 7 #T h i ss c r i p tm u s tb er u na sr o o t . #N o n r o o te x i te r r o r .

i f[" $ U I D "n e" $ R O O T _ U I D "] t h e n e c h o" M u s tb er o o tt or u nt h i ss c r i p t . " e x i t$ E _ N O T R O O T f i #U s ew i t he x t r e m ec a u t i o n ! #I fs o m e t h i n gg o e sw r o n g ,y o um a yw i p eo u ty o u rc u r r e n tf i l e s y s t e m .

N E W D I S K = / d e v / h d b #A s s u m e s/ d e v / h d bv a c a n t .C h e c k ! M O U N T P O I N T = / m n t / n e w d i s k #O rc h o o s ea n o t h e rm o u n tp o i n t .

f d i s k$ N E W D I S K m k e 2 f sc v$ N E W D I S K 1 #C h e c kf o rb a db l o c k s( v e r b o s eo u t p u t ) . # N o t e : ^ / d e v / h d b 1 ,* n o t */ d e v / h d b ! m k d i r$ M O U N T P O I N T c h m o d7 7 7$ M O U N T P O I N T #M a k e sn e wd r i v ea c c e s s i b l et oa l lu s e r s .

#N o w ,t e s t. . . #m o u n tte x t 2/ d e v / h d b 1/ m n t / n e w d i s k #T r yc r e a t i n gad i r e c t o r y . #I fi tw o r k s ,u m o u n ti t ,a n dp r o c e e d . #F i n a ls t e p : #A d dt h ef o l l o w i n gl i n et o/ e t c / f s t a b . #/ d e v / h d b 1 / m n t / n e w d i s k e x t 2 d e f a u l t s 11 e x i t

See also Example 17-8 and Example 31-3. mkdosfs Create a DOS FAT filesystem. tune2fs Tune ext2 filesystem. May be used to change filesystem parameters, such as maximum mount count. This must be invoked as root . This is an extremely dangerous command. Use it at your own risk, as you may inadvertently destroy your filesystem. dumpe2fs Dump (list to s t d o u t ) very verbose filesystem info. This must be invoked as root .
r o o t #d u m p e 2 f s/ d e v / h d a 7|g r e p' o u n tc o u n t ' d u m p e 2 f s1 . 1 9 ,1 3 J u l 2 0 0 0f o rE X T 2F S0 . 5 b ,9 5 / 0 8 / 0 9

M o u n tc o u n t : M a x i m u mm o u n tc o u n t :

6 2 0

hdparm List or change hard disk parameters. This command must be invoked as root , and it may be dangerous if misused. fdisk Create or change a partition table on a storage device, usually a hard drive. This command must be invoked as root . Use this command with extreme caution. If something goes wrong, you may destroy an existing filesystem. fsck, e2fsck, debugfs Filesystem check, repair, and debug command set. fsck: a front end for checking a UNIX filesystem (may invoke other utilities). The actual filesystem type generally defaults to ext2. e2fsck: ext2 filesystem checker. debugfs : ext2 filesystem debugger. One of the uses of this versatile, but dangerous command is to (attempt to) recover deleted files. For advanced users only! All of these should be invoked as root , and they can damage or destroy a filesystem if misused. badblocks Checks for bad blocks (physical media flaws) on a storage device. This command finds use when formatting a newly installed hard drive or testing the integrity of backup media. [91] As an example, badblocks /dev/fd0 tests a floppy disk. The badblocks command may be invoked destructively (overwrite all data) or in non-destructive read-only mode. If root user owns the device to be tested, as is generally the case, then root must invoke this command. lsusb, usbmodules The lsusb command lists all USB (Universal Serial Bus) buses and the devices hooked up to them. The usbmodules command outputs information about the driver modules for connected USB devices.
b a s h $l s u s b B u s0 0 1D e v i c e0 0 1 :I D0 0 0 0 : 0 0 0 0 D e v i c eD e s c r i p t o r : b L e n g t h 1 8 b D e s c r i p t o r T y p e 1 b c d U S B 1 . 0 0 b D e v i c e C l a s s 9H u b b D e v i c e S u b C l a s s 0 b D e v i c e P r o t o c o l 0 b M a x P a c k e t S i z e 0 8 i d V e n d o r 0 x 0 0 0 0 i d P r o d u c t 0 x 0 0 0 0 ...

lspci Lists pci busses present.


b a s h $l s p c i

0 0 : 0 0 . 0H o s tb r i d g e :I n t e lC o r p o r a t i o n8 2 8 4 58 4 5 ( B r o o k d a l e )C h i p s e tH o s tB r i d g e( r e v0 4 ) 0 0 : 0 1 . 0P C Ib r i d g e :I n t e lC o r p o r a t i o n8 2 8 4 58 4 5 ( B r o o k d a l e )C h i p s e tA G PB r i d g e( r e v0 4 ) 0 0 : 1 d . 0U S BC o n t r o l l e r :I n t e lC o r p o r a t i o n8 2 8 0 1 C A / C A MU S B( H u b# 1 )( r e v0 2 ) 0 0 : 1 d . 1U S BC o n t r o l l e r :I n t e lC o r p o r a t i o n8 2 8 0 1 C A / C A MU S B( H u b# 2 )( r e v0 2 ) 0 0 : 1 d . 2U S BC o n t r o l l e r :I n t e lC o r p o r a t i o n8 2 8 0 1 C A / C A MU S B( H u b# 3 )( r e v0 2 ) 0 0 : 1 e . 0P C Ib r i d g e :I n t e lC o r p o r a t i o n8 2 8 0 1M o b i l eP C IB r i d g e( r e v4 2 ) ...

mkbootdisk Creates a boot floppy which can be used to bring up the system if, for example, the MBR (master boot record) becomes corrupted. Of special interest is the i s ooption, which uses mkisofs to create a bootable ISO9660 filesystem image suitable for burning a bootable CDR. The mkbootdisk command is actually a Bash script, written by Erik Troan, in the / s b i ndirectory. mkisofs Creates an ISO9660 filesystem suitable for a CDR image. chroot CHange ROOT directory. Normally commands are fetched from $PATH, relative to / , the default root directory. This changes the root directory to a different one (and also changes the working directory to there). This is useful for security purposes, for instance when the system administrator wishes to restrict certain users, such as those telnetting in, to a secured portion of the filesystem (this is sometimes referred to as confining a guest user to a "chroot jail"). Note that after a chroot, the execution path for system binaries is no longer valid. Ac h r o o t/ o p twould cause references to / u s r / b i nto be translated to / o p t / u s r / b i n . Likewise, c h r o o t / a a a / b b b/ b i n / l swould redirect future instances of ls to / a a a / b b bas the base directory, rather than /as is normally the case. An alias XX 'chroot /aaa/bbb ls' in a user's ~ / . b a s h r ceffectively restricts which portion of the filesystem she may run command "XX" on. The chroot command is also handy when running from an emergency boot floppy (chroot to / d e v / f d 0 ), or as an option to lilo when recovering from a system crash. Other uses include installation from a different filesystem (an rpm option) or running a readonly filesystem from a CD ROM. Invoke only as root , and use with care. It might be necessary to copy certain system files to a chrooted directory, since the normal $ P A T H can no longer be relied upon. lockfile This utility is part of the procmail package (www.procmail.org). It creates a lock file, a semaphore that controls access to a file, device, or resource.
D e f i n i t i o n :A semaphore is a flag or signal.

(The usage originated in railroading, where a colored flag, lantern, or striped movable arm semaphore indicated whether a particular track was in use and therefore unavailable for another train.) A UNIX process can check the appropriate semaphore to determine whether a particular resource is available/accessible. The lock file serves as a flag that this particular file, device, or resource is in use by a process (and is therefore "busy"). The presence of a lock file permits only restricted access (or no access) to other processes.
l o c k f i l e/ h o m e / b o z o / l o c k f i l e s / $ 0 . l o c k #C r e a t e saw r i t e p r o t e c t e dl o c k f i l ep r e f i x e dw i t ht h en a m eo ft h es c r i p t .

l o c k f i l e/ h o m e / b o z o / l o c k f i l e s / $ { 0 # # * / } . l o c k #As a f e rv e r s i o no ft h ea b o v e ,a sp o i n t e do u tb yE .C h o r o b a .

Lock files are used in such applications as protecting system mail folders from simultaneously being changed by multiple users, indicating that a modem port is being accessed, and showing that an instance of Firefox is using its cache. Scripts may check for the existence of a lock file created by a certain process to check if that process is running. Note that if a script attempts to create a lock file that already exists, the script will likely hang. Normally, applications create and check for lock files in the / v a r / l o c kdirectory. [92] A script can test for the presence of a lock file by something like the following.
a p p n a m e = x y z i p #A p p l i c a t i o n" x y z i p "c r e a t e dl o c kf i l e" / v a r / l o c k / x y z i p . l o c k " . i f[e" / v a r / l o c k / $ a p p n a m e . l o c k "] t h e n # +P r e v e n to t h e rp r o g r a m s&s c r i p t s # f r o ma c c e s s i n gf i l e s / r e s o u r c e su s e db yx y z i p . . . .

flock Much less useful than the lockfile command is flock. It sets an "advisory" lock on a file and then executes a command while the lock is on. This is to prevent any other process from setting a lock on that file until completion of the specified command.
f l o c k$ 0c a t$ 0>l o c k f i l e _ _ $ 0 # S e tal o c ko nt h es c r i p tt h ea b o v el i n ea p p e a r si n , # +w h i l el i s t i n gt h es c r i p tt os t d o u t .

Unlike lockfile , flock does not automatically create a lock file. mknod Creates block or character device files (may be necessary when installing new hardware on the system). The MAKEDEV utility has virtually all of the functionality of mknod, and is easier to use. MAKEDEV Utility for creating device files. It must be run as root , and in the / d e vdirectory. It is a sort of advanced version of mknod. tmpwatch Automatically deletes files which have not been accessed within a specified period of time. Usually invoked by cron to remove stale log files. Backup dump, restore The dump command is an elaborate filesystem backup utility, generally used on larger installations and networks. [93] It reads raw disk partitions and writes a backup file in a binary format. Files to be backed up may be saved to a variety of storage media, including disks and tape drives. The restore command restores backups made with dump. fdformat Perform a low-level format on a floppy disk (/ d e v / f d 0 * ). System Resources ulimit

Sets an upper limit on use of system resources. Usually invoked with the foption, which sets a limit on file size (ulimit -f 1000 limits files to 1 meg maximum). [94] The toption limits the coredump size (ulimit -c 0 eliminates coredumps). Normally, the value of ulimit would be set in / e t c / p r o f i l eand/or ~ / . b a s h _ p r o f i l e(see Appendix H). Judicious use of ulimit can protect a system against the dreaded fork bomb.
# ! / b i n / b a s h #T h i ss c r i p ti sf o ri l l u s t r a t i v ep u r p o s e so n l y . #R u ni ta ty o u ro w np e r i l-i tW I L Lf r e e z ey o u rs y s t e m . w h i l et r u e # E n d l e s sl o o p . d o $ 0& # T h i ss c r i p ti n v o k e si t s e l f... # +f o r k sa ni n f i n i t en u m b e ro ft i m e s... # +u n t i lt h es y s t e mf r e e z e su pb e c a u s ea l lr e s o u r c e se x h a u s t e d . d o n e # T h i si st h en o t o r i o u s" s o r c e r e r ' sa p p e n t i c e "s c e n a r i o . e x i t0 # W i l ln o te x i th e r e ,b e c a u s et h i ss c r i p tw i l ln e v e rt e r m i n a t e .

A ulimit -Hu XX (where XX is the user process limit) in / e t c / p r o f i l ewould abort this script when it exceeded the preset limit. quota Display user or group disk quotas. setquota Set user or group disk quotas from the command-line. umask User file creation permissions mask . Limit the default file attributes for a particular user. All files created by that user take on the attributes specified by umask. The (octal) value passed to umask defines the file permissions disabled. For example, umask 022 ensures that new files will have at most 755 permissions (777 NAND 022). [95] Of course, the user may later change the attributes of particular files with chmod. The usual practice is to set the value of umask in / e t c / p r o f i l eand/or ~ / . b a s h _ p r o f i l e(see Appendix H). Example 17-10. Using umask to hide an output file from prying eyes
# ! / b i n / b a s h #r o t 1 3 a . s h :S a m ea s" r o t 1 3 . s h "s c r i p t ,b u tw r i t e so u t p u tt o" s e c u r e "f i l e . #U s a g e :. / r o t 1 3 a . s hf i l e n a m e #o r . / r o t 1 3 a . s h< f i l e n a m e #o r . / r o t 1 3 a . s ha n ds u p p l yk e y b o a r di n p u t( s t d i n ) u m a s k1 7 7 # F i l ec r e a t i o nm a s k . # F i l e sc r e a t e db yt h i ss c r i p t # +w i l lh a v e6 0 0p e r m i s s i o n s . # R e s u l t so u t p u tt of i l e" d e c r y p t e d . t x t " # +w h i c hc a no n l yb er e a d / w r i t t e n # b yi n v o k e ro fs c r i p t( o rr o o t ) .

O U T F I L E = d e c r y p t e d . t x t

c a t" $ @ "|t r' a z A Z '' n z a m N Z A M '>$ O U T F I L E # ^ ^I n p u tf r o ms t d i no raf i l e . ^ ^ ^ ^ ^ ^ ^ ^ ^ ^O u t p u tr e d i r e c t e dt of i l e . e x i t0

rdev Get info about or make changes to root device, swap space, or video mode. The functionality of rdev has generally been taken over by lilo, but rdev remains useful for setting up a ram disk. This is a dangerous command, if misused.

Modules lsmod List installed kernel modules.


b a s h $l s m o d M o d u l e a u t o f s o p l 3 s e r i a l _ c s s b u a r t 4 0 1 s o u n d s o u n d l o w s o u n d c o r e d s i 8 2 3 6 5 p c m c i a _ c o r e S i z e U s e db y 9 4 5 6 2( a u t o c l e a n ) 1 1 3 7 6 0 5 4 5 6 0( u n u s e d ) 3 4 7 5 2 0 6 3 8 4 0[ s b ] 5 8 3 6 8 0[ o p l 3s bu a r t 4 0 1 ] 4 6 4 0[ s o u n d ] 2 8 0 0 6[ s bs o u n d ] 6 4 4 8 2[ s e r i a l _ c s ] 2 2 9 2 8 2 4 5 9 8 4 0[ s e r i a l _ c sd si 8 2 3 6 5 ]

Doing a cat /proc/modules gives the same information. insmod Force installation of a kernel module (use modprobe instead, when possible). Must be invoked as root . rmmod Force unloading of a kernel module. Must be invoked as root . modprobe Module loader that is normally invoked automatically in a startup script. Must be invoked as root . depmod Creates module dependency file. Usually invoked from a startup script. modinfo Output information about a loadable module.
b a s h $m o d i n f oh i d f i l e n a m e : / l i b / m o d u l e s / 2 . 4 . 2 0 6 / k e r n e l / d r i v e r s / u s b / h i d . o d e s c r i p t i o n :" U S BH I Ds u p p o r td r i v e r s " a u t h o r : " A n d r e a sG a l ,V o j t e c hP a v l i k< v o j t e c h @ s u s e . c z > " l i c e n s e : " G P L "

Miscellaneous env Runs a program or script with certain environmental variables set or changed (without changing the overall system environment). The [ v a r n a m e = x x x ]permits changing the environmental variable v a r n a m efor the duration of the script. With no options specified, this command lists all the environmental variable settings. [96] The first line of a script (the "sha-bang" line) may use env when the path to the shell or interpreter is unknown.
# !/ u s r / b i n / e n vp e r l

p r i n t" T h i sP e r ls c r i p tw i l lr u n , \ n " ; p r i n t" e v e nw h e nId o n ' tk n o ww h e r et of i n dP e r l . \ n " ; #G o o df o rp o r t a b l ec r o s s p l a t f o r ms c r i p t s , #w h e r et h eP e r lb i n a r i e sm a yn o tb ei nt h ee x p e c t e dp l a c e . #T h a n k s ,S . C .

Or even ...
# ! / b i n / e n vb a s h #Q u e r i e st h e$ P A T He n v i r o m e n t a lv a r i a b l ef o rt h el o c a t i o no fb a s h . #T h e r e f o r e. . . #T h i ss c r i p tw i l lr u nw h e r eB a s hi sn o ti ni t su s u a lp l a c e ,i n/ b i n . . . .

ldd Show shared lib dependencies for an executable file.


b a s h $l d d/ b i n / l s l i b c . s o . 6= >/ l i b / l i b c . s o . 6( 0 x 4 0 0 0 c 0 0 0 ) / l i b / l d l i n u x . s o . 2= >/ l i b / l d l i n u x . s o . 2( 0 x 8 0 0 0 0 0 0 0 )

watch Run a command repeatedly, at specified time intervals. The default is two-second intervals, but this may be changed with the noption.
w a t c hn5t a i l/ v a r / l o g / m e s s a g e s #S h o w st a i le n do fs y s t e ml o g ,/ v a r / l o g / m e s s a g e s ,e v e r yf i v es e c o n d s .

Unfortunately, piping the output of watch command to grep does not work. strip Remove the debugging symbolic references from an executable binary. This decreases its size, but makes debugging it impossible. This command often occurs in a Makefile, but rarely in a shell script. nm List symbols in an unstripped compiled binary. xrandr Command-line tool for manipulating the root window of the screen. Example 17-11. Backlight : changes the brightness of the (laptop) screen backlight
# ! / b i n / b a s h #b a c k l i g h t . s h #r e l d a t e0 2 d e c 2 0 1 1 # Ab u gi nF e d o r aC o r e1 6 / 1 7m e s s e su pt h ek e y b o a r db a c k l i g h tc o n t r o l s . # T h i ss c r i p ti saq u i c k n d i r t yw o r k a r o u n d ,e s s e n t i a l l yas h e l lw r a p p e r # +f o rx r a n d r .I tg i v e sm o r ec o n t r o lt h a no n s c r e e ns l i d e r sa n dw i d g e t s . O U T P U T = $ ( x r a n d r|g r e pL V|a w k' { p r i n t$ 1 } ' ) #G e td i s p l a yn a m e ! I N C R = . 0 5 #F o rf i n e r g r a i n e dc o n t r o l ,s e tI N C Rt o. 0 3o r. 0 2 . o l d _ b r i g h t n e s s = $ ( x r a n d rv e r b o s e|g r e pr i g h t n e s s|a w k' {p r i n t$ 2} ' )

i f[z" $ 1 "] t h e n b r i g h t = 1 #I fn oc o m m a n d l i n ea r g ,s e tb r i g h t n e s st o1 . 0( d e f a u l t ) . e l s e i f[" $ 1 "=" + "] t h e n b r i g h t = $ ( e c h o" s c a l e = 2 ;$ o l d _ b r i g h t n e s s+$ I N C R "|b c ) e l s e i f[" $ 1 "=" "] t h e n b r i g h t = $ ( e c h o" s c a l e = 2 ;$ o l d _ b r i g h t n e s s-$ I N C R "|b c )

#+ . 0 5

#. 0 5

e l s e i f[" $ 1 "=" # "] #E c h o e sc u r r e n tb r i g h t n e s s ;d o e sn o tc h a n g ei t . t h e n b r i g h t = $ o l d _ b r i g h t n e s s e l s e i f[ [" $ 1 "=" h "| |" $ 1 "=" H "] ] t h e n e c h o e c h o" U s a g e : " e c h o" $ 0[ N oa r g s ] S e t s / r e s e t sb r i g h t n e s st od e f a u l t( 1 . 0 ) . " e c h o" $ 0+ I n c r e m e n t sb r i g h t n e s sb y0 . 5 . " e c h o" $ 0D e c r e m e n t sb r i g h t n e s sb y0 . 5 . " e c h o" $ 0# E c h o e sc u r r e n tb r i g h t n e s sw i t h o u tc h a n g i n gi t . " e c h o" $ 0N( n u m b e r ) S e t sb r i g h t n e s st oN( u s e f u lr a n g e. 7-1 . 2 ) . " e c h o" $ 0h[ H ] E c h o e st h i sh e l pm e s s a g e . " e c h o" $ 0a n y o t h e r G i v e sx r a n d ru s a g em e s s a g e . " b r i g h t = $ o l d _ b r i g h t n e s s e l s e b r i g h t = " $ 1 " f i f i f i f i f i

x r a n d ro u t p u t" $ O U T P U T "b r i g h t n e s s" $ b r i g h t " E _ C H A N G E 0 = $ ? e c h o" C u r r e n tb r i g h t n e s s=$ b r i g h t " e x i t$ E _ C H A N G E 0

#S e ex r a n d rm a n p a g e . #A sr o o t !

#= = = = = = = = = = =O r ,a l t e r n a t e l y...= = = = = = = = = = = = = = = = = = = =# # ! / b i n / b a s h #b a c k l i g h t 2 . s h #r e l d a t e2 0 j u n 2 0 1 2 # Ab u gi nF e d o r aC o r e1 6 / 1 7m e s s e su pt h ek e y b o a r db a c k l i g h tc o n t r o l s . # T h i si saq u i c k n d i r t yw o r k a r o u n d ,a na l t e r n a t et ob a c k l i g h t . s h . t a r g e t _ d i r = \ / s y s / d e v i c e s / p c i 0 0 0 0 : 0 0 / 0 0 0 0 : 0 0 : 0 1 . 0 / 0 0 0 0 : 0 1 : 0 0 . 0 / b a c k l i g h t / a c p i _ v i d e o 0 #H a r d w a r ed i r e c t o r y . a c t u a l _ b r i g h t n e s s = $ ( c a t$ t a r g e t _ d i r / a c t u a l _ b r i g h t n e s s ) m a x _ b r i g h t n e s s = $ ( c a t$ t a r g e t _ d i r / m a x _ b r i g h t n e s s ) B r i g h t n e s s = $ t a r g e t _ d i r / b r i g h t n e s s

l e t" r e q _ b r i g h t n e s s=a c t u a l _ b r i g h t n e s s "

#R e q u e s t e db r i g h t n e s s .

i f[" $ 1 "=" "] t h e n #D e c r e m e n tb r i g h t n e s s1n o t c h . l e t" r e q _ b r i g h t n e s s=$ a c t u a l _ b r i g h t n e s s-1 " e l s e i f[" $ 1 "=" + "] t h e n #I n c r e m e n tb r i g h t n e s s1n o t c h . l e t" r e q _ b r i g h t n e s s=$ a c t u a l _ b r i g h t n e s s+1 " f i f i i f[$ r e q _ b r i g h t n e s sg t$ m a x _ b r i g h t n e s s] t h e n r e q _ b r i g h t n e s s = $ m a x _ b r i g h t n e s s f i #D on o te x c e e dm a x .h a r d w a r ed e s i g nb r i g h t n e s s . e c h o e c h o" O l db r i g h t n e s s=$ a c t u a l _ b r i g h t n e s s " e c h o" M a xb r i g h t n e s s=$ m a x _ b r i g h t n e s s " e c h o" R e q u e s t e db r i g h t n e s s=$ r e q _ b r i g h t n e s s " e c h o #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = e c h o$ r e q _ b r i g h t n e s s>$ B r i g h t n e s s #M u s tb er o o tf o rt h i st ot a k ee f f e c t . E _ C H A N G E 1 = $ ? #S u c c e s s f u l ? #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = i f[" $ ? "e q0] t h e n e c h o" C h a n g e db r i g h t n e s s ! " e l s e e c h o" F a i l e dt oc h a n g eb r i g h t n e s s ! " f i a c t _ b r i g h t n e s s = $ ( c a t$ B r i g h t n e s s ) e c h o" A c t u a lb r i g h t n e s s=$ a c t _ b r i g h t n e s s " s c a l e 0 = 2 s f = 1 0 0#S c a l ef a c t o r . p c t = $ ( e c h o" s c a l e = $ s c a l e 0 ;$ a c t _ b r i g h t n e s s/$ m a x _ b r i g h t n e s s*$ s f "|b c ) e c h o" P e r c e n t a g eb r i g h t n e s s=$ p c t % " e x i t$ E _ C H A N G E 1

rdist Remote distribution client: synchronizes, clones, or backs up a file system on a remote server.

17.1. Analyzing a System Script


Using our knowledge of administrative commands, let us examine a system script. One of the shortest and simplest to understand scripts is "killall," [97] used to suspend running processes at system shutdown. Example 17-12. killall , from / e t c / r c . d / i n i t . d
# ! / b i n / s h #>C o m m e n t sa d d e db yt h ea u t h o ro ft h i sd o c u m e n tm a r k e db y" #> " . #>T h i si sp a r to ft h e' r c 's c r i p tp a c k a g e #>b yM i q u e lv a nS m o o r e n b u r g ,< m i q u e l s @ d r i n k e l . n l . m u g n e t . o r g > .

#>T h i sp a r t i c u l a rs c r i p ts e e m st ob eR e dH a t/F Cs p e c i f i c #>( m a yn o tb ep r e s e n ti no t h e rd i s t r i b u t i o n s ) . # B r i n gd o w na l lu n n e e d e ds e r v i c e st h a ta r es t i l lr u n n i n g # +( t h e r es h o u l d n ' tb ea n y ,s ot h i si sj u s tas a n i t yc h e c k ) f o rii n/ v a r / l o c k / s u b s y s / * ;d o #>S t a n d a r df o r / i nl o o p ,b u ts i n c e" d o "i so ns a m el i n e , #>i ti sn e c e s s a r yt oa d d" ; " . #C h e c ki ft h es c r i p ti st h e r e . [!f$ i]& &c o n t i n u e #>T h i si sac l e v e ru s eo fa n" a n dl i s t " ,e q u i v a l e n tt o : #>i f[!f" $ i "] ;t h e nc o n t i n u e #G e tt h es u b s y s t e mn a m e . s u b s y s = $ { i # / v a r / l o c k / s u b s y s / } #>M a t c hv a r i a b l en a m e ,w h i c h ,i nt h i sc a s e ,i st h ef i l en a m e . #>T h i si st h ee x a c te q u i v a l e n to fs u b s y s = ` b a s e n a m e$ i ` . #> I tg e t si tf r o mt h el o c kf i l en a m e #> +( i ft h e r ei sal o c kf i l e , #> +t h a t ' sp r o o ft h ep r o c e s sh a sb e e nr u n n i n g ) . #> S e et h e" l o c k f i l e "e n t r y ,a b o v e .

#B r i n gt h es u b s y s t e md o w n . i f[f/ e t c / r c . d / i n i t . d / $ s u b s y s . i n i t] ;t h e n / e t c / r c . d / i n i t . d / $ s u b s y s . i n i ts t o p e l s e / e t c / r c . d / i n i t . d / $ s u b s y ss t o p #> S u s p e n dr u n n i n gj o b sa n dd a e m o n s . #> N o t et h a t" s t o p "i sap o s i t i o n a lp a r a m e t e r , #> +n o tas h e l lb u i l t i n . f i d o n e

That wasn't so bad. Aside from a little fancy footwork with variable matching, there is no new material there. Exercise 1. In / e t c / r c . d / i n i t . d , analyze the halt script. It is a bit longer than killall, but similar in concept. Make a copy of this script somewhere in your home directory and experiment with it (do not run it as root ). Do a simulated run with the v nflags (s hv ns c r i p t n a m e ). Add extensive comments. Change the commands to echos. Exercise 2. Look at some of the more complex scripts in / e t c / r c . d / i n i t . d . Try to understand at least portions of them. Follow the above procedure to analyze them. For some additional insight, you might also examine the file s y s v i n i t f i l e s in / u s r / s h a r e / d o c / i n i t s c r i p t s ? . ? ? , which is part of the "initscripts" documentation.

Part 5. Advanced Topics


At this point, we are ready to delve into certain of the difficult and unusual aspects of scripting. Along the way, we will attempt to "push the envelope" in various ways and examine boundary conditions (what happens when we move into uncharted territory?). Table of Contents 18. Regular Expressions 18.1. A Brief Introduction to Regular Expressions 18.2. Globbing 19. Here Documents 19.1. Here Strings

20. I/O Redirection 20.1. Using exec 20.2. Redirecting Code Blocks 20.3. Applications 21. Subshells 22. Restricted Shells 23. Process Substitution 24. Functions 24.1. Complex Functions and Function Complexities 24.2. Local Variables 24.3. Recursion Without Local Variables 25. Aliases 26. List Constructs 27. Arrays 28. Indirect References 29. / d e vand / p r o c 29.1. / d e v 29.2. / p r o c 30. Network Programming 31. Of Zeros and Nulls 32. Debugging 33. Options 34. Gotchas 35. Scripting With Style 35.1. Unofficial Shell Scripting Stylesheet 36. Miscellany 36.1. Interactive and non-interactive shells and scripts 36.2. Shell Wrappers 36.3. Tests and Comparisons: Alternatives 36.4. Recursion: a script calling itself 36.5. "Colorizing" Scripts 36.6. Optimizations 36.7. Assorted Tips 36.8. Security Issues 36.9. Portability Issues 36.10. Shell Scripting Under Windows 37. Bash, versions 2, 3, and 4 37.1. Bash, version 2 37.2. Bash, version 3 37.3. Bash, version 4

Chapter 18. Regular Expressions


. . . the intellectual activity associated with software

development is largely one of gaining insight. --Stowe Boyd To fully utilize the power of shell scripting, you need to master Regular Expressions. Certain commands and utilities commonly used in scripts, such as grep, expr, sed and awk, interpret and use REs. As of version 3, Bash has acquired its own RE-match operator: =~.

18.1. A Brief Introduction to Regular Expressions


An expression is a string of characters. Those characters having an interpretation above and beyond their literal meaning are called metacharacters. A quote symbol, for example, may denote speech by a person, ditto, or a meta-meaning [98] for the symbols that follow. Regular Expressions are sets of characters and/or metacharacters that match (or specify) patterns. A Regular Expression contains one or more of the following: A character set . These are the characters retaining their literal meaning. The simplest type of Regular Expression consists only of a character set, with no metacharacters. An anchor. These designate (anchor) the position in the line of text that the RE is to match. For example, ^, and $ are anchors. Modifiers. These expand or narrow (modify) the range of text the RE is to match. Modifiers include the asterisk, brackets, and the backslash. The main uses for Regular Expressions (REs) are text searches and string manipulation. An RE matches a single character or a set of characters -- a string or a part of a string. The asterisk -- * -- matches any number of repeats of the character string or RE preceding it, including zero instances. "1133*" matches 1 1+o n eo rm o r e3 ' s :1 1 3 ,1 1 3 3 ,1 1 3 3 3 3 3 , and so forth. The dot -- . -- matches any one character, except a newline. [99] "13." matches 1 3+a tl e a s to n eo fa n yc h a r a c t e r( i n c l u d i n gas p a c e ) :1 1 3 3 ,1 1 3 3 3 , but not 1 3 (additional character missing). See Example 16-18 for a demonstration of dot single-character matching. The caret -- ^ -- matches the beginning of a line, but sometimes, depending on context, negates the meaning of a set of characters in an RE. The dollar sign -- $ -- at the end of an RE matches the end of a line. "XXX$" matches XXX at the end of a line. "^$" matches blank lines. Brackets -- [...] -- enclose a set of characters to match in a single RE. "[xyz]" matches any one of the characters x ,y , or z . "[c-n]" matches any one of the characters in the range cto n . "[B-Pk-y]" matches any one of the characters in the ranges Bto Pand kto y .

"[a-z0-9]" matches any single lowercase letter or any digit. "[^b-d]" matches any character except those in the range bto d . This is an instance of ^ negating or inverting the meaning of the following RE (taking on a role similar to ! in a different context). Combined sequences of bracketed characters match common word patterns. "[Yy][Ee][Ss]" matches y e s ,Y e s ,Y E S , y E s , and so forth. "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" matches any Social Security number. The backslash -- \ -- escapes a special character, which means that character gets interpreted literally (and is therefore no longer special). A "\$" reverts back to its literal meaning of "$", rather than its RE meaning of end-of-line. Likewise a "\\" has the literal meaning of "\". Escaped "angle brackets" -- \<...\> -- mark word boundaries. The angle brackets must be escaped, since otherwise they have only their literal character meaning. "\<the\>" matches the word "the," but not the words "them," "there," "other," etc.
b a s h $c a tt e x t f i l e T h i si sl i n e1 ,o fw h i c ht h e r ei so n l yo n ei n s t a n c e . T h i si st h eo n l yi n s t a n c eo fl i n e2 . T h i si sl i n e3 ,a n o t h e rl i n e . T h i si sl i n e4 .

b a s h $g r e p' t h e 't e x t f i l e T h i si sl i n e1 ,o fw h i c ht h e r ei so n l yo n ei n s t a n c e . T h i si st h eo n l yi n s t a n c eo fl i n e2 . T h i si sl i n e3 ,a n o t h e rl i n e .

b a s h $g r e p' \ < t h e \ > 't e x t f i l e T h i si st h eo n l yi n s t a n c eo fl i n e2 .

The only way to be certain that a particular RE works is to test it.


T E S TF I L E :t s t f i l e R u n g r e p" 1 1 3 3 * " o nt h i sf i l e . #N om a t c h . #N om a t c h . #M a t c h . #N om a t c h . #N om a t c h . #M a t c h . #N om a t c h . #N om a t c h . #M a t c h . #M a t c h . #N om a t c h . #M a t c h . #N om a t c h .

T h i sl i n ec o n t a i n st h en u m b e r1 1 3 . T h i sl i n ec o n t a i n st h en u m b e r1 3 . T h i sl i n ec o n t a i n st h en u m b e r1 3 3 . T h i sl i n ec o n t a i n st h en u m b e r1 1 3 3 . T h i sl i n ec o n t a i n st h en u m b e r1 1 3 3 1 2 . T h i sl i n ec o n t a i n st h en u m b e r1 1 1 2 . T h i sl i n ec o n t a i n st h en u m b e r1 1 3 3 1 2 3 1 2 . T h i sl i n ec o n t a i n sn on u m b e r sa ta l l . b a s h $g r e p" 1 1 3 3 * "t s t f i l e R u n g r e p" 1 1 3 3 * " o nt h i sf i l e . T h i sl i n ec o n t a i n st h en u m b e r1 1 3 . T h i sl i n ec o n t a i n st h en u m b e r1 1 3 3 . T h i sl i n ec o n t a i n st h en u m b e r1 1 3 3 1 2 . T h i sl i n ec o n t a i n st h en u m b e r1 1 3 3 1 2 3 1 2 .

#M a t c h . #M a t c h . #M a t c h . #M a t c h . #M a t c h .

Extended REs. Additional metacharacters added to the basic set. Used in egrep, awk, and Perl.

The question mark -- ? -- matches zero or one of the previous RE. It is generally used for matching single characters. The plus -- + -- matches one or more of the previous RE. It serves a role similar to the *, but does not match zero occurrences.
#G N Uv e r s i o n so fs e da n da w kc a nu s e" + " , #b u ti tn e e d st ob ee s c a p e d . e c h oa 1 1 1 b|s e dn e' / a 1 \ + b / p ' e c h oa 1 1 1 b|g r e p' a 1 \ + b ' e c h oa 1 1 1 b|g a w k' / a 1 + b / ' #A l lo fa b o v ea r ee q u i v a l e n t . #T h a n k s ,S . C .

Escaped "curly brackets" -- \{ \} -- indicate the number of occurrences of a preceding RE to match. It is necessary to escape the curly brackets since they have only their literal character meaning otherwise. This usage is technically not part of the basic RE set. "[0-9]\{5\}" matches exactly five digits (characters in the range of 0 to 9). Curly brackets are not available as an RE in the "classic" (non-POSIX compliant) version of awk. However, the GNU extended version of awk , gawk, has the r e i n t e r v a loption that permits them (without being escaped).
b a s h $e c h o2 2 2 2|g a w kr e i n t e r v a l' / 2 { 3 } / ' 2 2 2 2

Perl and some egrep versions do not require escaping the curly brackets. Parentheses -- ( ) -- enclose a group of REs. They are useful with the following "|" operator and in substring extraction using expr. The -- | -- "or" RE operator matches any of a set of alternate characters.
b a s h $e g r e p' r e ( a | e ) d 'm i s c . t x t P e o p l ew h or e a ds e e mt ob eb e t t e ri n f o r m e dt h a nt h o s ew h od on o t . T h ec l a r i n e tp r o d u c e ss o u n db yt h ev i b r a t i o no fi t sr e e d .

Some versions of sed, ed, and ex support escaped versions of the extended Regular Expressions described above, as do the GNU utilities. POSIX Character Classes. [ : c l a s s : ] This is an alternate method of specifying a range of characters to match.
[ : a l n u m : ]matches alphabetic or numeric characters. [ : a l p h a : ]matches alphabetic characters. [ : b l a n k : ]matches a space or a tab. [ : c n t r l : ]matches control characters. [ : d i g i t : ]matches (decimal) digits.

This is equivalent to A Z a z 0 9 .

This is equivalent to A Z a z .

This is equivalent to 0 9 . Matches characters in the range of ASCII 33 - 126. This is the same as

[ : g r a p h : ](graphic printable characters).

[ : p r i n t : ] , below,

but excluding the space character. This is equivalent to a z .

[ : l o w e r : ]matches lowercase alphabetic characters. [ : p r i n t : ](printable characters).

Matches characters in the range of ASCII 32 - 126. This is the same as [ : g r a p h : ] , above, but adding the space character.
[ : s p a c e : ]matches whitespace characters (space and [ : u p p e r : ]matches uppercase alphabetic characters. [ : x d i g i t : ]matches hexadecimal digits.

horizontal tab).

This is equivalent to A Z .

This is equivalent to 0 9 A F a f .

POSIX character classes generally require quoting or double brackets ([[ ]]).
b a s h $g r e p[ [ : d i g i t : ] ]t e s t . f i l e a b c = 7 2 3

#. . . i f[ [$ a r o w= ~[ [ : d i g i t : ] ]] ] # N u m e r i c a li n p u t ? t h e n # P O S I Xc h a rc l a s s i f[ [$ a c o l= ~[ [ : a l p h a : ] ]] ]#N u m b e rf o l l o w e db yal e t t e r ?I l l e g a l ! #. . . #F r o mk t o u r . s he x a m p l es c r i p t .

These character classes may even be used with globbing, to a limited extent.
b a s h $l sl? [ [ : d i g i t : ] ] [ [ : d i g i t : ] ] ? r w r w r 1b o z o b o z o 0A u g2 11 4 : 4 7a 3 3 b

POSIX character classes are used in Example 16-21 and Example 16-22. Sed, awk, and Perl, used as filters in scripts, take REs as arguments when "sifting" or transforming files or I/O streams. See Example A-12 and Example A-16 for illustrations of this. The standard reference on this complex topic is Friedl's Mastering Regular Expressions. Sed & Awk , by Dougherty and Robbins, also gives a very lucid treatment of REs. See the Bibliography for more information on these books.

18.2. Globbing
Bash itself cannot recognize Regular Expressions. Inside scripts, it is commands and utilities -- such as sed and awk -- that interpret RE's. Bash does carry out filename expansion [100] -- a process known as globbing -- but this does not use the standard RE set. Instead, globbing recognizes and expands wild cards. Globbing interprets the standard wild card characters [101] -- * and ?, character lists in square brackets, and certain other special characters (such as ^ for negating the sense of a match). There are important limitations on wild card characters in globbing, however. Strings containing *will not match filenames that start with a dot, as, for example, . b a s h r c . [102] Likewise, the ?has a different meaning in globbing than as part of an RE.
b a s h $l sl t o t a l2 r w r w r r w r w r r w r w r r w r w r -

1b o z o 1b o z o 1b o z o 1b o z o

b o z o b o z o b o z o b o z o

0A u g 0A u g 0A u g 4 6 6A u g

61 8 : 4 2a . 1 61 8 : 4 2b . 1 61 8 : 4 2c . 1 61 7 : 4 8t 2 . s h

r w r w r -

1b o z o b o z o

7 5 8J u l3 00 9 : 0 2t e s t 1 . t x t

b a s h $l slt ? . s h r w r w r 1b o z o b o z o b a s h $l sl[ a b ] * r w r w r 1b o z o b o z o r w r w r 1b o z o b o z o b a s h $l sl[ a c ] * r w r w r 1b o z o b o z o r w r w r 1b o z o b o z o r w r w r 1b o z o b o z o b a s h $l sl[ ^ a b ] * r w r w r 1b o z o b o z o r w r w r 1b o z o b o z o r w r w r 1b o z o b o z o b a s h $l sl{ b * , c * , * e s t * } r w r w r 1b o z o b o z o r w r w r 1b o z o b o z o r w r w r 1b o z o b o z o

4 6 6A u g 61 7 : 4 8t 2 . s h

0A u g 61 8 : 4 2a . 1 0A u g 61 8 : 4 2b . 1

0A u g 61 8 : 4 2a . 1 0A u g 61 8 : 4 2b . 1 0A u g 61 8 : 4 2c . 1

0A u g 61 8 : 4 2c . 1 4 6 6A u g 61 7 : 4 8t 2 . s h 7 5 8J u l3 00 9 : 0 2t e s t 1 . t x t

0A u g 61 8 : 4 2b . 1 0A u g 61 8 : 4 2c . 1 7 5 8J u l3 00 9 : 0 2t e s t 1 . t x t

Bash performs filename expansion on unquoted command-line arguments. The echo command demonstrates this.
b a s h $e c h o* a . 1b . 1c . 1t 2 . s ht e s t 1 . t x t b a s h $e c h ot * t 2 . s ht e s t 1 . t x t b a s h $e c h ot ? . s h t 2 . s h

It is possible to modify the way Bash interprets special characters in globbing. A set -f command disables globbing, and the n o c a s e g l o band n u l l g l o boptions to shopt change globbing behavior. See also Example 11-4. Filenames with embedded whitespace can cause globbing to choke. David Wheeler shows how to avoid many such pitfalls.
I F S = " $ ( p r i n t f' \ n \ t ' ) " #R e m o v es p a c e .

# C o r r e c tg l o bu s e : # A l w a y su s ef o r l o o p ,p r e f i xg l o b ,c h e c ki fe x i s t sf i l e . f o rf i l ei n. / *;d o #U s e. / *. . .N E V E Rb a r e* i f[e" $ f i l e "];t h e n #C h e c kw h e t h e rf i l ee x i s t s . C O M M A N D. . ." $ f i l e ". . . f i d o n e #T h i se x a m p l et a k e nf r o mD a v i dW h e e l e r ' ss i t e ,w i t hp e r m i s s i o n .

Chapter 19. Here Documents


Here and now, boys.

--Aldous Huxley, Island A here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command, such as ftp, cat, or the ex text editor.
C O M M A N D< < I n p u t C o m e s F r o m H E R E . . . . . . . . . I n p u t C o m e s F r o m H E R E

A limit string delineates (frames) the command list. The special symbol << precedes the limit string. This has the effect of redirecting the output of a command block into the s t d i nof the program or command. It is similar to i n t e r a c t i v e p r o g r a m<c o m m a n d f i l e , where c o m m a n d f i l econtains
c o m m a n d# 1 c o m m a n d# 2 . . .

The here document equivalent looks like this:


i n t e r a c t i v e p r o g r a m< < L i m i t S t r i n g c o m m a n d# 1 c o m m a n d# 2 . . . L i m i t S t r i n g

Choose a limit string sufficiently unusual that it will not occur anywhere in the command list and confuse matters. Note that here documents may sometimes be used to good effect with non-interactive utilities and commands, such as, for example, wall. Example 19-1. broadcast : Sends message to everyone logged in
# ! / b i n / b a s h w a l l< < z z z 2 3 E n d O f M e s s a g e z z z 2 3 E m a i ly o u rn o o n t i m eo r d e r sf o rp i z z at ot h es y s t e ma d m i n i s t r a t o r . ( A d da ne x t r ad o l l a rf o ra n c h o v yo rm u s h r o o mt o p p i n g . ) #A d d i t i o n a lm e s s a g et e x tg o e sh e r e . #N o t e :' w a l l 'p r i n t sc o m m e n tl i n e s . z z z 2 3 E n d O f M e s s a g e z z z 2 3 #C o u l dh a v eb e e nd o n em o r ee f f i c i e n t l yb y # w a l l< m e s s a g e f i l e # H o w e v e r ,e m b e d d i n gt h em e s s a g et e m p l a t ei nas c r i p t # +i saq u i c k a n d d i r t yo n e o f fs o l u t i o n . e x i t

Even such unlikely candidates as the vi text editor lend themselves to here documents. Example 19-2. dummyfile: Creates a 2-line dummy file
# ! / b i n / b a s h #N o n i n t e r a c t i v eu s eo f' v i 't oe d i taf i l e . #E m u l a t e s' s e d ' . E _ B A D A R G S = 8 5 i f[z" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `f i l e n a m e " e x i t$ E _ B A D A R G S f i

T A R G E T F I L E = $ 1 #I n s e r t2l i n e si nf i l e ,t h e ns a v e . # B e g i nh e r ed o c u m e n t # v i$ T A R G E T F I L E< < x 2 3 L i m i t S t r i n g x 2 3 i T h i si sl i n e1o ft h ee x a m p l ef i l e . T h i si sl i n e2o ft h ee x a m p l ef i l e . ^ [ Z Z x 2 3 L i m i t S t r i n g x 2 3 # E n dh e r ed o c u m e n t # # N o t et h a t^ [a b o v ei sal i t e r a le s c a p e # +t y p e db yC o n t r o l V< E s c > . # B r a mM o o l e n a a rp o i n t so u tt h a tt h i sm a yn o tw o r kw i t h' v i m ' # +b e c a u s eo fp o s s i b l ep r o b l e m sw i t ht e r m i n a li n t e r a c t i o n . e x i t

The above script could just as effectively have been implemented with ex, rather than vi. Here documents containing a list of ex commands are common enough to form their own category, known as ex scripts.
# ! / b i n / b a s h # R e p l a c ea l li n s t a n c e so f" S m i t h "w i t h" J o n e s " # +i nf i l e sw i t ha" . t x t "f i l e n a m es u f f i x . O R I G I N A L = S m i t h R E P L A C E M E N T = J o n e s f o rw o r di n$ ( f g r e pl$ O R I G I N A L* . t x t ) d o #e x$ w o r d< < E O F : % s / $ O R I G I N A L / $ R E P L A C E M E N T / g : w q E O F #: % si st h e" e x "s u b s t i t u t i o nc o m m a n d . #: w qi sw r i t e a n d q u i t . #d o n e

Analogous to "ex scripts" are cat scripts. Example 19-3. Multi-line message using cat
# ! / b i n / b a s h # ' e c h o 'i sf i n ef o rp r i n t i n gs i n g l el i n em e s s a g e s , # + b u ts o m e w h a tp r o b l e m a t i cf o rf o rm e s s a g eb l o c k s . # A' c a t 'h e r ed o c u m e n to v e r c o m e st h i sl i m i t a t i o n . c a t< < E n d o f m e s s a g e T h i si sl i n e1o ft h em e s s a g e . T h i si sl i n e2o ft h em e s s a g e . T h i si sl i n e3o ft h em e s s a g e . T h i si sl i n e4o ft h em e s s a g e . T h i si st h el a s tl i n eo ft h em e s s a g e . E n d o f m e s s a g e # R e p l a c i n gl i n e7 ,a b o v e ,w i t h # + c a t>$ N e w f i l e< < E n d o f m e s s a g e # + ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # +w r i t e st h eo u t p u tt ot h ef i l e$ N e w f i l e ,r a t h e rt h a nt os t d o u t .

e x i t0

# #C o d eb e l o wd i s a b l e d ,d u et o" e x i t0 "a b o v e . #S . C .p o i n t so u tt h a tt h ef o l l o w i n ga l s ow o r k s . e c h o" T h i si sl i n e1o ft h em e s s a g e . T h i si sl i n e2o ft h em e s s a g e . T h i si sl i n e3o ft h em e s s a g e . T h i si sl i n e4o ft h em e s s a g e . T h i si st h el a s tl i n eo ft h em e s s a g e . " #H o w e v e r ,t e x tm a yn o ti n c l u d ed o u b l eq u o t e su n l e s st h e ya r ee s c a p e d .

The -option to mark a here document limit string (< < L i m i t S t r i n g ) suppresses leading tabs (but not spaces) in the output. This may be useful in making a script more readable. Example 19-4. Multi-line message, with tabs suppressed
# ! / b i n / b a s h #S a m ea sp r e v i o u se x a m p l e ,b u t . . . # T h e-o p t i o nt oah e r ed o c u m e n t< < # +s u p p r e s s e sl e a d i n gt a b si nt h eb o d yo ft h ed o c u m e n t , # +b u t* n o t *s p a c e s . c a t< < E N D O F M E S S A G E T h i si sl i n e1o ft h em e s s a g e . T h i si sl i n e2o ft h em e s s a g e . T h i si sl i n e3o ft h em e s s a g e . T h i si sl i n e4o ft h em e s s a g e . T h i si st h el a s tl i n eo ft h em e s s a g e . E N D O F M E S S A G E #T h eo u t p u to ft h es c r i p tw i l lb ef l u s hl e f t . #L e a d i n gt a bi ne a c hl i n ew i l ln o ts h o w . #A b o v e5l i n e so f" m e s s a g e "p r e f a c e db yat a b ,n o ts p a c e s . #S p a c e sn o ta f f e c t e db y < < - . #N o t et h a tt h i so p t i o nh a sn oe f f e c to n* e m b e d d e d *t a b s . e x i t0

A here document supports parameter and command substitution. It is therefore possible to pass different parameters to the body of the here document, changing its output accordingly. Example 19-5. Here document with replaceable parameters
# ! / b i n / b a s h #A n o t h e r' c a t 'h e r ed o c u m e n t ,u s i n gp a r a m e t e rs u b s t i t u t i o n . #T r yi tw i t hn oc o m m a n d l i n ep a r a m e t e r s , . / s c r i p t n a m e #T r yi tw i t ho n ec o m m a n d l i n ep a r a m e t e r , . / s c r i p t n a m eM o r t i m e r #T r yi tw i t ho n et w o w o r dq u o t e dc o m m a n d l i n ep a r a m e t e r , # . / s c r i p t n a m e" M o r t i m e rJ o n e s " C M D L I N E P A R A M = 1 # E x p e c ta tl e a s tc o m m a n d l i n ep a r a m e t e r .

i f[$ #g e$ C M D L I N E P A R A M] t h e n N A M E = $ 1 # I fm o r et h a no n ec o m m a n d l i n ep a r a m , # +t h e nj u s tt a k et h ef i r s t . e l s e N A M E = " J o h nD o e " # D e f a u l t ,i fn oc o m m a n d l i n ep a r a m e t e r .

f i R E S P O N D E N T = " t h ea u t h o ro ft h i sf i n es c r i p t "

c a t< < E n d o f m e s s a g e H e l l o ,t h e r e ,$ N A M E . G r e e t i n g st oy o u ,$ N A M E ,f r o m$ R E S P O N D E N T . #T h i sc o m m e n ts h o w su pi nt h eo u t p u t( w h y ? ) . E n d o f m e s s a g e #N o t et h a tt h eb l a n kl i n e ss h o wu pi nt h eo u t p u t . #S od o e st h ec o m m e n t . e x i t

This is a useful script containing a here document with parameter substitution. Example 19-6. Upload a file pair to Sunsite incoming directory
# ! / b i n / b a s h #u p l o a d . s h # U p l o a df i l ep a i r( F i l e n a m e . l s m ,F i l e n a m e . t a r . g z ) # +t oi n c o m i n gd i r e c t o r ya tS u n s i t e / U N C( i b i b l i o . o r g ) . # F i l e n a m e . t a r . g zi st h et a r b a l li t s e l f . # F i l e n a m e . l s mi st h ed e s c r i p t o rf i l e . # S u n s i t er e q u i r e s" l s m "f i l e ,o t h e r w i s ew i l lb o u n c ec o n t r i b u t i o n s .

E _ A R G E R R O R = 8 5 i f[z" $ 1 "] t h e n e c h o" U s a g e :` b a s e n a m e$ 0 `F i l e n a m e t o u p l o a d " e x i t$ E _ A R G E R R O R f i

F i l e n a m e = ` b a s e n a m e$ 1 `

#S t r i p sp a t h n a m eo u to ff i l en a m e .

S e r v e r = " i b i b l i o . o r g " D i r e c t o r y = " / i n c o m i n g / L i n u x " # T h e s en e e dn o tb eh a r d c o d e di n t os c r i p t , # +b u tm a yi n s t e a db ec h a n g e dt oc o m m a n d l i n ea r g u m e n t . P a s s w o r d = " y o u r . e m a i l . a d d r e s s " f t pn$ S e r v e r< < E n d O f S e s s i o n #no p t i o nd i s a b l e sa u t o l o g o n u s e ra n o n y m o u s" $ P a s s w o r d " b i n a r y b e l l c d$ D i r e c t o r y p u t" $ F i l e n a m e . l s m " p u t" $ F i l e n a m e . t a r . g z " b y e E n d O f S e s s i o n e x i t0 # I ft h i sd o e s n ' tw o r k ,t h e nt r y : # q u o t eu s e ra n o n y m o u s" $ P a s s w o r d " #R i n g' b e l l 'a f t e re a c hf i l et r a n s f e r . #C h a n g ea b o v et os u i t .

Quoting or escaping the "limit string" at the head of a here document disables parameter substitution within its body. The

reason for this is that quoting/escaping the limit string effectively escapes the $, `, and \ special characters, and causes them to be interpreted literally. (Thank you, Allen Halsey, for pointing this out.) Example 19-7. Parameter substitution turned off
# ! / b i n / b a s h # A' c a t 'h e r e d o c u m e n t ,b u tw i t hp a r a m e t e rs u b s t i t u t i o nd i s a b l e d . N A M E = " J o h nD o e " R E S P O N D E N T = " t h ea u t h o ro ft h i sf i n es c r i p t " c a t< < ' E n d o f m e s s a g e ' H e l l o ,t h e r e ,$ N A M E . G r e e t i n g st oy o u ,$ N A M E ,f r o m$ R E S P O N D E N T . E n d o f m e s s a g e # # # + # # N op a r a m e t e rs u b s t i t u t i o nw h e nt h e" l i m i ts t r i n g "i sq u o t e do re s c a p e d . E i t h e ro ft h ef o l l o w i n ga tt h eh e a do ft h eh e r ed o c u m e n tw o u l dh a v e t h es a m ee f f e c t . c a t< < " E n d o f m e s s a g e " c a t< < \ E n d o f m e s s a g e

A n d ,l i k e w i s e :

c a t< < " S p e c i a l C h a r T e s t " D i r e c t o r yl i s t i n gw o u l df o l l o w i fl i m i ts t r i n gw e r en o tq u o t e d . ` l sl ` A r i t h m e t i ce x p a n s i o nw o u l dt a k ep l a c e i fl i m i ts t r i n gw e r en o tq u o t e d . $ ( ( 5+3 ) ) Aas i n g l eb a c k s l a s hw o u l de c h o i fl i m i ts t r i n gw e r en o tq u o t e d . \ \ S p e c i a l C h a r T e s t

e x i t

Disabling parameter substitution permits outputting literal text. Generating scripts or even program code is one use for this. Example 19-8. A script that generates another script
# ! / b i n / b a s h #g e n e r a t e s c r i p t . s h #B a s e do na ni d e ab yA l b e r tR e i n e r . O U T F I L E = g e n e r a t e d . s h #N a m eo ft h ef i l et og e n e r a t e .

##' H e r ed o c u m e n tc o n t a i n i n gt h eb o d yo ft h eg e n e r a t e ds c r i p t . ( c a t< < ' E O F ' # ! / b i n / b a s h e c h o" T h i si sag e n e r a t e ds h e l ls c r i p t . " # N o t et h a ts i n c ew ea r ei n s i d eas u b s h e l l , # +w ec a n ' ta c c e s sv a r i a b l e si nt h e" o u t s i d e "s c r i p t .

e c h o" G e n e r a t e df i l ew i l lb en a m e d :$ O U T F I L E " # A b o v el i n ew i l ln o tw o r ka sn o r m a l l ye x p e c t e d # +b e c a u s ep a r a m e t e re x p a n s i o nh a sb e e nd i s a b l e d . # I n s t e a d ,t h er e s u l ti sl i t e r a lo u t p u t . a = 7 b = 3 l e t" c=$ a*$ b " e c h o" c=$ c " e x i t0 E O F )>$ O U T F I L E ## Q u o t i n gt h e' l i m i ts t r i n g 'p r e v e n t sv a r i a b l ee x p a n s i o n # +w i t h i nt h eb o d yo ft h ea b o v e' h e r ed o c u m e n t . ' # T h i sp e r m i t so u t p u t t i n gl i t e r a ls t r i n g si nt h eo u t p u tf i l e . i f[f" $ O U T F I L E "] t h e n c h m o d7 5 5$ O U T F I L E #M a k et h eg e n e r a t e df i l ee x e c u t a b l e . e l s e e c h o" P r o b l e mi nc r e a t i n gf i l e :\ " $ O U T F I L E \ " " f i # T h i sm e t h o dc a na l s ob eu s e df o rg e n e r a t i n g # +Cp r o g r a m s ,P e r lp r o g r a m s ,P y t h o np r o g r a m s ,M a k e f i l e s , # +a n dt h el i k e . e x i t0

It is possible to set a variable from the output of a here document. This is actually a devious form of command substitution.
v a r i a b l e = $ ( c a t< < S E T V A R T h i sv a r i a b l e r u n so v e rm u l t i p l el i n e s . S E T V A R ) e c h o" $ v a r i a b l e "

A here document can supply input to a function in the same script. Example 19-9. Here documents and functions
# ! / b i n / b a s h #h e r e f u n c t i o n . s h G e t P e r s o n a l D a t a( ) { r e a df i r s t n a m e r e a dl a s t n a m e r e a da d d r e s s r e a dc i t y r e a ds t a t e r e a dz i p c o d e }#T h i sc e r t a i n l ya p p e a r st ob ea ni n t e r a c t i v ef u n c t i o n ,b u t...

#S u p p l yi n p u tt ot h ea b o v ef u n c t i o n . G e t P e r s o n a l D a t a< < R E C O R D 0 0 1 B o z o B o z e m a n 2 7 2 6N o n d e s c r i p tD r . B o z e m a n M T

2 1 2 2 6 R E C O R D 0 0 1

e c h o e c h o" $ f i r s t n a m e$ l a s t n a m e " e c h o" $ a d d r e s s " e c h o" $ c i t y ,$ s t a t e$ z i p c o d e " e c h o e x i t0

It is possible to use : as a dummy command accepting output from a here document. This, in effect, creates an "anonymous" here document. Example 19-10. "Anonymous" Here Document
# ! / b i n / b a s h :< < T E S T V A R I A B L E S $ { H O S T N A M E ? } $ { U S E R ? } $ { M A I L ? } #P r i n te r r o rm e s s a g ei fo n eo ft h ev a r i a b l e sn o ts e t . T E S T V A R I A B L E S e x i t$ ?

A variation of the above technique permits "commenting out" blocks of code. Example 19-11. Commenting out a block of code
# ! / b i n / b a s h #c o m m e n t b l o c k . s h :< < C O M M E N T B L O C K e c h o" T h i sl i n ew i l ln o te c h o . " T h i si sac o m m e n tl i n em i s s i n gt h e" # "p r e f i x . T h i si sa n o t h e rc o m m e n tl i n em i s s i n gt h e" # "p r e f i x . & * @ ! ! + + = T h ea b o v el i n ew i l lc a u s en oe r r o rm e s s a g e , b e c a u s et h eB a s hi n t e r p r e t e rw i l li g n o r ei t . C O M M E N T B L O C K e c h o" E x i tv a l u eo fa b o v e\ " C O M M E N T B L O C K \ "i s$ ? . " #N oe r r o rs h o w n . e c h o #0

# T h ea b o v et e c h n i q u ea l s oc o m e si nu s e f u lf o rc o m m e n t i n go u t # +ab l o c ko fw o r k i n gc o d ef o rd e b u g g i n gp u r p o s e s . # T h i ss a v e sh a v i n gt op u ta" # "a tt h eb e g i n n i n go fe a c hl i n e , # +t h e nh a v i n gt og ob a c ka n dd e l e t ee a c h" # "l a t e r . # N o t et h a tt h eu s eo fo fc o l o n ,a b o v e ,i so p t i o n a l . e c h o" J u s tb e f o r ec o m m e n t e d o u tc o d eb l o c k . " # T h el i n e so fc o d eb e t w e e nt h ed o u b l e d a s h e dl i n e sw i l ln o te x e c u t e . # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = :< < D E B U G X X X f o rf i l ei n* d o c a t" $ f i l e " d o n e D E B U G X X X # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = e c h o" J u s ta f t e rc o m m e n t e d o u tc o d eb l o c k . " e x i t0

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # N o t e ,h o w e v e r ,t h a ti fab r a c k e t e dv a r i a b l ei sc o n t a i n e dw i t h i n # +t h ec o m m e n t e d o u tc o d eb l o c k , # +t h e nt h i sc o u l dc a u s ep r o b l e m s . # f o re x a m p l e :

# / ! / b i n / b a s h :< < C O M M E N T B L O C K e c h o" T h i sl i n ew i l ln o te c h o . " & * @ ! ! + + = $ { f o o _ b a r _ b a z z ? } $ ( r mr f/ t m p / f o o b a r / ) $ ( t o u c hm y _ b u i l d _ d i r e c t o r y / c u p s / M a k e f i l e ) C O M M E N T B L O C K

$s hc o m m e n t e d b a d . s h c o m m e n t e d b a d . s h :l i n e3 :f o o _ b a r _ b a z z :p a r a m e t e rn u l lo rn o ts e t #T h er e m e d yf o rt h i si st os t r o n g q u o t et h e' C O M M E N T B L O C K 'i nl i n e4 9 ,a b o v e . :< < ' C O M M E N T B L O C K ' #T h a n ky o u ,K u r tP f e i f l e ,f o rp o i n t i n gt h i so u t .

Yet another twist of this nifty trick makes "self-documenting" scripts possible. Example 19-12. A self-documenting script
# ! / b i n / b a s h #s e l f d o c u m e n t . s h :s e l f d o c u m e n t i n gs c r i p t #M o d i f i c a t i o no f" c o l m . s h " . D O C _ R E Q U E S T = 7 0 i f[" $ 1 "=" h " o" $ 1 "=" h e l p "] #R e q u e s th e l p . t h e n e c h o ;e c h o" U s a g e :$ 0[ d i r e c t o r y n a m e ] " ;e c h o s e ds i l e n te' / D O C U M E N T A T I O N X X $ / , / ^ D O C U M E N T A T I O N X X $ / p '" $ 0 "| s e de' / D O C U M E N T A T I O N X X $ / d ' ;e x i t$ D O C _ R E Q U E S T ;f i

:< < D O C U M E N T A T I O N X X L i s tt h es t a t i s t i c so fas p e c i f i e dd i r e c t o r yi nt a b u l a rf o r m a t . T h ec o m m a n d l i n ep a r a m e t e rg i v e st h ed i r e c t o r yt ob el i s t e d . I fn od i r e c t o r ys p e c i f i e do rd i r e c t o r ys p e c i f i e dc a n n o tb er e a d , t h e nl i s tt h ec u r r e n tw o r k i n gd i r e c t o r y . D O C U M E N T A T I O N X X i f[z" $ 1 "o!r" $ 1 "] t h e n d i r e c t o r y = . e l s e d i r e c t o r y = " $ 1 " f i e c h o" L i s t i n go f" $ d i r e c t o r y " : " ;e c h o ( p r i n t f" P E R M I S S I O N SL I N K SO W N E RG R O U PS I Z EM O N T HD A YH H : M MP R O G N A M E \ n "\ ;l sl" $ d i r e c t o r y "|s e d1 d )|c o l u m nt e x i t0

Using a cat script is an alternate way of accomplishing this.


D O C _ R E Q U E S T = 7 0 i f[" $ 1 "=" h " o" $ 1 "=" h e l p "] #R e q u e s th e l p . t h e n #U s ea" c a ts c r i p t "... c a t< < D O C U M E N T A T I O N X X L i s tt h es t a t i s t i c so fas p e c i f i e dd i r e c t o r yi nt a b u l a rf o r m a t . T h ec o m m a n d l i n ep a r a m e t e rg i v e st h ed i r e c t o r yt ob el i s t e d . I fn od i r e c t o r ys p e c i f i e do rd i r e c t o r ys p e c i f i e dc a n n o tb er e a d , t h e nl i s tt h ec u r r e n tw o r k i n gd i r e c t o r y . D O C U M E N T A T I O N X X e x i t$ D O C _ R E Q U E S T f i

See also Example A-28, Example A-40, Example A-41, and Example A-42 for more examples of self-documenting scripts. Here documents create temporary files, but these files are deleted after opening and are not accessible to any other process.
b a s h $b a s hc' l s o fap$ $d 0 '< <E O F >E O F l s o f 1 2 1 3b o z o 0 r R E G 3 , 5 03 0 3 8 6/ t m p / t 1 2 1 3 0 s h( d e l e t e d )

Some utilities will not work inside a here document . The closing limit string, on the final line of a here document, must start in the first character position. There can be no leading whitespace. Trailing whitespace after the limit string likewise causes unexpected behavior. The whitespace prevents the limit string from being recognized. [103]
# ! / b i n / b a s h e c h o" " c a t< < L i m i t S t r i n g e c h o" T h i si sl i n e1o ft h em e s s a g ei n s i d et h eh e r ed o c u m e n t . " e c h o" T h i si sl i n e2o ft h em e s s a g ei n s i d et h eh e r ed o c u m e n t . " e c h o" T h i si st h ef i n a ll i n eo ft h em e s s a g ei n s i d et h eh e r ed o c u m e n t . " L i m i t S t r i n g # ^ ^ ^ ^ I n d e n t e dl i m i ts t r i n g .E r r o r !T h i ss c r i p tw i l ln o tb e h a v ea se x p e c t e d . e c h o" " # T h e s ec o m m e n t sa r eo u t s i d et h e' h e r ed o c u m e n t ' , # +a n ds h o u l dn o te c h o . e c h o" O u t s i d et h eh e r ed o c u m e n t . " e x i t0 e c h o" T h i sl i n eh a db e t t e rn o te c h o . " #F o l l o w sa n' e x i t 'c o m m a n d .

Some people very cleverly use a single ! as a limit string. But, that's not necessarily a good idea.
#T h i sw o r k s . c a t< < ! H e l l o !

!T h r e em o r ee x c l a m a t i o n s! ! ! !

#B u t... c a t< < ! H e l l o ! S i n g l ee x c l a m a t i o np o i n tf o l l o w s ! ! ! #C r a s h e sw i t ha ne r r o rm e s s a g e .

#H o w e v e r ,t h ef o l l o w i n gw i l lw o r k . c a t< < E O F H e l l o ! S i n g l ee x c l a m a t i o np o i n tf o l l o w s ! ! E O F #I t ' ss a f e rt ou s eam u l t i c h a r a c t e rl i m i ts t r i n g .

For those tasks too complex for a here document , consider using the e x p e c tscripting language, which was specifically designed for feeding input into interactive programs.

19.1. Here Strings


A here string can be considered as a stripped-down form of a here document . It consists of nothing more than COMMAND <<< $WORD, where $ W O R Dis expanded and fed to the s t d i nof COMMAND . As a simple example, consider this alternative to the echo-grep construction.
#I n s t e a do f : i fe c h o" $ V A R "|g r e pqt x t #e t c . #i f[ [$ V A R=* t x t *] ]

#T r y : i fg r e pq" t x t "< < <" $ V A R " t h e n # ^ ^ ^ e c h o" $ V A Rc o n t a i n st h es u b s t r i n gs e q u e n c e\ " t x t \ " " f i #T h a n ky o u ,S e b a s t i a nK a m i n s k i ,f o rt h es u g g e s t i o n .

Or, in combination with read:


S t r i n g = " T h i si sas t r i n go fw o r d s . " r e a draW o r d s< < <" $ S t r i n g " # T h eao p t i o nt o" r e a d " # +a s s i g n st h er e s u l t i n gv a l u e st os u c c e s s i v em e m b e r so fa na r r a y . e c h o" F i r s tw o r di nS t r i n gi s : e c h o" S e c o n dw o r di nS t r i n gi s : e c h o" T h i r dw o r di nS t r i n gi s : e c h o" F o u r t hw o r di nS t r i n gi s : e c h o" F i f t hw o r di nS t r i n gi s : e c h o" S i x t hw o r di nS t r i n gi s : e c h o" S e v e n t hw o r di nS t r i n gi s : $ { W o r d s [ 0 ] } " $ { W o r d s [ 1 ] } " $ { W o r d s [ 2 ] } " $ { W o r d s [ 3 ] } " $ { W o r d s [ 4 ] } " $ { W o r d s [ 5 ] } " $ { W o r d s [ 6 ] } " #T h i s #i s #a #s t r i n g #o f #w o r d s . #( n u l l ) #P a s te n do f$ S t r i n g .

#T h a n ky o u ,F r a n c i s c oL o b o ,f o rt h es u g g e s t i o n .

It is, of course, possible to feed the output of a here string into the s t d i nof a loop.
#A sS e a m u sp o i n t so u t... A r r a y V a r = (e l e m e n t 0e l e m e n t 1e l e m e n t 2{ A . . D }) w h i l er e a de l e m e n t;d o e c h o" $ e l e m e n t "1 > & 2 d o n e< < <$ ( e c h o$ { A r r a y V a r [ * ] } ) #e l e m e n t 0e l e m e n t 1e l e m e n t 2ABCD

Example 19-13. Prepending a line to a file


# ! / b i n / b a s h #p r e p e n d . s h :A d dt e x ta tb e g i n n i n go ff i l e . # # E x a m p l ec o n t r i b u t e db yK e n n yS t a u f f e r , # +a n ds l i g h t l ym o d i f i e db yd o c u m e n ta u t h o r .

E _ N O S U C H F I L E = 8 5 r e a dp" F i l e :"f i l e #pa r gt o' r e a d 'd i s p l a y sp r o m p t . i f[!e" $ f i l e "] t h e n #B a i lo u ti fn os u c hf i l e . e c h o" F i l e$ f i l en o tf o u n d . " e x i t$ E _ N O S U C H F I L E f i r e a dp" T i t l e :"t i t l e c a t-$ f i l e< < < $ t i t l e>$ f i l e . n e w e c h o" M o d i f i e df i l ei s$ f i l e . n e w " e x i t #E n d ss c r i p te x e c u t i o n . f r o m' m a nb a s h ' : H e r eS t r i n g s Av a r i a n to fh e r ed o c u m e n t s ,t h ef o r m a ti s : < < < w o r d T h ew o r di se x p a n d e da n ds u p p l i e dt ot h ec o m m a n do ni t ss t a n d a r di n p u t .

O fc o u r s e ,t h ef o l l o w i n ga l s ow o r k s : s e de' 1 i \ T i t l e :'$ f i l e

Example 19-14. Parsing a mailbox


# ! / b i n / b a s h # S c r i p tb yF r a n c i s c oL o b o , # +a n ds l i g h t l ym o d i f i e da n dc o m m e n t e db yA B SG u i d ea u t h o r . # U s e di nA B SG u i d ew i t hp e r m i s s i o n .( T h a n ky o u ! ) #T h i ss c r i p tw i l ln o tr u nu n d e rB a s hv e r s i o n sl t3 . 0 .

E _ M I S S I N G _ A R G = 8 7 i f[z" $ 1 "] t h e n e c h o" U s a g e :$ 0m a i l b o x f i l e " e x i t$ E _ M I S S I N G _ A R G f i

m b o x _ g r e p ( ) #P a r s em a i l b o xf i l e . { d e c l a r eib o d y = 0m a t c h = 0 d e c l a r ead a t es e n d e r d e c l a r em a i lh e a d e rv a l u e

w h i l eI F S =r e a drm a i l # ^ ^ ^ ^ R e s e t$ I F S . # O t h e r w i s e" r e a d "w i l ls t r i pl e a d i n g&t r a i l i n gs p a c ef r o mi t si n p u t . d o i f[ [$ m a i l= ~" ^ F r o m"] ] t h e n ( (b o d y =0) ) ( (m a t c h=0) ) u n s e td a t e #M a t c h" F r o m "f i e l di nm e s s a g e . #" Z e r oo u t "v a r i a b l e s .

e l i f( (b o d y) ) t h e n ( (m a t c h) ) # e c h o" $ m a i l " # U n c o m m e n ta b o v el i n ei fy o uw a n te n t i r eb o d y # +o fm e s s a g et od i s p l a y . e l i f[ [$ m a i l] ] ;t h e n I F S = :r e a drh e a d e rv a l u e< < <" $ m a i l " # ^ ^ ^ " h e r es t r i n g " c a s e" $ h e a d e r "i n [ F f ] [ R r ] [ O o ] [ M m ])[ [$ v a l u e= ~" $ 2 "] ]& &( (m a t c h + +) ); ; #M a t c h" F r o m "l i n e . [ D d ] [ A a ] [ T t ] [ E e ])r e a drad a t e< < <" $ v a l u e "; ; # ^ ^ ^ #M a t c h" D a t e "l i n e . [ R r ] [ E e ] [ C c ] [ E e ] [ I i ] [ V v ] [ E e ] [ D d ])r e a dras e n d e r< < <" $ v a l u e "; ; # ^ ^ ^ #M a t c hI PA d d r e s s( m a yb es p o o f e d ) . e s a c e l s e ( (b o d y + +) ) ( (m a t c h ) )& & e c h o" M E S S A G E$ { d a t e : + o f :$ { d a t e [ * ] }} " # E n t i r e$ d a t ea r r a y ^ e c h o" I Pa d d r e s so fs e n d e r :$ { s e n d e r [ 1 ] } " # S e c o n df i e l do f" R e c e i v e d "l i n e ^ f i

d o n e<" $ 1 "#R e d i r e c ts t d o u to ff i l ei n t ol o o p . }

m b o x _ g r e p" $ 1 " #S e n dm a i l b o xf i l et of u n c t i o n . e x i t$ ? #E x e r c i s e s : ##1 )B r e a kt h es i n g l ef u n c t i o n ,a b o v e ,i n t om u l t i p l ef u n c t i o n s , # + f o rt h es a k eo fr e a d a b i l i t y . #2 )A d da d d i t i o n a lp a r s i n gt ot h es c r i p t ,c h e c k i n gf o rv a r i o u sk e y w o r d s .

$m a i l b o x _ g r e p . s hs c a m _ m a i l M E S S A G Eo fT h u ,5J a n2 0 0 60 8 : 0 0 : 5 60 5 0 0( E S T )

I Pa d d r e s so fs e n d e r :1 9 6 . 3 . 6 2 . 4

Exercise: Find other uses for here strings, such as, for example, feeding input to dc.

Chapter 20. I/O Redirection


There are always three default files [104] open, s t d i n(the keyboard), s t d o u t(the screen), and s t d e r r(error messages output to the screen). These, and any other open files, can be redirected. Redirection simply means capturing output from a file, command, program, script, or even code block within a script (see Example 3-1 and Example 3-2) and sending it as input to another file, command, program, or script. Each open file gets assigned a file descriptor. [105] The file descriptors for s t d i n ,s t d o u t , and s t d e r rare 0, 1, and 2, respectively. For opening additional files, there remain descriptors 3 to 9. It is sometimes useful to assign one of these additional file descriptors to s t d i n ,s t d o u t , or s t d e r ras a temporary duplicate link. [106] This simplifies restoration to normal after complex redirection and reshuffling (see Example 20-1).
C O M M A N D _ O U T P U T> #R e d i r e c ts t d o u tt oaf i l e . #C r e a t e st h ef i l ei fn o tp r e s e n t ,o t h e r w i s eo v e r w r i t e si t . l sl R>d i r t r e e . l i s t #C r e a t e saf i l ec o n t a i n i n gal i s t i n go ft h ed i r e c t o r yt r e e . :>f i l e n a m e #T h e>t r u n c a t e sf i l e" f i l e n a m e "t oz e r ol e n g t h . #I ff i l en o tp r e s e n t ,c r e a t e sz e r o l e n g t hf i l e( s a m ee f f e c ta s' t o u c h ' ) . #T h e:s e r v e sa sad u m m yp l a c e h o l d e r ,p r o d u c i n gn oo u t p u t . >f i l e n a m e #T h e>t r u n c a t e sf i l e" f i l e n a m e "t oz e r ol e n g t h . #I ff i l en o tp r e s e n t ,c r e a t e sz e r o l e n g t hf i l e( s a m ee f f e c ta s' t o u c h ' ) . #( S a m er e s u l ta s" :> " ,a b o v e ,b u tt h i sd o e sn o tw o r kw i t hs o m es h e l l s . ) C O M M A N D _ O U T P U T> > #R e d i r e c ts t d o u tt oaf i l e . #C r e a t e st h ef i l ei fn o tp r e s e n t ,o t h e r w i s ea p p e n d st oi t .

#S i n g l e l i n er e d i r e c t i o nc o m m a n d s( a f f e c to n l yt h el i n et h e ya r eo n ) : #1 > f i l e n a m e #R e d i r e c ts t d o u tt of i l e" f i l e n a m e . " 1 > > f i l e n a m e #R e d i r e c ta n da p p e n ds t d o u tt of i l e" f i l e n a m e . " 2 > f i l e n a m e #R e d i r e c ts t d e r rt of i l e" f i l e n a m e . " 2 > > f i l e n a m e #R e d i r e c ta n da p p e n ds t d e r rt of i l e" f i l e n a m e . " & > f i l e n a m e #R e d i r e c tb o t hs t d o u ta n ds t d e r rt of i l e" f i l e n a m e . " #T h i so p e r a t o ri sn o wf u n c t i o n a l ,a so fB a s h4 ,f i n a lr e l e a s e . M > N #" M "i saf i l ed e s c r i p t o r ,w h i c hd e f a u l t st o1 ,i fn o te x p l i c i t l ys e t . #" N "i saf i l e n a m e . #F i l ed e s c r i p t o r" M "i sr e d i r e c tt of i l e" N . " M > & N #" M "i saf i l ed e s c r i p t o r ,w h i c hd e f a u l t st o1 ,i fn o ts e t . #" N "i sa n o t h e rf i l ed e s c r i p t o r . # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

#R e d i r e c t i n gs t d o u t ,o n el i n ea tat i m e . L O G F I L E = s c r i p t . l o g e c h o" T h i ss t a t e m e n ti ss e n tt ot h el o gf i l e ,\ " $ L O G F I L E \ " . "1 > $ L O G F I L E e c h o" T h i ss t a t e m e n ti sa p p e n d e dt o\ " $ L O G F I L E \ " . "1 > > $ L O G F I L E e c h o" T h i ss t a t e m e n ti sa l s oa p p e n d e dt o\ " $ L O G F I L E \ " . "1 > > $ L O G F I L E e c h o" T h i ss t a t e m e n ti se c h o e dt os t d o u t ,a n dw i l ln o ta p p e a ri n\ " $ L O G F I L E \ " . " #T h e s er e d i r e c t i o nc o m m a n d sa u t o m a t i c a l l y" r e s e t "a f t e re a c hl i n e .

#R e d i r e c t i n gs t d e r r ,o n el i n ea tat i m e . E R R O R F I L E = s c r i p t . e r r o r s b a d _ c o m m a n d 12 > $ E R R O R F I L E b a d _ c o m m a n d 22 > > $ E R R O R F I L E b a d _ c o m m a n d 3 # E r r o rm e s s a g es e n tt o$ E R R O R F I L E . # E r r o rm e s s a g ea p p e n d e dt o$ E R R O R F I L E . # E r r o rm e s s a g ee c h o e dt os t d e r r , # +a n dd o e sn o ta p p e a ri n$ E R R O R F I L E . #T h e s er e d i r e c t i o nc o m m a n d sa l s oa u t o m a t i c a l l y" r e s e t "a f t e re a c hl i n e . # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 2 > & 1 #R e d i r e c t ss t d e r rt os t d o u t . #E r r o rm e s s a g e sg e ts e n tt os a m ep l a c ea ss t a n d a r do u t p u t . > > f i l e n a m e2 > & 1 b a d _ c o m m a n d> > f i l e n a m e2 > & 1 #A p p e n d sb o t hs t d o u ta n ds t d e r rt ot h ef i l e" f i l e n a m e ". . . 2 > & 1|[ c o m m a n d ( s ) ] b a d _ c o m m a n d2 > & 1|a w k' { p r i n t$ 5 } ' #f o u n d #S e n d ss t d e r rt h r o u g hap i p e . #| &w a sa d d e dt oB a s h4a sa na b b r e v i a t i o nf o r2 > & 1| . i > & j #R e d i r e c t sf i l ed e s c r i p t o rit oj . #A l lo u t p u to ff i l ep o i n t e dt ob yig e t ss e n tt of i l ep o i n t e dt ob yj . > & j #R e d i r e c t s ,b yd e f a u l t ,f i l ed e s c r i p t o r1( s t d o u t )t oj . #A l ls t d o u tg e t ss e n tt of i l ep o i n t e dt ob yj . 0 <F I L E N A M E <F I L E N A M E #A c c e p ti n p u tf r o maf i l e . #C o m p a n i o nc o m m a n dt o" > " ,a n do f t e nu s e di nc o m b i n a t i o nw i t hi t . # #g r e ps e a r c h w o r d< f i l e n a m e

[ j ] < > f i l e n a m e # O p e nf i l e" f i l e n a m e "f o rr e a d i n ga n dw r i t i n g , # +a n da s s i g nf i l ed e s c r i p t o r" j "t oi t . # I f" f i l e n a m e "d o e sn o te x i s t ,c r e a t ei t . # I ff i l ed e s c r i p t o r" j "i sn o ts p e c i f i e d ,d e f a u l tt of d0 ,s t d i n . # # A na p p l i c a t i o no ft h i si sw r i t i n ga tas p e c i f i e dp l a c ei naf i l e . e c h o1 2 3 4 5 6 7 8 9 0>F i l e #W r i t es t r i n gt o" F i l e " . e x e c3 < >F i l e #O p e n" F i l e "a n da s s i g nf d3t oi t . r e a dn4< & 3 #R e a do n l y4c h a r a c t e r s . e c h on.> & 3 #W r i t ead e c i m a lp o i n tt h e r e . e x e c3 > & #C l o s ef d3 . c a tF i l e #= = >1 2 3 4 . 6 7 8 9 0 # R a n d o ma c c e s s ,b yg o l l y .

| #P i p e . #G e n e r a lp u r p o s ep r o c e s sa n dc o m m a n dc h a i n i n gt o o l .

#S i m i l a rt o" > " ,b u tm o r eg e n e r a li ne f f e c t . #U s e f u lf o rc h a i n i n gc o m m a n d s ,s c r i p t s ,f i l e s ,a n dp r o g r a m st o g e t h e r . c a t* . t x t|s o r t|u n i q>r e s u l t f i l e #S o r t st h eo u t p u to fa l lt h e. t x tf i l e sa n dd e l e t e sd u p l i c a t el i n e s , #f i n a l l ys a v e sr e s u l t st o" r e s u l t f i l e " .

Multiple instances of input and output redirection and/or pipes can be combined in a single command line.
c o m m a n d<i n p u t f i l e>o u t p u t f i l e #O rt h ee q u i v a l e n t : <i n p u t f i l ec o m m a n d>o u t p u t f i l e #A l t h o u g ht h i si sn o n s t a n d a r d .

c o m m a n d 1|c o m m a n d 2|c o m m a n d 3>o u t p u t f i l e

See Example 16-31 and Example A-14. Multiple output streams may be redirected to one file.
l sy z> >c o m m a n d . l o g2 > & 1 # C a p t u r er e s u l to fi l l e g a lo p t i o n s" y z "i nf i l e" c o m m a n d . l o g . " # B e c a u s es t d e r ri sr e d i r e c t e dt ot h ef i l e , # +a n ye r r o rm e s s a g e sw i l la l s ob et h e r e . # N o t e ,h o w e v e r ,t h a tt h ef o l l o w i n gd o e s* n o t *g i v et h es a m er e s u l t . l sy z2 > & 1> >c o m m a n d . l o g # O u t p u t sa ne r r o rm e s s a g e ,b u td o e sn o tw r i t et of i l e . # M o r ep r e c i s e l y ,t h ec o m m a n do u t p u t( i nt h i sc a s e ,n u l l ) # +w r i t e st ot h ef i l e ,b u tt h ee r r o rm e s s a g eg o e so n l yt os t d o u t . # I fr e d i r e c t i n gb o t hs t d o u ta n ds t d e r r , # +t h eo r d e ro ft h ec o m m a n d sm a k e sad i f f e r e n c e .

Closing File Descriptors n<&Close input file descriptor n . 0<&-, <&Close s t d i n . n>&Close output file descriptor n . 1>&-, >&Close s t d o u t . Child processes inherit open file descriptors. This is why pipes work. To prevent an fd from being inherited, close it.
#R e d i r e c t i n go n l ys t d e r rt oap i p e . e x e c3 > & 1 l sl2 > & 1> & 33 > & -|g r e pb a d3 > & # ^ ^ ^ ^ ^ ^ ^ ^ e x e c3 > & #T h a n k s ,S . C . #S a v ec u r r e n t" v a l u e "o fs t d o u t . #C l o s ef d3f o r' g r e p '( b u tn o t' l s ' ) . #N o wc l o s ei tf o rt h er e m a i n d e ro ft h es c r i p t .

For a more detailed introduction to I/O redirection see Appendix F.

20.1. Using exec

An exec <filename command redirects s t d i nto a file. From that point on, all s t d i ncomes from that file, rather than its normal source (usually keyboard input). This provides a method of reading a file line by line and possibly parsing each line of input using sed and/or awk. Example 20-1. Redirecting s t d i nusing exec
# ! / b i n / b a s h #R e d i r e c t i n gs t d i nu s i n g' e x e c ' .

e x e c6 < & 0

#L i n kf i l ed e s c r i p t o r# 6w i t hs t d i n . #S a v e ss t d i n . #s t d i nr e p l a c e db yf i l e" d a t a f i l e " #R e a d sf i r s tl i n eo ff i l e" d a t a f i l e " . #R e a d ss e c o n dl i n eo ff i l e" d a t a f i l e . "

e x e c<d a t a f i l e r e a da 1 r e a da 2

e c h o e c h o" F o l l o w i n gl i n e sr e a df r o mf i l e . " e c h o" " e c h o$ a 1 e c h o$ a 2 e c h o ;e c h o ;e c h o e x e c0 < & 66 < & # N o wr e s t o r es t d i nf r o mf d# 6 ,w h e r ei th a db e e ns a v e d , # +a n dc l o s ef d# 6(6 < & -)t of r e ei tf o ro t h e rp r o c e s s e st ou s e . # #< & 66 < & a l s ow o r k s . e c h on" E n t e rd a t a " r e a db 1 #N o w" r e a d "f u n c t i o n sa se x p e c t e d ,r e a d i n gf r o mn o r m a ls t d i n . e c h o" I n p u tr e a df r o ms t d i n . " e c h o" " e c h o" b 1=$ b 1 " e c h o e x i t0

Similarly, an exec >filename command redirects s t d o u tto a designated file. This sends all command output that would normally go to s t d o u tto that file. exec N > filename affects the entire script or current shell. Redirection in the PID of the script or shell from that point on has changed. However . . . N > filename affects only the newly-forked process, not the entire script or shell. Thank you, Ahmed Darwish, for pointing this out. Example 20-2. Redirecting s t d o u tusing exec
# ! / b i n / b a s h #r e a s s i g n s t d o u t . s h L O G F I L E = l o g f i l e . t x t e x e c6 > & 1 #L i n kf i l ed e s c r i p t o r# 6w i t hs t d o u t . #S a v e ss t d o u t . #s t d o u tr e p l a c e dw i t hf i l e" l o g f i l e . t x t " .

e x e c>$ L O G F I L E

#-#

#A l lo u t p u tf r o mc o m m a n d si nt h i sb l o c ks e n tt of i l e$ L O G F I L E . e c h on" L o g f i l e :" d a t e e c h o" " e c h o e c h o" O u t p u to f\ " l sa l \ "c o m m a n d " e c h o l sa l e c h o ;e c h o e c h o" O u t p u to f\ " d f \ "c o m m a n d " e c h o d f #-# e x e c1 > & 66 > & #R e s t o r es t d o u ta n dc l o s ef i l ed e s c r i p t o r# 6 .

e c h o e c h o" = =s t d o u tn o wr e s t o r e dt od e f a u l t= =" e c h o l sa l e c h o e x i t0

Example 20-3. Redirecting both s t d i nand s t d o u tin the same script with exec
# ! / b i n / b a s h #u p p e r c o n v . s h #C o n v e r t sas p e c i f i e di n p u tf i l et ou p p e r c a s e . E _ F I L E _ A C C E S S = 7 0 E _ W R O N G _ A R G S = 7 1 i f[!r" $ 1 "] #I ss p e c i f i e di n p u tf i l er e a d a b l e ? t h e n e c h o" C a n ' tr e a df r o mi n p u tf i l e ! " e c h o" U s a g e :$ 0i n p u t f i l eo u t p u t f i l e " e x i t$ E _ F I L E _ A C C E S S f i # W i l le x i tw i t hs a m ee r r o r # +e v e ni fi n p u tf i l e( $ 1 )n o ts p e c i f i e d( w h y ? ) . i f[z" $ 2 "] t h e n e c h o" N e e dt os p e c i f yo u t p u tf i l e . " e c h o" U s a g e :$ 0i n p u t f i l eo u t p u t f i l e " e x i t$ E _ W R O N G _ A R G S f i

e x e c4 < & 0 e x e c<$ 1 e x e c7 > & 1 e x e c>$ 2

#W i l lr e a df r o mi n p u tf i l e .

#W i l lw r i t et oo u t p u tf i l e . #A s s u m e so u t p u tf i l ew r i t a b l e( a d dc h e c k ? ) .

#c a t-|t ra zA Z #U p p e r c a s ec o n v e r s i o n . # ^ ^ ^ ^ ^ #R e a d sf r o ms t d i n . # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ #W r i t e st os t d o u t . #H o w e v e r ,b o t hs t d i na n ds t d o u tw e r er e d i r e c t e d . #N o t et h a tt h e' c a t 'c a nb eo m i t t e d . #e x e c1 > & 77 > & #R e s t o r es t o u t .

e x e c0 < & 44 < & -

#R e s t o r es t d i n .

#A f t e rr e s t o r a t i o n ,t h ef o l l o w i n gl i n ep r i n t st os t d o u ta se x p e c t e d . e c h o" F i l e\ " $ 1 \ "w r i t t e nt o\ " $ 2 \ "a su p p e r c a s ec o n v e r s i o n . " e x i t0

I/O redirection is a clever way of avoiding the dreaded inaccessible variables within a subshell problem. Example 20-4. Avoiding a subshell
# ! / b i n / b a s h #a v o i d s u b s h e l l . s h #S u g g e s t e db yM a t t h e wW a l k e r . L i n e s = 0 e c h o c a tm y f i l e . t x t|w h i l er e a dl i n e ; d o{ e c h o$ l i n e ( (L i n e s + +) ) ; # I n c r e m e n t e dv a l u e so ft h i sv a r i a b l e # +i n a c c e s s i b l eo u t s i d el o o p . # S u b s h e l lp r o b l e m . } d o n e e c h o" N u m b e ro fl i n e sr e a d=$ L i n e s " #0 #W r o n g !

e c h o" "

e x e c3 < >m y f i l e . t x t w h i l er e a dl i n e< & 3 d o{ e c h o" $ l i n e " ( (L i n e s + +) ) ;

# I n c r e m e n t e dv a l u e so ft h i sv a r i a b l e # +a c c e s s i b l eo u t s i d el o o p . # N os u b s h e l l ,n op r o b l e m .

} d o n e e x e c3 > & e c h o" N u m b e ro fl i n e sr e a d=$ L i n e s " e c h o e x i t0 #L i n e sb e l o wn o ts e e nb ys c r i p t . $c a tm y f i l e . t x t L i n e1 . L i n e2 . L i n e3 . L i n e4 . L i n e5 . L i n e6 . L i n e7 . L i n e8 . #8

20.2. Redirecting Code Blocks

Blocks of code, such as while, until, and for loops, even if/then test blocks can also incorporate redirection of s t d i n . Even a function may use this form of redirection (see Example 24-11). The < operator at the end of the code block accomplishes this. Example 20-5. Redirected while loop
# ! / b i n / b a s h #r e d i r 2 . s h i f[z" $ 1 "] t h e n F i l e n a m e = n a m e s . d a t a #D e f a u l t ,i fn of i l e n a m es p e c i f i e d . e l s e F i l e n a m e = $ 1 f i # +F i l e n a m e = $ { 1 : n a m e s . d a t a } # c a nr e p l a c et h ea b o v et e s t( p a r a m e t e rs u b s t i t u t i o n ) . c o u n t = 0 e c h o w h i l e[" $ n a m e "! =S m i t h] #W h yi sv a r i a b l e$ n a m ei nq u o t e s ? d o r e a dn a m e #R e a d sf r o m$ F i l e n a m e ,r a t h e rt h a ns t d i n . e c h o$ n a m e l e t" c o u n t+ =1 " d o n e< " $ F i l e n a m e " #R e d i r e c t ss t d i nt of i l e$ F i l e n a m e . # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ e c h o ;e c h o" $ c o u n tn a m e sr e a d " ;e c h o e x i t0 # N o t et h a ti ns o m eo l d e rs h e l ls c r i p t i n gl a n g u a g e s , # +t h er e d i r e c t e dl o o pw o u l dr u na sas u b s h e l l . # T h e r e f o r e ,$ c o u n tw o u l dr e t u r n0 ,t h ei n i t i a l i z e dv a l u eo u t s i d et h el o o p . # B a s ha n dk s ha v o i ds t a r t i n gas u b s h e l l* w h e n e v e rp o s s i b l e * , # +s ot h a tt h i ss c r i p t ,f o re x a m p l e ,r u n sc o r r e c t l y . # ( T h a n k st oH e i n e rS t e v e nf o rp o i n t i n gt h i so u t . ) # H o w e v e r... # B a s h* c a n *s o m e t i m e ss t a r tas u b s h e l li naP I P E D" w h i l e r e a d "l o o p , # +a sd i s t i n c tf r o maR E D I R E C T E D" w h i l e "l o o p . a b c = h i e c h oe" 1 \ n 2 \ n 3 "|w h i l er e a dl d oa b c = " $ l " e c h o$ a b c d o n e e c h o$ a b c # T h a n k s ,B r u n od eO l i v e i r aS c h n e i d e r ,f o rd e m o n s t r a t i n gt h i s # +w i t ht h ea b o v es n i p p e to fc o d e . # A n d ,t h a n k s ,B r i a nO n n ,f o rc o r r e c t i n ga na n n o t a t i o ne r r o r .

Example 20-6. Alternate form of redirected while loop


# ! / b i n / b a s h #T h i si sa na l t e r n a t ef o r mo ft h ep r e c e d i n gs c r i p t . # S u g g e s t e db yH e i n e rS t e v e n # +a saw o r k a r o u n di nt h o s es i t u a t i o n sw h e nar e d i r e c tl o o p # +r u n sa sas u b s h e l l ,a n dt h e r e f o r ev a r i a b l e si n s i d et h el o o p #+ d on o tk e e pt h e i rv a l u e su p o nl o o pt e r m i n a t i o n .

i f[z" $ 1 "] t h e n F i l e n a m e = n a m e s . d a t a e l s e F i l e n a m e = $ 1 f i

#D e f a u l t ,i fn of i l e n a m es p e c i f i e d .

e x e c3 < & 0 e x e c0 < " $ F i l e n a m e " c o u n t = 0 e c h o

#S a v es t d i nt of i l ed e s c r i p t o r3 . #R e d i r e c ts t a n d a r di n p u t .

w h i l e[" $ n a m e "! =S m i t h] d o r e a dn a m e #R e a d sf r o mr e d i r e c t e ds t d i n( $ F i l e n a m e ) . e c h o$ n a m e l e t" c o u n t+ =1 " d o n e # L o o pr e a d sf r o mf i l e$ F i l e n a m e # +b e c a u s eo fl i n e2 0 . # T h eo r i g i n a lv e r s i o no ft h i ss c r i p tt e r m i n a t e dt h e" w h i l e "l o o pw i t h # + d o n e< " $ F i l e n a m e " # E x e r c i s e : # W h yi st h i su n n e c e s s a r y ?

e x e c0 < & 3 e x e c3 < & -

#R e s t o r eo l ds t d i n . #C l o s et e m p o r a r yf d3 .

e c h o ;e c h o" $ c o u n tn a m e sr e a d " ;e c h o e x i t0

Example 20-7. Redirected until loop


# ! / b i n / b a s h #S a m ea sp r e v i o u se x a m p l e ,b u tw i t h" u n t i l "l o o p . i f[z" $ 1 "] t h e n F i l e n a m e = n a m e s . d a t a e l s e F i l e n a m e = $ 1 f i

#D e f a u l t ,i fn of i l e n a m es p e c i f i e d .

#w h i l e[" $ n a m e "! =S m i t h] u n t i l[" $ n a m e "=S m i t h] #C h a n g e ! = t o= . d o r e a dn a m e #R e a d sf r o m$ F i l e n a m e ,r a t h e rt h a ns t d i n . e c h o$ n a m e d o n e< " $ F i l e n a m e " #R e d i r e c t ss t d i nt of i l e$ F i l e n a m e . # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ #S a m er e s u l t sa sw i t h" w h i l e "l o o pi np r e v i o u se x a m p l e . e x i t0

Example 20-8. Redirected for loop


# ! / b i n / b a s h i f[z" $ 1 "] t h e n F i l e n a m e = n a m e s . d a t a

#D e f a u l t ,i fn of i l e n a m es p e c i f i e d .

e l s e F i l e n a m e = $ 1 f i l i n e _ c o u n t = ` w c$ F i l e n a m e|a w k' {p r i n t$ 1} ' ` # N u m b e ro fl i n e si nt a r g e tf i l e . # # V e r yc o n t r i v e da n dk l u d g y ,n e v e r t h e l e s ss h o w st h a t # +i t ' sp o s s i b l et or e d i r e c ts t d i nw i t h i na" f o r "l o o p . . . # +i fy o u ' r ec l e v e re n o u g h . # #M o r ec o n c i s ei s l i n e _ c o u n t = $ ( w cl<" $ F i l e n a m e " )

f o rn a m ei n` s e q$ l i n e _ c o u n t ` #w h i l e[" $ n a m e "! =S m i t h] d o r e a dn a m e e c h o$ n a m e i f[" $ n a m e "=S m i t h] t h e n b r e a k f i d o n e< " $ F i l e n a m e " # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ e x i t0

#R e c a l lt h a t" s e q "p r i n t ss e q u e n c eo fn u m b e r s . - m o r ec o m p l i c a t e dt h a na" w h i l e "l o o p #R e a d sf r o m$ F i l e n a m e ,r a t h e rt h a ns t d i n . #N e e da l lt h i se x t r ab a g g a g eh e r e .

#R e d i r e c t ss t d i nt of i l e$ F i l e n a m e .

We can modify the previous example to also redirect the output of the loop. Example 20-9. Redirected for loop (both s t d i nand s t d o u tredirected)
# ! / b i n / b a s h i f[z" $ 1 "] t h e n F i l e n a m e = n a m e s . d a t a e l s e F i l e n a m e = $ 1 f i S a v e f i l e = $ F i l e n a m e . n e w F i n a l N a m e = J o n a h

#D e f a u l t ,i fn of i l e n a m es p e c i f i e d .

#F i l e n a m et os a v er e s u l t si n . #N a m et ot e r m i n a t e" r e a d "o n .

l i n e _ c o u n t = ` w c$ F i l e n a m e|a w k' {p r i n t$ 1} ' ` #N u m b e ro fl i n e si nt a r g e tf i l e .

f o rn a m ei n` s e q$ l i n e _ c o u n t ` d o r e a dn a m e e c h o" $ n a m e " i f[" $ n a m e "=" $ F i n a l N a m e "] t h e n b r e a k f i d o n e<" $ F i l e n a m e ">" $ S a v e f i l e " # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ e x i t0

#R e d i r e c t ss t d i nt of i l e$ F i l e n a m e , a n ds a v e si tt ob a c k u pf i l e .

Example 20-10. Redirected if/then test


# ! / b i n / b a s h i f[z" $ 1 "] t h e n F i l e n a m e = n a m e s . d a t a e l s e

#D e f a u l t ,i fn of i l e n a m es p e c i f i e d .

F i l e n a m e = $ 1 f i T R U E = 1 i f[" $ T R U E "] t h e n r e a dn a m e e c h o$ n a m e f i< " $ F i l e n a m e " # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ #i ft r u e a n d i f: a l s ow o r k .

#R e a d so n l yf i r s tl i n eo ff i l e . #A n" i f / t h e n "t e s th a sn ow a yo fi t e r a t i n gu n l e s se m b e d d e di nal o o p . e x i t0

Example 20-11. Data file names.data for above examples


A r i s t o t l e A r r h e n i u s B e l i s a r i u s C a p a b l a n c a D i c k e n s E u l e r G o e t h e H e g e l J o n a h L a p l a c e M a r o c z y P u r c e l l S c h m i d t S c h o p e n h a u e r S e m m e l w e i s s S m i t h S t e i n m e t z T u k h a s h e v s k y T u r i n g V e n n W a r s h a w s k i Z n o s k o B o r o w s k i # T h i si sad a t af i l ef o r # +" r e d i r 2 . s h " ," r e d i r 3 . s h " ," r e d i r 4 . s h " ," r e d i r 4 a . s h " ," r e d i r 5 . s h " .

Redirecting the s t d o u tof a code block has the effect of saving its output to a file. See Example 3-2. Here documents are a special case of redirected code blocks. That being the case, it should be possible to feed the output of a here document into the s t d i nfor a while loop.
#T h i se x a m p l eb yA l b e r tS i e r s e m a #U s e dw i t hp e r m i s s i o n( t h a n k s ! ) . f u n c t i o nd o e s O u t p u t ( ) #C o u l db ea ne x t e r n a lc o m m a n dt o o ,o fc o u r s e . #H e r ew es h o wy o uc a nu s eaf u n c t i o na sw e l l . { l sa l* . j p g|a w k' { p r i n t$ 5 , $ 9 } ' }

n r = 0 t o t a l S i z e = 0

# W ew a n tt h ew h i l el o o pt ob ea b l et om a n i p u l a t et h e s ea n d # +t ob ea b l et os e et h ec h a n g e sa f t e rt h e' w h i l e 'f i n i s h e d .

w h i l er e a df i l e S i z ef i l e N a m e;d o e c h o" $ f i l e N a m ei s$ f i l e S i z eb y t e s " l e tn r + +

t o t a l S i z e = $ ( ( t o t a l S i z e + f i l e S i z e ) ) d o n e < < E O F $ ( d o e s O u t p u t ) E O F

#O r :" l e tt o t a l S i z e + = f i l e S i z e "

e c h o" $ n rf i l e st o t a l i n g$ t o t a l S i z eb y t e s "

20.3. Applications
Clever use of I/O redirection permits parsing and stitching together snippets of command output (see Example 15-7). This permits generating report and log files. Example 20-12. Logging events
# ! / b i n / b a s h #l o g e v e n t s . s h #A u t h o r :S t e p h a n eC h a z e l a s . #U s e di nA B SG u i d ew i t hp e r m i s s i o n . #E v e n tl o g g i n gt oaf i l e . #M u s tb er u na sr o o t( f o rw r i t ea c c e s si n/ v a r / l o g ) . R O O T _ U I D = 0 E _ N O T R O O T = 6 7 #O n l yu s e r sw i t h$ U I D0h a v er o o tp r i v i l e g e s . #N o n r o o te x i te r r o r .

i f[" $ U I D "n e" $ R O O T _ U I D "] t h e n e c h o" M u s tb er o o tt or u nt h i ss c r i p t . " e x i t$ E _ N O T R O O T f i

F D _ D E B U G 1 = 3 F D _ D E B U G 2 = 4 F D _ D E B U G 3 = 5 #= = =U n c o m m e n to n eo ft h et w ol i n e sb e l o wt oa c t i v a t es c r i p t .= = = #L O G _ E V E N T S = 1 #L O G _ V A R S = 1

l o g ( ) #W r i t e st i m ea n dd a t et ol o gf i l e . { e c h o" $ ( d a t e ) $ * "> & 7 #T h i s* a p p e n d s *t h ed a t et ot h ef i l e . # ^ ^ ^ ^ ^ ^ ^ c o m m a n ds u b s t i t u t i o n #S e eb e l o w . }

c a s e$ L O G _ L E V E Li n 1 )e x e c3 > & 2 4 >/ d e v / n u l l5 >/ d e v / n u l l ; ; 2 )e x e c3 > & 2 4 > & 2 5 >/ d e v / n u l l ; ; 3 )e x e c3 > & 2 4 > & 2 5 > & 2 ; ; * )e x e c3 >/ d e v / n u l l4 >/ d e v / n u l l5 >/ d e v / n u l l ; ; e s a c F D _ L O G V A R S = 6 i f[ [$ L O G _ V A R S] ] t h e ne x e c6 > >/ v a r / l o g / v a r s . l o g e l s ee x e c6 >/ d e v / n u l l f i F D _ L O G E V E N T S = 7

#B u r yo u t p u t .

i f[ [$ L O G _ E V E N T S] ] t h e n #e x e c7> ( e x e cg a w k' { p r i n ts t r f t i m e ( ) ,$ 0 } '> >/ v a r / l o g / e v e n t . l o g ) #A b o v el i n ef a i l si nv e r s i o n so fB a s hm o r er e c e n tt h a n2 . 0 4 .W h y ? e x e c7 > >/ v a r / l o g / e v e n t . l o g #A p p e n dt o" e v e n t . l o g " . l o g #W r i t et i m ea n dd a t e . e l s ee x e c7 >/ d e v / n u l l #B u r yo u t p u t . f i e c h o" D E B U G 3 :b e g i n n i n g "> & $ { F D _ D E B U G 3 } l sl> & 52 > & 4 e c h o" D o n e " #c o m m a n d 1> & 52 > & 4 #c o m m a n d 2

e c h o" s e n d i n gm a i l "> & $ { F D _ L O G E V E N T S } #W r i t e s" s e n d i n gm a i l "t of i l ed e s c r i p t o r# 7 .

e x i t0

Chapter 21. Subshells


Running a shell script launches a new process, a subshell.
D e f i n i t i o n :A subshell is a child

process launched by a shell (or shell script ).

A subshell is a separate instance of the command processor -- the shell that gives you the prompt at the console or in an xterm window. Just as your commands are interpreted at the command-line prompt, similarly does a script batch-process a list of commands. Each shell script running is, in effect, a subprocess (child process) of the parent shell. A shell script can itself launch subprocesses. These subshells let the script do parallel processing, in effect executing multiple subtasks simultaneously.
# ! / b i n / b a s h #s u b s h e l l t e s t . s h ( #I n s i d ep a r e n t h e s e s ,a n dt h e r e f o r eas u b s h e l l... w h i l e[1] #E n d l e s sl o o p . d o e c h o" S u b s h e l lr u n n i n g... " d o n e ) # S c r i p tw i l lr u nf o r e v e r , # +o ra tl e a s tu n t i lt e r m i n a t e db yaC t l C . e x i t$ ? #E n do fs c r i p t( b u tw i l ln e v e rg e th e r e ) .

N o w ,r u nt h es c r i p t : s hs u b s h e l l t e s t . s h A n d ,w h i l et h es c r i p ti sr u n n i n g ,f r o mad i f f e r e n tx t e r m : p se f|g r e ps u b s h e l l t e s t . s h U I D 5 0 0 5 0 0 P I D P P I D CS T I M ET T Y 2 6 9 8 2 5 0 2 01 4 : 2 6p t s / 4 2 6 9 9 2 6 9 82 11 4 : 2 6p t s / 4 ^ ^ ^ ^ T I M E C M D 0 0 : 0 0 : 0 0s hs u b s h e l l t e s t . s h 0 0 : 0 0 : 2 4s hs u b s h e l l t e s t . s h

A n a l y s i s : P I D2 6 9 8 ,t h es c r i p t ,l a u n c h e dP I D2 6 9 9 ,t h es u b s h e l l . N o t e :T h e" U I D. . . "l i n ew o u l db ef i l t e r e do u tb yt h e" g r e p "c o m m a n d , b u ti ss h o w nh e r ef o ri l l u s t r a t i v ep u r p o s e s .

In general, an external command in a script forks off a subprocess, [107] whereas a Bash builtin does not. For this reason, builtins execute more quickly and use fewer system resources than their external command equivalents. Command List within Parentheses ( command1; command2; command3; ... ) A command list embedded between p a r e n t h e s e sruns as a subshell. Variables in a subshell are not visible outside the block of code in the subshell. They are not accessible to the parent process, to the shell that launched the subshell. These are, in effect, variables local to the child process. Example 21-1. Variable scope in a subshell
# ! / b i n / b a s h #s u b s h e l l . s h e c h o e c h o" W ea r eo u t s i d et h es u b s h e l l . " e c h o" S u b s h e l ll e v e lO U T S I D Es u b s h e l l=$ B A S H _ S U B S H E L L " #B a s h ,v e r s i o n3 ,a d d st h en e w $ B A S H _ S U B S H E L Lv a r i a b l e . e c h o ;e c h o o u t e r _ v a r i a b l e = O u t e r g l o b a l _ v a r i a b l e = # D e f i n eg l o b a lv a r i a b l ef o r" s t o r a g e "o f # +v a l u eo fs u b s h e l lv a r i a b l e . ( e c h o" W ea r ei n s i d et h es u b s h e l l . " e c h o" S u b s h e l ll e v e lI N S I D Es u b s h e l l=$ B A S H _ S U B S H E L L " i n n e r _ v a r i a b l e = I n n e r e c h o" F r o mi n s i d es u b s h e l l ,\ " i n n e r _ v a r i a b l e \ "=$ i n n e r _ v a r i a b l e " e c h o" F r o mi n s i d es u b s h e l l ,\ " o u t e r \ "=$ o u t e r _ v a r i a b l e " g l o b a l _ v a r i a b l e = " $ i n n e r _ v a r i a b l e " ) e c h o ;e c h o e c h o" W ea r eo u t s i d et h es u b s h e l l . " e c h o" S u b s h e l ll e v e lO U T S I D Es u b s h e l l=$ B A S H _ S U B S H E L L " e c h o i f[z" $ i n n e r _ v a r i a b l e "] t h e n e c h o" i n n e r _ v a r i a b l eu n d e f i n e di nm a i nb o d yo fs h e l l " e l s e e c h o" i n n e r _ v a r i a b l ed e f i n e di nm a i nb o d yo fs h e l l " f i e c h o" F r o mm a i nb o d yo fs h e l l ,\ " i n n e r _ v a r i a b l e \ "=$ i n n e r _ v a r i a b l e " # $ i n n e r _ v a r i a b l ew i l ls h o wa sb l a n k( u n i n i t i a l i z e d ) # +b e c a u s ev a r i a b l e sd e f i n e di nas u b s h e l la r e" l o c a lv a r i a b l e s " . # I st h e r ear e m e d yf o rt h i s ? e c h o" g l o b a l _ v a r i a b l e=" $ g l o b a l _ v a r i a b l e " " #W h yd o e s n ' tt h i sw o r k ? e c h o # W i l lt h i sa l l o w" e x p o r t i n g " # +as u b s h e l lv a r i a b l e ?

#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #A d d i t i o n a l l y. . . e c h o" " ;e c h o v a r = 4 1 #G l o b a lv a r i a b l e .

(l e t" v a r + = 1 " ;e c h o" \ $ v a rI N S I D Es u b s h e l l=$ v a r ") #4 2 e c h o" \ $ v a rO U T S I D Es u b s h e l l=$ v a r " #4 1 # V a r i a b l eo p e r a t i o n si n s i d eas u b s h e l l ,e v e nt oaG L O B A Lv a r i a b l e # +d on o ta f f e c tt h ev a l u eo ft h ev a r i a b l eo u t s i d et h es u b s h e l l !

e x i t0 # Q u e s t i o n : # # O n c eh a v i n ge x i t e das u b s h e l l , # +i st h e r ea n yw a yt or e e n t e rt h a tv e r ys a m es u b s h e l l # +t om o d i f yo ra c c e s st h es u b s h e l lv a r i a b l e s ?

See also $BASHPID and Example 34-2.


D e f i n i t i o n :The scope of a variable is the context in which it has meaning,

in which it has a value that can be referenced. For example, the scope of a local variable lies only within the function, block of code, or subshell within which it is defined, while the scope of a global variable is the entire script in which it appears. While the $BASH_SUBSHELL internal variable indicates the nesting level of a subshell, the $SHLVL variable shows no change within a subshell.
e c h o"\ $ B A S H _ S U B S H E L Lo u t s i d es u b s h e l l =$ B A S H _ S U B S H E L L " #0 (e c h o"\ $ B A S H _ S U B S H E L Li n s i d es u b s h e l l =$ B A S H _ S U B S H E L L ") #1 ((e c h o"\ $ B A S H _ S U B S H E L Li n s i d en e s t e ds u b s h e l l=$ B A S H _ S U B S H E L L "))#2 #^^ * * *n e s t e d* * * ^^ e c h o e c h o"\ $ S H L V Lo u t s i d es u b s h e l l=$ S H L V L " (e c h o"\ $ S H L V Li n s i d es u b s h e l l =$ S H L V L ") #3 #3( N oc h a n g e ! )

Directory changes made in a subshell do not carry over to the parent shell. Example 21-2. List User Profiles
# ! / b i n / b a s h #a l l p r o f s . s h :P r i n ta l lu s e rp r o f i l e s . #T h i ss c r i p tw r i t t e nb yH e i n e rS t e v e n ,a n dm o d i f i e db yt h ed o c u m e n ta u t h o r . F I L E = . b a s h r c # F i l ec o n t a i n i n gu s e rp r o f i l e , # +w a s" . p r o f i l e "i no r i g i n a ls c r i p t . f o rh o m ei n` a w kF :' { p r i n t$ 6 } '/ e t c / p a s s w d ` d o [d" $ h o m e "]| |c o n t i n u e #I fn oh o m ed i r e c t o r y ,g ot on e x t . [r" $ h o m e "]| |c o n t i n u e #I fn o tr e a d a b l e ,g ot on e x t . ( c d$ h o m e ;[e$ F I L E]& &l e s s$ F I L E ) d o n e # W h e ns c r i p tt e r m i n a t e s ,t h e r ei sn on e e dt o' c d 'b a c kt oo r i g i n a ld i r e c t o r y , # +b e c a u s e' c d$ h o m e 't a k e sp l a c ei nas u b s h e l l .

e x i t0

A subshell may be used to set up a "dedicated environment" for a command group.


C O M M A N D 1 C O M M A N D 2 C O M M A N D 3 ( I F S = : P A T H = / b i n u n s e tT E R M I N F O s e tC s h i f t5 C O M M A N D 4 C O M M A N D 5 e x i t3#O n l ye x i t st h es u b s h e l l ! ) #T h ep a r e n ts h e l lh a sn o tb e e na f f e c t e d ,a n dt h ee n v i r o n m e n ti sp r e s e r v e d . C O M M A N D 6 C O M M A N D 7

As seen here, the exit command only terminates the subshell in which it is running, not the parent shell or script. One application of such a "dedicated environment" is testing whether a variable is defined.
i f( s e tu ;:$ v a r i a b l e )2 >/ d e v / n u l l t h e n e c h o" V a r i a b l ei ss e t . " f i # V a r i a b l eh a sb e e ns e ti nc u r r e n ts c r i p t , # +o ri sa na ni n t e r n a lB a s hv a r i a b l e , # +o ri sp r e s e n ti ne n v i r o n m e n t( h a sb e e ne x p o r t e d ) . #C o u l da l s ob ew r i t t e n[ [$ { v a r i a b l e x }! =x| |$ { v a r i a b l e y }! =y] ] #o r [ [$ { v a r i a b l e x }! =x $ v a r i a b l e] ] #o r [ [$ { v a r i a b l e + x }=x] ] #o r [ [$ { v a r i a b l e x }! =x] ]

Another application is checking for a lock file:


i f( s e tC ;:>l o c k _ f i l e )2 >/ d e v / n u l l t h e n : #l o c k _ f i l ed i d n ' te x i s t :n ou s e rr u n n i n gt h es c r i p t e l s e e c h o" A n o t h e ru s e ri sa l r e a d yr u n n i n gt h a ts c r i p t . " e x i t6 5 f i # C o d es n i p p e tb yS t p h a n eC h a z e l a s , # +w i t hm o d i f i c a t i o n sb yP a u l oM a r c e lC o e l h oA r a g a o .

+ Processes may execute in parallel within different subshells. This permits breaking a complex task into subcomponents processed concurrently. Example 21-3. Running parallel processes in subshells
( c a tl i s t 1l i s t 2l i s t 3|s o r t|u n i q>l i s t 1 2 3 )& ( c a tl i s t 4l i s t 5l i s t 6|s o r t|u n i q>l i s t 4 5 6 )& #M e r g e sa n ds o r t sb o t hs e t so fl i s t ss i m u l t a n e o u s l y . #R u n n i n gi nb a c k g r o u n de n s u r e sp a r a l l e le x e c u t i o n . # #S a m ee f f e c ta s # c a tl i s t 1l i s t 2l i s t 3|s o r t|u n i q>l i s t 1 2 3& # c a tl i s t 4l i s t 5l i s t 6|s o r t|u n i q>l i s t 4 5 6& w a i t #D o n ' te x e c u t et h en e x tc o m m a n du n t i ls u b s h e l l sf i n i s h .

d i f fl i s t 1 2 3l i s t 4 5 6

Redirecting I/O to a subshell uses the "|" pipe operator, as in l sa l|( c o m m a n d ) . A code block between curly brackets does not launch a subshell. { command1; command2; command3; . . . commandN; }
v a r 1 = 2 3 e c h o" $ v a r 1 " {v a r 1 = 7 6 ;} e c h o" $ v a r 1 " #2 3

#7 6

Chapter 22. Restricted Shells


Disabled commands in restricted shells . Running a script or portion of a script in restricted mode disables certain commands that would otherwise be available. This is a security measure intended to limit the privileges of the script user and to minimize possible damage from running the script. The following commands and actions are disabled: Using c dto change the working directory. Changing the values of the $ P A T H ,$ S H E L L ,$ B A S H _ E N V , or $ E N Venvironmental variables. Reading or changing the $ S H E L L O P T S , shell environmental options. Output redirection. Invoking commands containing one or more /'s. Invoking exec to substitute a different process for the shell. Various other commands that would enable monkeying with or attempting to subvert the script for an unintended purpose. Getting out of restricted mode within the script. Example 22-1. Running a script in restricted mode
# ! / b i n / b a s h # S t a r t i n gt h es c r i p tw i t h" # ! / b i n / b a s hr " # +r u n se n t i r es c r i p ti nr e s t r i c t e dm o d e . e c h o e c h o" C h a n g i n gd i r e c t o r y . " c d/ u s r / l o c a l e c h o" N o wi n` p w d ` " e c h o" C o m i n gb a c kh o m e . " c d e c h o" N o wi n` p w d ` " e c h o #E v e r y t h i n gu pt oh e r ei nn o r m a l ,u n r e s t r i c t e dm o d e . s e tr #s e tr e s t r i c t e d

h a ss a m ee f f e c t .

e c h o" = = >N o wi nr e s t r i c t e dm o d e .< = = " e c h o e c h o e c h o" A t t e m p t i n gd i r e c t o r yc h a n g ei nr e s t r i c t e dm o d e . " c d. . e c h o" S t i l li n` p w d ` " e c h o e c h o e c h o" \ $ S H E L L=$ S H E L L " e c h o" A t t e m p t i n gt oc h a n g es h e l li nr e s t r i c t e dm o d e . " S H E L L = " / b i n / a s h " e c h o e c h o" \ $ S H E L L =$ S H E L L " e c h o e c h o e c h o" A t t e m p t i n gt or e d i r e c to u t p u ti nr e s t r i c t e dm o d e . " l sl/ u s r / b i n>b i n . f i l e s l slb i n . f i l e s #T r yt ol i s ta t t e m p t e df i l ec r e a t i o ne f f o r t . e c h o e x i t0

Chapter 23. Process Substitution


Piping the s t d o u tof a command into the s t d i nof another is a powerful technique. But, what if you need to pipe the s t d o u tof multiple commands? This is where p r o c e s ss u b s t i t u t i o ncomes in. Process substitution feeds the output of a process (or processes) into the s t d i nof another process. Template Command list enclosed within parentheses >(command_list) <(command_list) Process substitution uses / d e v / f d / < n >files to send the results of the process(es) within parentheses to another process. [108] There is no space between the the "<" or ">" and the parentheses. Space there would give an error message.
b a s h $e c h o> ( t r u e ) / d e v / f d / 6 3 b a s h $e c h o< ( t r u e ) / d e v / f d / 6 3 b a s h $e c h o> ( t r u e )< ( t r u e ) / d e v / f d / 6 3/ d e v / f d / 6 2

b a s h $w c< ( c a t/ u s r / s h a r e / d i c t / l i n u x . w o r d s ) 4 8 3 5 2 3 4 8 3 5 2 34 9 9 2 0 1 0/ d e v / f d / 6 3

b a s h $g r e ps c r i p t/ u s r / s h a r e / d i c t / l i n u x . w o r d s|w c 2 6 2 2 6 2 3 6 0 1 b a s h $w c< ( g r e ps c r i p t/ u s r / s h a r e / d i c t / l i n u x . w o r d s ) 2 6 2 2 6 2 3 6 0 1/ d e v / f d / 6 3

Bash creates a pipe with two file descriptors, f I nand f O u t . The s t d i nof true connects to f O u t(dup2(fOut, 0)), then Bash passes a / d e v / f d / f I nargument to echo. On systems lacking / d e v / f d / < n >files, Bash may use temporary files. (Thanks, S.C.) Process substitution can compare the output of two different commands, or even the output of different options to the same command.
b a s h $c o m m< ( l sl )< ( l sa l ) t o t a l1 2 r w r w r 1b o z ob o z o 7 8M a r1 01 2 : 5 8F i l e 0 r w r w r 1b o z ob o z o 4 2M a r1 01 2 : 5 8F i l e 2 r w r w r 1b o z ob o z o 1 0 3M a r1 01 2 : 5 8t 2 . s h t o t a l2 0 d r w x r w x r w x 2b o z ob o z o 4 0 9 6M a r1 01 8 : 1 0. d r w x - 7 2b o z ob o z o 4 0 9 6M a r1 01 7 : 5 8. . r w r w r 1b o z ob o z o 7 8M a r1 01 2 : 5 8F i l e 0 r w r w r 1b o z ob o z o 4 2M a r1 01 2 : 5 8F i l e 2 r w r w r 1b o z ob o z o 1 0 3M a r1 01 2 : 5 8t 2 . s h

Process substitution can compare the contents of two directories -- to see which filenames are in one, but not the other.
d i f f< ( l s$ f i r s t _ d i r e c t o r y )< ( l s$ s e c o n d _ d i r e c t o r y )

Some other usages and uses of process substitution:


r e a dal i s t<< (o dA dw 2 4tu 2/ d e v / u r a n d o m) # R e a dal i s to fr a n d o mn u m b e r sf r o m/ d e v / u r a n d o m , # +p r o c e s sw i t h" o d " # +a n df e e di n t os t d i no f" r e a d "... # F r o m" i n s e r t i o n s o r t . b a s h "e x a m p l es c r i p t . # C o u r t e s yo fJ u a n J oC i a r l a n t e . P O R T = 6 8 8 1 #b i t t o r r e n t

#S c a nt h ep o r tt om a k es u r en o t h i n gn e f a r i o u si sg o i n go n . n e t c a tl$ P O R T|t e e > ( m d 5 s u m> m y d a t a o r i g . m d 5 )| g z i p|t e e > ( m d 5 s u m-|s e d' s / $ / m y d a t a . l z 2 / ' > m y d a t a g z . m d 5 ) > m y d a t a . g z #C h e c kt h ed e c o m p r e s s i o n : g z i pd < m y d a t a . g z|m d 5 s u mcm y d a t a o r i g . m d 5 ) #T h eM D 5 s u mo ft h eo r i g i n a lc h e c k ss t d i na n dd e t e c t sc o m p r e s s i o ni s s u e s . # B i l lD a v i d s e nc o n t r i b u t e dt h i se x a m p l e # +( w i t hl i g h te d i t sb yt h eA B SG u i d ea u t h o r ) . c a t< ( l sl ) #S a m ea s l sl|c a t s o r tk9< ( l sl/ b i n )< ( l sl/ u s r / b i n )< ( l sl/ u s r / X 1 1 R 6 / b i n ) #L i s t sa l lt h ef i l e si nt h e3m a i n' b i n 'd i r e c t o r i e s ,a n ds o r t sb yf i l e n a m e . #N o t et h a tt h r e e( c o u n t' e m )d i s t i n c tc o m m a n d sa r ef e dt o' s o r t ' .

d i f f< ( c o m m a n d 1 )< ( c o m m a n d 2 )

#G i v e sd i f f e r e n c ei nc o m m a n do u t p u t .

t a rc f> ( b z i p 2c>f i l e . t a r . b z 2 )$ d i r e c t o r y _ n a m e

#C a l l s" t a rc f/ d e v / f d / ? ?$ d i r e c t o r y _ n a m e " ,a n d" b z i p 2c>f i l e . t a r . b z 2 " . # #B e c a u s eo ft h e/ d e v / f d / < n >s y s t e mf e a t u r e , #t h ep i p eb e t w e e nb o t hc o m m a n d sd o e sn o tn e e dt ob en a m e d . # #T h i sc a nb ee m u l a t e d . # b z i p 2c<p i p e>f i l e . t a r . b z 2 & t a rc fp i p e$ d i r e c t o r y _ n a m e r mp i p e # o r e x e c3 > & 1 t a rc f/ d e v / f d / 4$ d i r e c t o r y _ n a m e4 > & 1> & 33 > & -|b z i p 2c>f i l e . t a r . b z 23 > & e x e c3 > & -

#T h a n k s ,S t p h a n eC h a z e l a s

Here is a method of circumventing the problem of an echo piped to a while-read loop running in a subshell. Example 23-1. Code block redirection without forking
# ! / b i n / b a s h #w r p s . b a s h :w h i l e r e a dl o o pw i t hp r o c e s ss u b s t i t u t i o n . #T h i se x a m p l ec o n t r i b u t e db yT o m a sP o s p i s e k . #( H e a v i l ye d i t e db yt h eA B SG u i d ea u t h o r . ) e c h o e c h o" r a n d o mi n p u t "|w h i l er e a di d o g l o b a l = 3 D " :N o ta v a i l a b l eo u t s i d et h el o o p . " #. . .b e c a u s ei tr u n si nas u b s h e l l . d o n e e c h o" \ $ g l o b a l( f r o mo u t s i d et h es u b p r o c e s s )=$ g l o b a l " #$ g l o b a l( f r o mo u t s i d et h es u b p r o c e s s )= e c h o ;e c h o" " ;e c h o w h i l er e a di d o e c h o$ i g l o b a l = 3 D " :A v a i l a b l eo u t s i d et h el o o p . " #. . .b e c a u s ei td o e sN O Tr u ni nas u b s h e l l . d o n e<< (e c h o" r a n d o mi n p u t ") # ^^ e c h o" \ $ g l o b a l( u s i n gp r o c e s ss u b s t i t u t i o n )=$ g l o b a l " #R a n d o mi n p u t #$ g l o b a l( u s i n gp r o c e s ss u b s t i t u t i o n )=3 D :A v a i l a b l eo u t s i d et h el o o p .

e c h o ;e c h o" # # # # # # # # # # " ;e c h o

#A n dl i k e w i s e... d e c l a r eai n l o o p i n d e x = 0 c a t$ 0|w h i l er e a dl i n e d o i n l o o p [ $ i n d e x ] = " $ l i n e " ( ( i n d e x + + ) ) #I tr u n si nas u b s h e l l ,s o. . . d o n e

e c h o" O U T P U T=" e c h o$ { i n l o o p [ * ] }

#. . .n o t h i n ge c h o e s .

e c h o ;e c h o" " ;e c h o

d e c l a r eao u t l o o p i n d e x = 0 w h i l er e a dl i n e d o o u t l o o p [ $ i n d e x ] = " $ l i n e " ( ( i n d e x + + ) ) #I td o e sN O Tr u ni nas u b s h e l l ,s o. . . d o n e<< (c a t$ 0) e c h o" O U T P U T=" e c h o$ { o u t l o o p [ * ] } #. . .t h ee n t i r es c r i p te c h o e s . e x i t$ ?

This is a similar example. Example 23-2. Redirecting the output of process substitution into a loop.
# ! / b i n / b a s h #p s u b . b a s h #A si n s p i r e db yD i e g oM o l i n a( t h a n k s ! ) . d e c l a r eaa r r a y 0 w h i l er e a d d o a r r a y 0 [ $ { # a r r a y 0 [ @ ] } ] = " $ R E P L Y " d o n e<< (s e de' s / b a s h / C R A S H B A N G ! / '$ 0|g r e pb i n|a w k' { p r i n t$ 1 } ') # S e t st h ed e f a u l t' r e a d 'v a r i a b l e ,$ R E P L Y ,b yp r o c e s ss u b s t i t u t i o n , # +t h e nc o p i e si ti n t oa na r r a y . e c h o" $ { a r r a y 0 [ @ ] } " e x i t$ ? #= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =# b a s hp s u b . b a s h # ! / b i n / C R A S H B A N G !d o n e# ! / b i n / C R A S H B A N G !

A reader sent in the following interesting example of process substitution.


#S c r i p tf r a g m e n tt a k e nf r o mS u S Ed i s t r i b u t i o n : ## w h i l er e a d d e sw h a tm a s ki f a c e ;d o #S o m ec o m m a n d s. . . d o n e<< ( r o u t en ) # ^^ F i r s t<i sr e d i r e c t i o n ,s e c o n di sp r o c e s ss u b s t i t u t i o n . #T ot e s ti t ,l e t ' sm a k ei td os o m e t h i n g . w h i l er e a d d e sw h a tm a s ki f a c e ;d o e c h o$ d e s$ w h a t$ m a s k$ i f a c e d o n e<< ( r o u t en ) #O u t p u t : #K e r n e lI Pr o u t i n gt a b l e #D e s t i n a t i o nG a t e w a yG e n m a s kF l a g sM e t r i cR e fU s eI f a c e #1 2 7 . 0 . 0 . 00 . 0 . 0 . 02 5 5 . 0 . 0 . 0U000l o ##

# A sS t p h a n eC h a z e l a sp o i n t so u t , # +a ne a s i e r t o u n d e r s t a n de q u i v a l e n ti s : r o u t en| w h i l er e a dd e sw h a tm a s ki f a c e ;d o #V a r i a b l e ss e tf r o mo u t p u to fp i p e . e c h o$ d e s$ w h a t$ m a s k$ i f a c e d o n e # T h i sy i e l d st h es a m eo u t p u ta sa b o v e . # H o w e v e r ,a sU l r i c hG a y e rp o i n t so u t... # +t h i ss i m p l i f i e de q u i v a l e n tu s e sas u b s h e l lf o rt h ew h i l el o o p , # +a n dt h e r e f o r et h ev a r i a b l e sd i s a p p e a rw h e nt h ep i p et e r m i n a t e s . ## # H o w e v e r ,F i l i pM o r i t zc o m m e n t st h a tt h e r ei sas u b t l ed i f f e r e n c e # +b e t w e e nt h ea b o v et w oe x a m p l e s ,a st h ef o l l o w i n gs h o w s . ( r o u t en|w h i l er e a dx ;d o( ( y + + ) ) ;d o n e e c h o$ y#$ yi ss t i l lu n s e t w h i l er e a dx ;d o( ( y + + ) ) ;d o n e<< ( r o u t en ) e c h o$ y#$ yh a st h en u m b e ro fl i n e so fo u t p u to fr o u t en ) M o r eg e n e r a l l ys p o k e n ( :|x = x #s e e m st os t a r tas u b s h e l ll i k e :|(x = x) #w h i l e x = x<< ( : ) #d o e sn o t ) #T h i si su s e f u l ,w h e np a r s i n gc s va n dt h el i k e . #T h a ti s ,i ne f f e c t ,w h a tt h eo r i g i n a lS u S Ec o d ef r a g m e n td o e s .

Chapter 24. Functions


Like "real" programming languages, Bash has functions, though in a somewhat limited implementation. A function is a subroutine, a code block that implements a set of operations, a "black box" that performs a specified task. Wherever there is repetitive code, when a task repeats with only slight variations in procedure, then consider using a function. function f u n c t i o n _ n a m e{ c o m m a n d ... } or
f u n c t i o n _ n a m e() { c o m m a n d ...

} This second form will cheer the hearts of C programmers (and is more portable). As in C, the function's opening bracket may optionally appear on the second line.
f u n c t i o n _ n a m e()

{
c o m m a n d ...

A function may be "compacted" into a single line.


f u n( ){e c h o" T h i si saf u n c t i o n " ;e c h o ;} # ^ ^

In this case, however, a semicolon must follow the final command in the function.
f u n( ){e c h o" T h i si saf u n c t i o n " ;e c h o}#E r r o r ! # ^ f u n 2( ){e c h o" E v e nas i n g l e c o m m a n df u n c t i o n ?Y e s ! " ;} # ^

Functions are called, triggered, simply by invoking their names. A function call is equivalent to a command. Example 24-1. Simple functions
# ! / b i n / b a s h #e x 5 9 . s h :E x e r c i s i n gf u n c t i o n s( s i m p l e ) . J U S T _ A _