Easily find issues by searching: #<Issue ID>
Example: #1832
Easily find members by searching in: <username>, <first name> and <last name>.
Example: Search smith, will return results smith and adamsmith
These scripts, while not fitting into the text of this document, do illustrate some interesting shell programming techniques. Some are useful, too. Have fun analyzing and running them.
Example A-1. mailformat: Formatting an e-mail message
#!/bin/bash # mail-format.sh (ver. 1.1): Format e-mail messages. # Gets rid of carets, tabs, and also folds excessively long lines. # ================================================================= # Standard Check for Script Argument(s) ARGS=1 E_BADARGS=65 E_NOFILE=66 if [ $# -ne $ARGS ] # Correct number of arguments passed to script? then echo "Usage: `basename $0` filename" exit $E_BADARGS fi if [ -f "$1" ] # Check if file exists. then file_name=$1 else echo "File \"$1\" does not exist." exit $E_NOFILE fi # ================================================================= MAXWIDTH=70 # Width to fold excessively long lines to. # --------------------------------- # A variable can hold a sed script. sedscript='s/^>// s/^ *>// s/^ *// s/ *//' # --------------------------------- # Delete carets and tabs at beginning of lines, #+ then fold lines to $MAXWIDTH characters. sed "$sedscript" $1 | fold -s --width=$MAXWIDTH # -s option to "fold" #+ breaks lines at whitespace, if possible. # This script was inspired by an article in a well-known trade journal #+ extolling a 164K MS Windows utility with similar functionality. # # An nice set of text processing utilities and an efficient #+ scripting language provide an alternative to bloated executables. exit
Example A-2. rn: A simple-minded file renaming utility
This script is a modification of Example 16-22.
#! /bin/bash # rn.sh # Very simpleminded filename "rename" utility (based on "lowercase.sh"). # # The "ren" utility, by Vladimir Lanin ([email protected]), #+ does a much better job of this. ARGS=2 E_BADARGS=85 ONE=1 # For getting singular/plural right (see below). if [ $# -ne "$ARGS" ] then echo "Usage: `basename $0` old-pattern new-pattern" # As in "rn gif jpg", which renames all gif files in working directory to jpg. exit $E_BADARGS fi number=0 # Keeps track of how many files actually renamed. for filename in *$1* #Traverse all matching files in directory. do if [ -f "$filename" ] # If finds match... then fname=`basename $filename` # Strip off path. n=`echo $fname | sed -e "s/$1/$2/"` # Substitute new for old in filename. mv $fname $n # Rename. let "number += 1" fi done if [ "$number" -eq "$ONE" ] # For correct grammar. then echo "$number file renamed." else echo "$number files renamed." fi exit $? # Exercises: # --------- # What types of files will this not work on? # How can this be fixed?
Example A-3. blank-rename: Renames filenames containing blanks
This is an even simpler-minded version of previous script.
#! /bin/bash # blank-rename.sh # # Substitutes underscores for blanks in all the filenames in a directory. ONE=1 # For getting singular/plural right (see below). number=0 # Keeps track of how many files actually renamed. FOUND=0 # Successful return value. for filename in * #Traverse all files in directory. do echo "$filename" | grep -q " " # Check whether filename if [ $? -eq $FOUND ] #+ contains space(s). then fname=$filename # Yes, this filename needs work. n=`echo $fname | sed -e "s/ /_/g"` # Substitute underscore for blank. mv "$fname" "$n" # Do the actual renaming. let "number += 1" fi done if [ "$number" -eq "$ONE" ] # For correct grammar. then echo "$number file renamed." else echo "$number files renamed." fi exit 0
Example A-4. encryptedpw: Uploading to an ftp site, using a locally encrypted password
#!/bin/bash # Example "ex72.sh" modified to use encrypted password. # Note that this is still rather insecure, #+ since the decrypted password is sent in the clear. # Use something like "ssh" if this is a concern. E_BADARGS=85 if [ -z "$1" ] then echo "Usage: `basename $0` filename" exit $E_BADARGS fi Username=bozo # Change to suit. pword=/home/bozo/secret/password_encrypted.file # File containing encrypted password. Filename=`basename $1` # Strips pathname out of file name. Server="XXX" Directory="YYY" # Change above to actual server name & directory. Password=`cruft <$pword` # Decrypt password. # Uses the author's own "cruft" file encryption package, #+ based on the classic "onetime pad" algorithm, #+ and obtainable from: #+ Primary-site: ftp://ibiblio.org/pub/Linux/utils/file #+ cruft-0.2.tar.gz [16k] ftp -n $Server <<End-Of-Session user $Username $Password binary bell cd $Directory put $Filename bye End-Of-Session # -n option to "ftp" disables auto-logon. # Note that "bell" rings 'bell' after each file transfer. exit 0
Example A-5. copy-cd: Copying a data CD
#!/bin/bash # copy-cd.sh: copying a data CD CDROM=/dev/cdrom # CD ROM device OF=/home/bozo/projects/cdimage.iso # output file # /xxxx/xxxxxxxx/ Change to suit your system. BLOCKSIZE=2048 # SPEED=10 # If unspecified, uses max spd. # DEVICE=/dev/cdrom older version. DEVICE="1,0,0" echo; echo "Insert source CD, but do *not* mount it." echo "Press ENTER when ready. " read ready # Wait for input, $ready not used. echo; echo "Copying the source CD to $OF." echo "This may take a while. Please be patient." dd if=$CDROM of=$OF bs=$BLOCKSIZE # Raw device copy. echo; echo "Remove data CD." echo "Insert blank CDR." echo "Press ENTER when ready. " read ready # Wait for input, $ready not used. echo "Copying $OF to CDR." # cdrecord -v -isosize speed=$SPEED dev=$DEVICE $OF # Old version. wodim -v -isosize dev=$DEVICE $OF # Uses Joerg Schilling's "cdrecord" package (see its docs). # http://www.fokus.gmd.de/nthp/employees/schilling/cdrecord.html # Newer Linux distros may use "wodim" rather than "cdrecord" ... echo; echo "Done copying $OF to CDR on device $CDROM." echo "Do you want to erase the image file (y/n)? " # Probably a huge file. read answer case "$answer" in [yY]) rm -f $OF echo "$OF erased." ;; *) echo "$OF not erased.";; esac echo # Exercise: # Change the above "case" statement to also accept "yes" and "Yes" as input. exit 0
Example A-6. Collatz series
#!/bin/bash # collatz.sh # The notorious "hailstone" or Collatz series. # ------------------------------------------- # 1) Get the integer "seed" from the command-line. # 2) NUMBER <-- seed # 3) Print NUMBER. # 4) If NUMBER is even, divide by 2, or # 5)+ if odd, multiply by 3 and add 1. # 6) NUMBER <-- result # 7) Loop back to step 3 (for specified number of iterations). # # The theory is that every such sequence, #+ no matter how large the initial value, #+ eventually settles down to repeating "4,2,1..." cycles, #+ even after fluctuating through a wide range of values. # # This is an instance of an "iterate," #+ an operation that feeds its output back into its input. # Sometimes the result is a "chaotic" series. MAX_ITERATIONS=200 # For large seed numbers (>32000), try increasing MAX_ITERATIONS. h=${1:-$$} # Seed. # Use $PID as seed, #+ if not specified as command-line arg. echo echo "C($h) -*- $MAX_ITERATIONS Iterations" echo for ((i=1; i<=MAX_ITERATIONS; i++)) do # echo -n "$h " # ^^^ # tab # printf does it better ... COLWIDTH=%7d printf $COLWIDTH $h let "remainder = h % 2" if [ "$remainder" -eq 0 ] # Even? then let "h /= 2" # Divide by 2. else let "h = h*3 + 1" # Multiply by 3 and add 1. fi COLUMNS=10 # Output 10 values per line. let "line_break = i % $COLUMNS" if [ "$line_break" -eq 0 ] then echo fi done echo # For more information on this strange mathematical function, #+ see _Computers, Pattern, Chaos, and Beauty_, by Pickover, p. 185 ff., #+ as listed in the bibliography. exit 0
Example A-7. days-between: Days between two dates
#!/bin/bash # days-between.sh: Number of days between two dates. # Usage: ./days-between.sh [M]M/[D]D/YYYY [M]M/[D]D/YYYY # # Note: Script modified to account for changes in Bash, v. 2.05b +, #+ that closed the loophole permitting large negative #+ integer return values. ARGS=2 # Two command-line parameters expected. E_PARAM_ERR=85 # Param error. REFYR=1600 # Reference year. CENTURY=100 DIY=365 ADJ_DIY=367 # Adjusted for leap year + fraction. MIY=12 DIM=31 LEAPCYCLE=4 MAXRETVAL=255 # Largest permissible #+ positive return value from a function. diff= # Declare global variable for date difference. value= # Declare global variable for absolute value. day= # Declare globals for day, month, year. month= year= Param_Error () # Command-line parameters wrong. { echo "Usage: `basename $0` [M]M/[D]D/YYYY [M]M/[D]D/YYYY" echo " (date must be after 1/3/1600)" exit $E_PARAM_ERR } Parse_Date () # Parse date from command-line params. { month=${1%%/**} dm=${1%/**} # Day and month. day=${dm#*/} let "year = `basename $1`" # Not a filename, but works just the same. } check_date () # Checks for invalid date(s) passed. { [ "$day" -gt "$DIM" ] || [ "$month" -gt "$MIY" ] || [ "$year" -lt "$REFYR" ] && Param_Error # Exit script on bad value(s). # Uses or-list / and-list. # # Exercise: Implement more rigorous date checking. } strip_leading_zero () # Better to strip possible leading zero(s) { #+ from day and/or month return ${1#0} #+ since otherwise Bash will interpret them } #+ as octal values (POSIX.2, sect 2.9.2.1). day_index () # Gauss' Formula: { # Days from March 1, 1600 to date passed as param. # ^^^^^^^^^^^^^ day=$1 month=$2 year=$3 let "month = $month - 2" if [ "$month" -le 0 ] then let "month += 12" let "year -= 1" fi let "year -= $REFYR" let "indexyr = $year / $CENTURY" let "Days = $DIY*$year + $year/$LEAPCYCLE - $indexyr \ + $indexyr/$LEAPCYCLE + $ADJ_DIY*$month/$MIY + $day - $DIM" # For an in-depth explanation of this algorithm, see #+ http://weblogs.asp.net/pgreborio/archive/2005/01/06/347968.aspx echo $Days } calculate_difference () # Difference between two day indices. { let "diff = $1 - $2" # Global variable. } abs () # Absolute value { # Uses global "value" variable. if [ "$1" -lt 0 ] # If negative then #+ then let "value = 0 - $1" #+ change sign, else #+ else let "value = $1" #+ leave it alone. fi } if [ $# -ne "$ARGS" ] # Require two command-line params. then Param_Error fi Parse_Date $1 check_date $day $month $year # See if valid date. strip_leading_zero $day # Remove any leading zeroes day=$? #+ on day and/or month. strip_leading_zero $month month=$? let "date1 = `day_index $day $month $year`" Parse_Date $2 check_date $day $month $year strip_leading_zero $day day=$? strip_leading_zero $month month=$? date2=$(day_index $day $month $year) # Command substitution. calculate_difference $date1 $date2 abs $diff # Make sure it's positive. diff=$value echo $diff exit 0 # Exercise: # -------- # If given only one command-line parameter, have the script #+ use today's date as the second. # Compare this script with #+ the implementation of Gauss' Formula in a C program at #+ http://buschencrew.hypermart.net/software/datedif
Example A-8. Making a dictionary
#!/bin/bash # makedict.sh [make dictionary] # Modification of /usr/sbin/mkdict (/usr/sbin/cracklib-forman) script. # Original script copyright 1993, by Alec Muffett. # # This modified script included in this document in a manner #+ consistent with the "LICENSE" document of the "Crack" package #+ that the original script is a part of. # This script processes text files to produce a sorted list #+ of words found in the files. # This may be useful for compiling dictionaries #+ and for other lexicographic purposes. E_BADARGS=65 if [ ! -r "$1" ] # Need at least one then #+ valid file argument. echo "Usage: $0 files-to-process" exit $E_BADARGS fi # SORT="sort" # No longer necessary to define #+ options to sort. Changed from #+ original script. cat $* | # Contents of specified files to stdout. tr A-Z a-z | # Convert to lowercase. tr ' ' '\012' | # New: change spaces to newlines. # tr -cd '\012[a-z][0-9]' | # Get rid of everything #+ non-alphanumeric (in orig. script). tr -c '\012a-z' '\012' | # Rather than deleting non-alpha #+ chars, change them to newlines. sort | # $SORT options unnecessary now. uniq | # Remove duplicates. grep -v '^#' | # Delete lines starting with hashmark. grep -v '^$' # Delete blank lines. exit 0
Example A-9. Soundex conversion
#!/bin/bash # soundex.sh: Calculate "soundex" code for names # ======================================================= # Soundex script # by # Mendel Cooper # [email protected] # reldate: 23 January, 2002 # # Placed in the Public Domain. # # A slightly different version of this script appeared in #+ Ed Schaefer's July, 2002 "Shell Corner" column #+ in "Unix Review" on-line, #+ http://www.unixreview.com/documents/uni1026336632258/ # ======================================================= ARGCOUNT=1 # Need name as argument. E_WRONGARGS=90 if [ $# -ne "$ARGCOUNT" ] then echo "Usage: `basename $0` name" exit $E_WRONGARGS fi assign_value () # Assigns numerical value { #+ to letters of name. val1=bfpv # 'b,f,p,v' = 1 val2=cgjkqsxz # 'c,g,j,k,q,s,x,z' = 2 val3=dt # etc. val4=l val5=mn val6=r # Exceptionally clever use of 'tr' follows. # Try to figure out what is going on here. value=$( echo "$1" \ | tr -d wh \ | tr $val1 1 | tr $val2 2 | tr $val3 3 \ | tr $val4 4 | tr $val5 5 | tr $val6 6 \ | tr -s 123456 \ | tr -d aeiouy ) # Assign letter values. # Remove duplicate numbers, except when separated by vowels. # Ignore vowels, except as separators, so delete them last. # Ignore 'w' and 'h', even as separators, so delete them first. # # The above command substitution lays more pipe than a plumber <g>. } input_name="$1" echo echo "Name = $input_name" # Change all characters of name input to lowercase. # ------------------------------------------------ name=$( echo $input_name | tr A-Z a-z ) # ------------------------------------------------ # Just in case argument to script is mixed case. # Prefix of soundex code: first letter of name. # -------------------------------------------- char_pos=0 # Initialize character position. prefix0=${name:$char_pos:1} prefix=`echo $prefix0 | tr a-z A-Z` # Uppercase 1st letter of soundex. let "char_pos += 1" # Bump character position to 2nd letter of name. name1=${name:$char_pos} # ++++++++++++++++++++++++++ Exception Patch ++++++++++++++++++++++++++++++ # Now, we run both the input name and the name shifted one char #+ to the right through the value-assigning function. # If we get the same value out, that means that the first two characters #+ of the name have the same value assigned, and that one should cancel. # However, we also need to test whether the first letter of the name #+ is a vowel or 'w' or 'h', because otherwise this would bollix things up. char1=`echo $prefix | tr A-Z a-z` # First letter of name, lowercased. assign_value $name s1=$value assign_value $name1 s2=$value assign_value $char1 s3=$value s3=9$s3 # If first letter of name is a vowel #+ or 'w' or 'h', #+ then its "value" will be null (unset). #+ Therefore, set it to 9, an otherwise #+ unused value, which can be tested for. if [[ "$s1" -ne "$s2" || "$s3" -eq 9 ]] then suffix=$s2 else suffix=${s2:$char_pos} fi # ++++++++++++++++++++++ end Exception Patch ++++++++++++++++++++++++++++++ padding=000 # Use at most 3 zeroes to pad. soun=$prefix$suffix$padding # Pad with zeroes. MAXLEN=4 # Truncate to maximum of 4 chars. soundex=${soun:0:$MAXLEN} echo "Soundex = $soundex" echo # The soundex code is a method of indexing and classifying names #+ by grouping together the ones that sound alike. # The soundex code for a given name is the first letter of the name, #+ followed by a calculated three-number code. # Similar sounding names should have almost the same soundex codes. # Examples: # Smith and Smythe both have a "S-530" soundex. # Harrison = H-625 # Hargison = H-622 # Harriman = H-655 # This works out fairly well in practice, but there are numerous anomalies. # # # The U.S. Census and certain other governmental agencies use soundex, # as do genealogical researchers. # # For more information, #+ see the "National Archives and Records Administration home page", #+ http://www.nara.gov/genealogy/soundex/soundex.html # Exercise: # -------- # Simplify the "Exception Patch" section of this script. exit 0
Example A-10. Game of Life
#!/bin/bash # life.sh: "Life in the Slow Lane" # Author: Mendel Cooper # License: GPL3 # Version 0.2: Patched by Daniel Albers #+ to allow non-square grids as input. # Version 0.2.1: Added 2-second delay between generations. # ##################################################################### # # This is the Bash script version of John Conway's "Game of Life". # # "Life" is a simple implementation of cellular automata. # # --------------------------------------------------------------------- # # On a rectangular grid, let each "cell" be either "living" or "dead." # # Designate a living cell with a dot, and a dead one with a blank space.# # Begin with an arbitrarily drawn dot-and-blank grid, # #+ and let this be the starting generation: generation 0. # # Determine each successive generation by the following rules: # # 1) Each cell has 8 neighbors, the adjoining cells # #+ left, right, top, bottom, and the 4 diagonals. # # # # 123 # # 4*5 The * is the cell under consideration. # # 678 # # # # 2) A living cell with either 2 or 3 living neighbors remains alive. # SURVIVE=2 # # 3) A dead cell with 3 living neighbors comes alive, a "birth." # BIRTH=3 # # 4) All other cases result in a dead cell for the next generation. # # ##################################################################### # startfile=gen0 # Read the starting generation from the file "gen0" ... # Default, if no other file specified when invoking script. # if [ -n "$1" ] # Specify another "generation 0" file. then startfile="$1" fi ############################################ # Abort script if "startfile" not specified #+ and #+ default file "gen0" not present. E_NOSTARTFILE=86 if [ ! -e "$startfile" ] then echo "Startfile \""$startfile"\" missing!" exit $E_NOSTARTFILE fi ############################################ ALIVE1=. DEAD1=_ # Represent living and dead cells in the start-up file. # -----------------------------------------------------# # This script uses a 10 x 10 grid (may be increased, #+ but a large grid will slow down execution). ROWS=10 COLS=10 # Change above two variables to match desired grid size. # -----------------------------------------------------# GENERATIONS=10 # How many generations to cycle through. # Adjust this upwards #+ if you have time on your hands. NONE_ALIVE=85 # Exit status on premature bailout, #+ if no cells left alive. DELAY=2 # Pause between generations. TRUE=0 FALSE=1 ALIVE=0 DEAD=1 avar= # Global; holds current generation. generation=0 # Initialize generation count. # ================================================================= let "cells = $ROWS * $COLS" # How many cells. # Arrays containing "cells." declare -a initial declare -a current display () { alive=0 # How many cells alive at any given time. # Initially zero. declare -a arr arr=( `echo "$1"` ) # Convert passed arg to array. element_count=${#arr[*]} local i local rowcheck for ((i=0; i<$element_count; i++)) do # Insert newline at end of each row. let "rowcheck = $i % COLS" if [ "$rowcheck" -eq 0 ] then echo # Newline. echo -n " " # Indent. fi cell=${arr[i]} if [ "$cell" = . ] then let "alive += 1" fi echo -n "$cell" | sed -e 's/_/ /g' # Print out array, changing underscores to spaces. done return } IsValid () # Test if cell coordinate valid. { if [ -z "$1" -o -z "$2" ] # Mandatory arguments missing? then return $FALSE fi local row local lower_limit=0 # Disallow negative coordinate. local upper_limit local left local right let "upper_limit = $ROWS * $COLS - 1" # Total number of cells. if [ "$1" -lt "$lower_limit" -o "$1" -gt "$upper_limit" ] then return $FALSE # Out of array bounds. fi row=$2 let "left = $row * $COLS" # Left limit. let "right = $left + $COLS - 1" # Right limit. if [ "$1" -lt "$left" -o "$1" -gt "$right" ] then return $FALSE # Beyond row boundary. fi return $TRUE # Valid coordinate. } IsAlive () # Test whether cell is alive. # Takes array, cell number, and { #+ state of cell as arguments. GetCount "$1" $2 # Get alive cell count in neighborhood. local nhbd=$? if [ "$nhbd" -eq "$BIRTH" ] # Alive in any case. then return $ALIVE fi if [ "$3" = "." -a "$nhbd" -eq "$SURVIVE" ] then # Alive only if previously alive. return $ALIVE fi return $DEAD # Defaults to dead. } GetCount () # Count live cells in passed cell's neighborhood. # Two arguments needed: # $1) variable holding array # $2) cell number { local cell_number=$2 local array local top local center local bottom local r local row local i local t_top local t_cen local t_bot local count=0 local ROW_NHBD=3 array=( `echo "$1"` ) let "top = $cell_number - $COLS - 1" # Set up cell neighborhood. let "center = $cell_number - 1" let "bottom = $cell_number + $COLS - 1" let "r = $cell_number / $COLS" for ((i=0; i<$ROW_NHBD; i++)) # Traverse from left to right. do let "t_top = $top + $i" let "t_cen = $center + $i" let "t_bot = $bottom + $i" let "row = $r" # Count center row. IsValid $t_cen $row # Valid cell position? if [ $? -eq "$TRUE" ] then if [ ${array[$t_cen]} = "$ALIVE1" ] # Is it alive? then # If yes, then ... let "count += 1" # Increment count. fi fi let "row = $r - 1" # Count top row. IsValid $t_top $row if [ $? -eq "$TRUE" ] then if [ ${array[$t_top]} = "$ALIVE1" ] # Redundancy here. then # Can it be optimized? let "count += 1" fi fi let "row = $r + 1" # Count bottom row. IsValid $t_bot $row if [ $? -eq "$TRUE" ] then if [ ${array[$t_bot]} = "$ALIVE1" ] then let "count += 1" fi fi done if [ ${array[$cell_number]} = "$ALIVE1" ] then let "count -= 1" # Make sure value of tested cell itself fi #+ is not counted. return $count } next_gen () # Update generation array. { local array local i=0 array=( `echo "$1"` ) # Convert passed arg to array. while [ "$i" -lt "$cells" ] do IsAlive "$1" $i ${array[$i]} # Is the cell alive? if [ $? -eq "$ALIVE" ] then # If alive, then array[$i]=. #+ represent the cell as a period. else array[$i]="_" # Otherwise underscore fi #+ (will later be converted to space). let "i += 1" done # let "generation += 1" # Increment generation count. ### Why was the above line commented out? # Set variable to pass as parameter to "display" function. avar=`echo ${array[@]}` # Convert array back to string variable. display "$avar" # Display it. echo; echo echo "Generation $generation - $alive alive" if [ "$alive" -eq 0 ] then echo echo "Premature exit: no more cells alive!" exit $NONE_ALIVE # No point in continuing fi #+ if no live cells. } # ========================================================= # main () # { # Load initial array with contents of startup file. initial=( `cat "$startfile" | sed -e '/#/d' | tr -d '\n' |\ # Delete lines containing '#' comment character. sed -e 's/\./\. /g' -e 's/_/_ /g'` ) # Remove linefeeds and insert space between elements. clear # Clear screen. echo # Title setterm -reverse on echo "=======================" setterm -reverse off echo " $GENERATIONS generations" echo " of" echo "\"Life in the Slow Lane\"" setterm -reverse on echo "=======================" setterm -reverse off sleep $DELAY # Display "splash screen" for 2 seconds. # -------- Display first generation. -------- Gen0=`echo ${initial[@]}` display "$Gen0" # Display only. echo; echo echo "Generation $generation - $alive alive" sleep $DELAY # ------------------------------------------- let "generation += 1" # Bump generation count. echo # ------- Display second generation. ------- Cur=`echo ${initial[@]}` next_gen "$Cur" # Update & display. sleep $DELAY # ------------------------------------------ let "generation += 1" # Increment generation count. # ------ Main loop for displaying subsequent generations ------ while [ "$generation" -le "$GENERATIONS" ] do Cur="$avar" next_gen "$Cur" let "generation += 1" sleep $DELAY done # ============================================================== echo # } exit 0 # CEOF:EOF # The grid in this script has a "boundary problem." # The the top, bottom, and sides border on a void of dead cells. # Exercise: Change the script to have the grid wrap around, # + so that the left and right sides will "touch," # + as will the top and bottom. # # Exercise: Create a new "gen0" file to seed this script. # Use a 12 x 16 grid, instead of the original 10 x 10 one. # Make the necessary changes to the script, #+ so it will run with the altered file. # # Exercise: Modify this script so that it can determine the grid size #+ from the "gen0" file, and set any variables necessary #+ for the script to run. # This would make unnecessary any changes to variables #+ in the script for an altered grid size. # # Exercise: Optimize this script. # It has redundant code.
Example A-11. Data file for Game of Life
# gen0 # # This is an example "generation 0" start-up file for "life.sh". # -------------------------------------------------------------- # The "gen0" file is a 10 x 10 grid using a period (.) for live cells, #+ and an underscore (_) for dead ones. We cannot simply use spaces #+ for dead cells in this file because of a peculiarity in Bash arrays. # [Exercise for the reader: explain this.] # # Lines beginning with a '#' are comments, and the script ignores them. __.__..___ __.._.____ ____.___.. _._______. ____._____ ..__...___ ____._____ ___...____ __.._..___ _..___..__
+++
The following script is by Mark Moraes of the University of Toronto. See the file Moraes-COPYRIGHT for permissions and restrictions. This file is included in the combined HTML/source tarball of the ABS Guide.
Example A-12. behead: Removing mail and news message headers
#! /bin/sh # Strips off the header from a mail/News message i.e. till the first #+ empty line. # Author: Mark Moraes, University of Toronto # ==> These comments added by author of this document. if [ $# -eq 0 ]; then # ==> If no command-line args present, then works on file redirected to stdin. sed -e '1,/^$/d' -e '/^[ ]*$/d' # --> Delete empty lines and all lines until # --> first one beginning with white space. else # ==> If command-line args present, then work on files named. for i do sed -e '1,/^$/d' -e '/^[ ]*$/d' $i # --> Ditto, as above. done fi exit # ==> Exercise: Add error checking and other options. # ==> # ==> Note that the small sed script repeats, except for the arg passed. # ==> Does it make sense to embed it in a function? Why or why not? /* * Copyright University of Toronto 1988, 1989. * Written by Mark Moraes * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author and the University of Toronto are not responsible * for the consequences of use of this software, no matter how awful, * even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */
+
Antek Sawicki contributed the following script, which makes very clever use of the parameter substitution operators discussed in Section 10.2.
Example A-13. password: Generating random 8-character passwords
#!/bin/bash # # # Random password generator for Bash 2.x + #+ by Antek Sawicki <[email protected]>, #+ who generously gave usage permission to the ABS Guide author. # # ==> Comments added by document author ==> MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" # ==> Password will consist of alphanumeric characters. LENGTH="8" # ==> May change 'LENGTH' for longer password. while [ "${n:=1}" -le "$LENGTH" ] # ==> Recall that := is "default substitution" operator. # ==> So, if 'n' has not been initialized, set it to 1. do PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}" # ==> Very clever, but tricky. # ==> Starting from the innermost nesting... # ==> ${#MATRIX} returns length of array MATRIX. # ==> $RANDOM%${#MATRIX} returns random number between 1 # ==> and [length of MATRIX] - 1. # ==> ${MATRIX:$(($RANDOM%${#MATRIX})):1} # ==> returns expansion of MATRIX at random position, by length 1. # ==> See {var:pos:len} parameter substitution in Chapter 9. # ==> and the associated examples. # ==> PASS=... simply pastes this result onto previous PASS (concatenation). # ==> To visualize this more clearly, uncomment the following line # echo "$PASS" # ==> to see PASS being built up, # ==> one character at a time, each iteration of the loop. let n+=1 # ==> Increment 'n' for next pass. done echo "$PASS" # ==> Or, redirect to a file, as desired. exit 0
+
James R. Van Zandt contributed this script which uses named pipes and, in his words, "really exercises quoting and escaping."
Example A-14. fifo: Making daily backups, using named pipes
#!/bin/bash # ==> Script by James R. Van Zandt, and used here with his permission. # ==> Comments added by author of this document. HERE=`uname -n` # ==> hostname THERE=bilbo echo "starting remote backup to $THERE at `date +%r`" # ==> `date +%r` returns time in 12-hour format, i.e. "08:08:34 PM". # make sure /pipe really is a pipe and not a plain file rm -rf /pipe mkfifo /pipe # ==> Create a "named pipe", named "/pipe" ... # ==> 'su xyz' runs commands as user "xyz". # ==> 'ssh' invokes secure shell (remote login client). su xyz -c "ssh $THERE \"cat > /home/xyz/backup/${HERE}-daily.tar.gz\" < /pipe"& cd / tar -czf - bin boot dev etc home info lib man root sbin share usr var > /pipe # ==> Uses named pipe, /pipe, to communicate between processes: # ==> 'tar/gzip' writes to /pipe and 'ssh' reads from /pipe. # ==> The end result is this backs up the main directories, from / on down. # ==> What are the advantages of a "named pipe" in this situation, # ==>+ as opposed to an "anonymous pipe", with |? # ==> Will an anonymous pipe even work here? # ==> Is it necessary to delete the pipe before exiting the script? # ==> How could that be done? exit 0
+
Stéphane Chazelas used the following script to demonstrate generating prime numbers without arrays.
Example A-15. Generating prime numbers using the modulo operator
#!/bin/bash # primes.sh: Generate prime numbers, without using arrays. # Script contributed by Stephane Chazelas. # This does *not* use the classic "Sieve of Eratosthenes" algorithm, #+ but instead the more intuitive method of testing each candidate number #+ for factors (divisors), using the "%" modulo operator. LIMIT=1000 # Primes, 2 ... 1000. Primes() { (( n = $1 + 1 )) # Bump to next integer. shift # Next parameter in list. # echo "_n=$n i=$i_" if (( n == LIMIT )) then echo $* return fi for i; do # "i" set to "@", previous values of $n. # echo "-n=$n i=$i-" (( i * i > n )) && break # Optimization. (( n % i )) && continue # Sift out non-primes using modulo operator. Primes $n $@ # Recursion inside loop. return done Primes $n $@ $n # Recursion outside loop. # Successively accumulate #+ positional parameters. # "$@" is the accumulating list of primes. } Primes 1 exit $? # Pipe output of the script to 'fmt' for prettier printing. # Uncomment lines 16 and 24 to help figure out what is going on. # Compare the speed of this algorithm for generating primes #+ with the Sieve of Eratosthenes (ex68.sh). # Exercise: Rewrite this script without recursion.
+
Rick Boivie's revision of Jordi Sanfeliu's tree script.
Example A-16. tree: Displaying a directory tree
#!/bin/bash # tree.sh # Written by Rick Boivie. # Used with permission. # This is a revised and simplified version of a script #+ by Jordi Sanfeliu (the original author), and patched by Ian Kjos. # This script replaces the earlier version used in #+ previous releases of the Advanced Bash Scripting Guide. # Copyright (c) 2002, by Jordi Sanfeliu, Rick Boivie, and Ian Kjos. # ==> Comments added by the author of this document. search () { for dir in `echo *` # ==> `echo *` lists all the files in current working directory, #+ ==> without line breaks. # ==> Similar effect to for dir in * # ==> but "dir in `echo *`" will not handle filenames with blanks. do if [ -d "$dir" ] ; then # ==> If it is a directory (-d)... zz=0 # ==> Temp variable, keeping track of # directory level. while [ $zz != $1 ] # Keep track of inner nested loop. do echo -n "| " # ==> Display vertical connector symbol, # ==> with 2 spaces & no line feed # in order to indent. zz=`expr $zz + 1` # ==> Increment zz. done if [ -L "$dir" ] ; then # ==> If directory is a symbolic link... echo "+---$dir" `ls -l $dir | sed 's/^.*'$dir' //'` # ==> Display horiz. connector and list directory name, but... # ==> delete date/time part of long listing. else echo "+---$dir" # ==> Display horizontal connector symbol... # ==> and print directory name. numdirs=`expr $numdirs + 1` # ==> Increment directory count. if cd "$dir" ; then # ==> If can move to subdirectory... search `expr $1 + 1` # with recursion ;-) # ==> Function calls itself. cd .. fi fi fi done } if [ $# != 0 ] ; then cd $1 # Move to indicated directory. #else # stay in current directory fi echo "Initial directory = `pwd`" numdirs=0 search 0 echo "Total directories = $numdirs" exit 0
Patsie's version of a directory tree script.
Example A-17. tree2: Alternate directory tree script
#!/bin/bash # tree2.sh # Lightly modified/reformatted by ABS Guide author. # Included in ABS Guide with permission of script author (thanks!). ## Recursive file/dirsize checking script, by Patsie ## ## This script builds a list of files/directories and their size (du -akx) ## and processes this list to a human readable tree shape ## The 'du -akx' is only as good as the permissions the owner has. ## So preferably run as root* to get the best results, or use only on ## directories for which you have read permissions. Anything you can't ## read is not in the list. #* ABS Guide author advises caution when running scripts as root! ########## THIS IS CONFIGURABLE ########## TOP=5 # Top 5 biggest (sub)directories. MAXRECURS=5 # Max 5 subdirectories/recursions deep. E_BL=80 # Blank line already returned. E_DIR=81 # Directory not specified. ########## DON'T CHANGE ANYTHING BELOW THIS LINE ########## PID=$$ # Our own process ID. SELF=`basename $0` # Our own program name. TMP="/tmp/${SELF}.${PID}.tmp" # Temporary 'du' result. # Convert number to dotted thousand. function dot { echo " $*" | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' | tail -c 12; } # Usage: tree <recursion> <indent prefix> <min size> <directory> function tree { recurs="$1" # How deep nested are we? prefix="$2" # What do we display before file/dirname? minsize="$3" # What is the minumum file/dirsize? dirname="$4" # Which directory are we checking? # Get ($TOP) biggest subdirs/subfiles from TMP file. LIST=`egrep "[[:space:]]${dirname}/[^/]*$" "$TMP" | awk '{if($1>'$minsize') print;}' | sort -nr | head -$TOP` [ -z "$LIST" ] && return # Empty list, then go back. cnt=0 num=`echo "$LIST" | wc -l` # How many entries in the list. ## Main loop echo "$LIST" | while read size name; do ((cnt+=1)) # Count entry number. bname=`basename "$name"` # We only need a basename of the entry. [ -d "$name" ] && bname="$bname/" # If it's a directory, append a slash. echo "`dot $size`$prefix +-$bname" # Display the result. # Call ourself recursively if it's a directory #+ and we're not nested too deep ($MAXRECURS). # The recursion goes up: $((recurs+1)) # The prefix gets a space if it's the last entry, #+ or a pipe if there are more entries. # The minimum file/dirsize becomes #+ a tenth of his parent: $((size/10)). # Last argument is the full directory name to check. if [ -d "$name" -a $recurs -lt $MAXRECURS ]; then [ $cnt -lt $num ] \ || (tree $((recurs+1)) "$prefix " $((size/10)) "$name") \ && (tree $((recurs+1)) "$prefix |" $((size/10)) "$name") fi done [ $? -eq 0 ] && echo " $prefix" # Every time we jump back add a 'blank' line. return $E_BL # We return 80 to tell we added a blank line already. } ### ### ### main program ### ### ### rootdir="$@" [ -d "$rootdir" ] || { echo "$SELF: Usage: $SELF <directory>" >&2; exit $E_DIR; } # We should be called with a directory name. echo "Building inventory list, please wait ..." # Show "please wait" message. du -akx "$rootdir" 1>"$TMP" 2>/dev/null # Build a temporary list of all files/dirs and their size. size=`tail -1 "$TMP" | awk '{print $1}'` # What is our rootdirectory's size? echo "`dot $size` $rootdir" # Display rootdirectory's entry. tree 0 "" 0 "$rootdir" # Display the tree below our rootdirectory. rm "$TMP" 2>/dev/null # Clean up TMP file. exit $?
Noah Friedman permitted use of his string function script. It essentially reproduces some of the C-library string manipulation functions.
Example A-18. string functions: C-style string functions
About AquaClusters Privacy Policy Support Version - 19.0.2-4 AquaFold, Inc Copyright © 2007-2017