From b32e9c2737061a7f362eba000c91e41e8edf3a65 Mon Sep 17 00:00:00 2001 From: gferg <> Date: Mon, 7 Jan 2002 15:24:19 +0000 Subject: [PATCH] updated --- LDP/guide/docbook/abs-guide/Change.log | 82 +++ LDP/guide/docbook/abs-guide/abs-guide.sgml | 684 ++++++++++++++++++--- LDP/guide/docbook/abs-guide/ex56.sh | 2 +- LDP/guide/docbook/abs-guide/ex62.sh | 15 +- LDP/guide/docbook/abs-guide/ex9.sh | 10 +- LDP/guide/docbook/abs-guide/symlinks.sh | 4 +- LDP/guide/docbook/abs-guide/symlinks2.sh | 6 +- LDP/guide/docbook/abs-guide/weirdvars.sh | 6 +- 8 files changed, 726 insertions(+), 83 deletions(-) diff --git a/LDP/guide/docbook/abs-guide/Change.log b/LDP/guide/docbook/abs-guide/Change.log index 9c542d80..343dee01 100644 --- a/LDP/guide/docbook/abs-guide/Change.log +++ b/LDP/guide/docbook/abs-guide/Change.log @@ -2,6 +2,88 @@ RELEASE HISTORY ------- ------- Change log +Version 1.0.X interim release + +1) Fix up comments in "weirdvars.sh" example. + +2) In "Variables" chapter, slight wording change in first paragraph. + +3) Slight changes to "ex9.sh" example. + +4) Added redirection as an alternative remedy to the script hang problem with + background commands in "Job Control Commands" section of "Internal + Commands" chapter. + +5) In "Text Processing Commands" section of "External Commands" chapter: + Added "-q" option at "grep", with in-line example. + Added usage example for "cut". + Much more information on "uniq -c", and added "wf.sh" example. + +6) In "Functions" chapter: + Added more info on oversize (> 256) return values. + Modified "ex62.sh" example. + Reorganized "Local Variables" section. + Added note that before function call, all variables within functions + are local, not just those explicitly declared as such. + +7) Add section on "Shell Scripting Under Windows" to "Miscellany" chapter. + +8) In "String Manipulation" section of "Variables Revisited" chapter: + Bugfix in comment in "%%" substring removal example. + Added "cvt.sh" example at "%%" substring removal discussion. + Added subsection on using "awk" functionality for string manipulation, + with added "substring-extraction.sh" example. + +9) In "$RANDOM" section of "Variables Revisited" chapter: + Removed superfluous "note" icon at beginning of section. + Added example of using "awk" rand() function to generate random numbers. + +10) In "Command Substitution" chapter: + Added discussion and example of extending Bash toolset. + Added footnote about what exactly constitutes a "command". + +11) In "System and Administrative Commands" chapter: + Added "lastlog" command. + More info on "route" and "netstat". + Fixed reference to "crond" at "logrotate". + Added "tmpwatch". + Added "sar". + +12) In "Miscellaneous Commands" section of "External Commands" chapter, + added more info and an example to "dd". + +13) In "Math Commands" section of "External Commands" chapter: + Added an alternative method of invoking 'bc', with "alt-bc.sh" example. + Added using "awk" math commands, with "hypotenuse.sh" example. + +14) In "Archiving Commands" section of "External Commands" chapter, + added footnote to "tar". + +15) In "Bibliography" section: + Cleaned up cross reference to University of Alberta site. + Added comp.unix.shell newsgroup reference. + +16) Made corrections to "symlinks.sh" and "symlinks2.sh" examples, + per Dominik 'Aeneas' Schnitzer. + +17) In "Starting Off With a Sha-Bang" chapter, clarified footnote explaining + "magic numbers", per Stanislav Brabec's suggestion. + +18) In "I/O Redirection" chapter, added stdout redirection instance, with + example. + +19) In "Sed and Awk Micro-Primer" appendix: + Added $filename to in-line examples. + Fixup on "END" command block description. + +20) Added semicolons as necessary to terminate commands in Perl examples. + +21) Added "History Commands" appendix. + + + + + Version 1.0 (stable!), released 10/14/01 1) Quoted "$LOGFILE" in in-line example in "Scripting With Style" subsection diff --git a/LDP/guide/docbook/abs-guide/abs-guide.sgml b/LDP/guide/docbook/abs-guide/abs-guide.sgml index dd93ee19..13f79d8c 100644 --- a/LDP/guide/docbook/abs-guide/abs-guide.sgml +++ b/LDP/guide/docbook/abs-guide/abs-guide.sgml @@ -213,13 +213,19 @@ Uncomment line below to generate index. + + + + + + ]> Advanced Bash-Scripting Guide - A complete guide to shell scripting, using Bash + A complete guide to shell scripting @@ -231,8 +237,8 @@ Uncomment line below to generate index. - - 14 October 2001 + 1.1 + 06 January 2002 @@ -279,9 +285,15 @@ Uncomment line below to generate index. 1.0 14 October 2001 mc - Bugfixes, reorganization, material added. This book - has finally reached the point where it can be designated a - stable release. + Bugfixes, reorganization, material added. + Stable release. + + + + 1.1 + 06 January 2002 + mc + Bugfixes, material and scripts added. @@ -303,7 +315,7 @@ Uncomment line below to generate index. The latest update of this document, as an archived tarball including both the SGML source and rendered HTML, may be downloaded from + url="http://personal.riverusers.com/~thegrendel/abs-guide-1.1.tar.gz"> the author's home site. See the change log for a revision history. @@ -529,10 +541,10 @@ Uncomment line below to generate index. is a set of commands to be fed to the command interpreter indicated. The #! is actually a two-byte - Some flavors - of UNIX take a four-byte magic number, - requiring a blank after the !, - #! /bin/sh. + Some flavors of UNIX (those based on 4.2BSD) + take a four-byte magic number, requiring + a blank after the !, + #! /bin/sh. magic number @@ -2215,7 +2227,7 @@ echo $a # 28 of quantities, string parsing, and are indispensable for working in the abstract with symbols - tokens that represent something else. A variable is nothing more than a location or set of - locations in computer memory that holds an item of data. + locations in computer memory holding an item of data. Variable Substitution @@ -6048,12 +6060,18 @@ echo ${stringZ##a*C} # abc # |------------| echo ${stringZ%b*c} # abcABC123ABCa -# Strip out shortest match between 'a' and 'C', from back of $stringZ. +# Strip out shortest match between 'b' and 'c', from back of $stringZ. echo ${stringZ%%b*c} # a -# Strip out longest match between 'a' and 'C', from back of $stringZ. +# Strip out longest match between 'b' and 'c', from back of $stringZ. + + Converting graphic file formats, with filename change + &cvt; + + + @@ -6148,8 +6166,27 @@ echo ${stringZ/%abc/XYZ} # abcABC123ABCXYZ - For further discussion of string manipulation in scripts, - refer to and the + + Manipulating strings using awk + + A Bash script may invoke the string manipulation facilities of + awk as an alternative to using its + built-in operations. + + + Alternate ways of extracting substrings + &substringex; + + + + + + + + Further Discussion + + For more on string manipulation in scripts, refer to and the relevant section of the expr command listing. For script examples, see: @@ -6161,6 +6198,10 @@ echo ${stringZ/%abc/XYZ} # abcABC123ABCXYZ + + + + @@ -6698,10 +6739,10 @@ echo "number = $number" # number = 0 $RANDOM $RANDOM: generate random integer - $RANDOM is an internal Bash function (not a constant) that + $RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. $RANDOM should not be used - to generate an encryption key. + to generate an encryption key. Generating random numbers @@ -6731,7 +6772,8 @@ echo "number = $number" # number = 0 - The /dev/urandom device-file provides + + The /dev/urandom device-file provides a means of generating much more random pseudorandom numbers than the $RANDOM variable. dd if=/dev/urandom of=targetfile @@ -6740,7 +6782,22 @@ echo "number = $number" # number = 0 to a variable in a script requires a workaround, such as filtering through od (as in above example) or using dd - (see ). + (see ). + + + + There are also other means of generating pseudorandom + numbers in a script. Awk provides a + convenient means of doing this. + + + Pseudorandom numbers, using <link + linkend="awkref">awk</link> + &random2; + + + + @@ -8582,9 +8639,10 @@ done Within a script, running a command in the background - with an ampersand (&) may cause the script to hang - until ENTER is hit. This can be a - major annoyance. + with an ampersand (&) may cause the script + to hang until ENTER is hit. This + seems to occur with commands that write to + stdout. It can be a major annoyance. #!/bin/bash # test.sh @@ -8612,6 +8670,10 @@ wait [bozo@localhost test-scripts]$ total 1 -rwxr-xr-x 1 bozo bozo 34 Oct 11 15:09 test.sh + Redirecting the + output of the command to a file or even to + /dev/null also takes care of this + problem. @@ -9982,7 +10044,68 @@ gzip -cd patchXX.gz | patch -p0 # and finally writes the result to an output file. The useful option prefixes each line of - the input file with the number of occurrences. + the input file with its number of occurrences. + + +bash$ cat testfile +This line occurs only once. + This line occurs twice. + This line occurs twice. + This line occurs three times. + This line occurs three times. + This line occurs three times. + + +bash$ uniq -c testfile + 1 This line occurs only once. + 2 This line occurs twice. + 3 This line occurs three times. + + +bash$ sort testfile | uniq -c | sort -nr + 3 This line occurs three times. + 2 This line occurs twice. + 1 This line occurs only once. + + + + The sort INPUTFILE | uniq -c | sort -nr + command string produces a frequency + of occurrence listing on the + INPUTFILE file (the + options 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. + + + Word Frequency Analysis + &wf; + + + + +bash$ cat testfile +This line occurs only once. + This line occurs twice. + This line occurs twice. + This line occurs three times. + This line occurs three times. + This line occurs three times. + + +bash$ ./wf.sh testfile + 6 this + 6 occurs + 6 line + 3 times + 3 three + 2 twice + 1 only + 1 once + + @@ -10045,6 +10168,16 @@ gzip -cd patchXX.gz | patch -p0 Using cut to list the OS and kernel version: uname -a | cut -d" " -f1,3,11,12 + Using cut to extract message headers from + an e-mail folder: + + bash$ grep '^Subject:' read-messages | cut -c10-80 +Re: Linux suitable for mission-critical apps? + MAKE MILLIONS WORKING AT HOME!!! + Spam complaint + Re: Spam complaint + + Using cut to parse a file: # List all the users in /etc/passwd. @@ -10338,7 +10471,22 @@ printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -c '$' # 9 If there is a successful match, grep returns an exit status of 0, which makes it useful in a condition test in a - script. + script, especially in combination with the + option to suppress output. + SUCCESS=0 # if grep lookup succeeds +word=Linux +filename=data.file + +grep -q "$word" "$filename" # The "-q" option causes nothing to echo to stdout. + +if [ $? -eq $SUCCESS ] +then + echo "$word found in $filename" +else + echo "$word not found in $filename" +fi + + demonstrates how to use grep to search for a word pattern in @@ -10901,8 +11049,20 @@ printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -c '$' # 9 accept gzip compression options, such as tar czvf archive-name.tar.gz *, which recursively archives and compresses all - files (except dotfiles) - in a directory tree. + files in a directory tree except dotfiles in the current + working directory ($PWD). + + + A tar czvf ... + will include dotfiles in + directories below the current + working directory. This is an undocumented + tar feature. + + + + Some useful tar options: @@ -10974,8 +11134,10 @@ printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -c '$' # 9 cpio - This specialized archiving copy command is rarely seen any more, - having been supplanted by + 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. @@ -12235,7 +12397,9 @@ printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -c '$' # 9 the rescue. Here is a simple template for using - bc to calculate a script variable. + bc to calculate a script + variable. This uses command + substitution. @@ -12253,6 +12417,63 @@ printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -c '$' # 9 &base; + 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. + + + variable=`bc << LIMIT_STRING +options +statements +operations +LIMIT_STRING +` + +...or... + + +variable=$(bc << LIMIT_STRING +options +statements +operations +LIMIT_STRING +) + + + + + Another way to invoke <command>bc</command> + &altbc; + + + + + + + + awk + + awk + + + command + math + + + Yet another way of doing floating point math in + a script is using awk's + built-in math functions in a shell + wrapper. + + + Calculating the hypotenuse of a triangle + &hypot; + + @@ -12616,8 +12837,20 @@ echo -n "hello world" | dd cbs=1 conv=unblock 2> /dev/null The dd command can copy raw data and disk images to and from devices, such as floppies and tape drives (). A common use is - creating boot floppies. - dd if=kernel-image of=/dev/fd0H1440 + creating boot floppies. + + dd if=kernel-image of=/dev/fd0H1440 + + + 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. + + dd if=/dev/fd0 of=/home/bozo/projects/floppy.img + + + Other applications of dd include initializing temporary swap files () and ramdisks (). It can even do a @@ -13380,13 +13613,47 @@ setserial /dev/$DEVICE irq 0 ; setserial /dev/$DEVICE irq $IRQ< last - Gives information about previous commands, as stored + Gives information about previous commands, as stored in the /var/account/pacct file. Command name and user name can be specified by options. This is one of the GNU accounting utilities. + + lastlog + + lastlog + + + command + last + + + List the last login time of all system users. This + references the /var/log/lastlog + file. + + bash$ lastlog +root tty1 Fri Dec 7 18:43:21 -0700 2001 + bin **Never logged in** + daemon **Never logged in** + ... + bozo tty1 Sat Dec 8 21:14:29 -0700 2001 + + + +bash$ lastlog | grep root +root tty1 Fri Dec 7 18:43:21 -0700 2001 + + + + This command will fail if the user invoking + it does not have read permission for the + /var/log/lastlog file. + + + lsof @@ -13641,11 +13908,13 @@ setserial /dev/$DEVICE irq 0 ; setserial /dev/$DEVICE irq $IRQ< netstat - Show current network information and statistics, + Show current network statistics and information, such as routing tables and active connections. This utility accesses information in /proc/net (). See . + netstat -r is equivalent to route. @@ -13742,6 +14011,42 @@ setserial /dev/$DEVICE irq 0 ; setserial /dev/$DEVICE irq $IRQ< + + sar + + sar + + + command + system activity report + + + Invoking sar (system activity report) + gives a very detailed rundown on system statistics. + This command is found on some commercial UNIX + systems, but is not part of the base Linux + distribution. It is contained in the + sysstat utilities package, written by Sebastien + Godard. + + +bash$ sar +Linux 2.4.7-10 (localhost.localdomain) 12/31/2001 + + 10:30:01 AM CPU %user %nice %system %idle + 10:40:00 AM all 1.39 0.00 0.77 97.84 + 10:50:00 AM all 76.83 0.00 1.45 21.72 + 11:00:00 AM all 1.32 0.00 0.69 97.99 + 11:10:00 AM all 1.17 0.00 0.30 98.53 + 11:20:00 AM all 0.51 0.00 0.30 99.19 + 06:30:00 PM all 100.00 0.00 100.01 0.00 + Average: all 1.39 0.00 0.66 97.95 + + + + @@ -13792,7 +14097,7 @@ setserial /dev/$DEVICE irq 0 ; setserial /dev/$DEVICE irq $IRQ< This utility manages the system log files, rotating, compressing, deleting, and/or mailing them, as appropriate. - Usually cron runs + Usually crond runs logrotate on a daily basis. Adding an appropriate entry to @@ -14140,7 +14445,7 @@ echo `/sbin/ifconfig | grep ^[a-z] | awk '{print $1}'` - route + route route @@ -14154,8 +14459,10 @@ echo `/sbin/ifconfig | grep ^[a-z] | awk '{print $1}'` bash$ route -Destination Gateway Genmask Flags Metric Ref Use Iface - 127.0.0.0 * 255.0.0.0 U 0 0 0 lo +Destination Gateway Genmask Flags MSS Window irtt Iface + pm3-67.bozosisp * 255.255.255.255 UH 40 0 0 ppp0 + 127.0.0.0 * 255.0.0.0 U 40 0 0 lo + default pm3-67.bozosisp 0.0.0.0 UG 40 0 0 ppp0 @@ -14716,6 +15023,23 @@ then + + tmpwatch + + tmpwatch + + + command + tmpwatch + + + Automatically deletes files which have not been accessed + within a specified period of time. Usually invoked by + crond to remove stale log + files. + + + MAKEDEV @@ -15112,6 +15436,11 @@ print "even when I don't know where to find Perl.\n"; Command substitution reassigns the output of a command + For purposes of command + substitution, a command may + be an external system command, an internal scripting + builtin, or even a script + function. or even multiple commands; it literally plugs the command output into another context. @@ -15242,7 +15571,39 @@ variable2=`cat file2` # Set "variable2" to contents of "file2". + + 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 + stdout (like a well-behaved UNIX + tool should) and assigning that output to a variable. + + #include <stdio.h> + +/* "Hello, world." C program */ + +int main() +{ + printf( "Hello, world." ); + return (0); +} + bash$ gcc -o hello hello.c + + + + + #!/bin/bash +# hello.sh + +greeting=`./hello` +echo $greeting + bash$ sh hello.sh +Hello, world. + + + + The $(COMMAND) form has superseded backticks for command substitution. output=$(sed -n /"$1"/p $file) @@ -15267,6 +15628,7 @@ variable2=`cat file2` # Set "variable2" to contents of "file2". + @@ -15402,12 +15764,49 @@ let "z += 3" #If quotes, then spaces and special operators allowed. : > filename # The > truncates file "filename" to zero length. + # If file not present, creates zero-length file (same effect as 'touch'). # The : serves as a dummy placeholder, producing no output. >> # Redirect stdout to a file. # Creates the file if not present, otherwise appends to it. + + # Single-line redirection commands (affect only the line they are on): + # -------------------------------------------------------------------- + 1>filename + # Redirect stdout to file "filename". + 1>>filename + # Redirect and append stdout to file "filename". + 2>filename + # Redirect stderr to file "filename". + 2>>filename + # Redirect and append stderr to file "filename". + + #============================================================================== + # Redirecting stdout, one line at a time. + LOGFILE=script.log + + echo "This statement is sent to the log file, \"$LOGFILE\"." 1>$LOGFILE + echo "This statement is appended to \"$LOGFILE\"." 1>>$LOGFILE + echo "This statement is also appended to \"$LOGFILE\"." 1>>$LOGFILE + echo "This statement is echoed to stdout, and will not appear in \"$LOGFILE\"." + # These redirection commands automatically "reset" after each line. + + + + # Redirecting stderr, one line at a time. + ERRORFILE=script.errors + + bad_command1 2>$ERRORFILE # Error message sent to $ERRORFILE. + bad_command2 2>>$ERRORFILE # Error message appended to $ERRORFILE. + bad_command3 # Error message echoed to stderr, + #+ and does not appear in $ERRORFILE. + # These redirection commands also automatically "reset" after each line. + #============================================================================== + + + 2>&1 # Redirects stderr to stdout. # Error messages get sent to same place as standard output. @@ -15753,8 +16152,8 @@ exit 0 - Some utilities will not work in a here - document. + Some utilities will not work inside a + here document. For those tasks too complex for a here document, consider using the expect @@ -17098,6 +17497,32 @@ fi value. This also permits returning large positive integer, using a bit of trickery. + An alternate method of accomplishing this is to simply + assign the return value to a global variable. + Return_Val= # Global variable to hold oversize return value of function. + +alt_return_test () +{ + fvar=$1 + Return_Val=$fvar + return # Returns 0 (success). +} + +alt_return_test 1 +echo $? # 0 +echo "return value = $Return_Val" # 1 + +alt_return_test 256 +echo "return value = $Return_Val" # 256 + +alt_return_test 257 +echo "return value = $Return_Val" # 257 + +alt_return_test 25701 +echo "return value = $Return_Val" #25701 + + + Comparing two large integers &max2; @@ -17186,11 +17611,10 @@ Function () # This doesn't work. - Local Variables and Recursion + Local Variables - <anchor id="localref1">Local variables make recursion - possible. + <anchor id="localref1">What makes a variable <quote>local</quote>? local variables @@ -17211,6 +17635,37 @@ Function () # This doesn't work. &ex62; + + Before a function is called, all + variables declared within the function are invisible outside + the body of the function, not just those explicitly declared + as local. + #!/bin/bash + +func () +{ +global_var=37 # Visible only within the function block + #+ before the function has been called. +} # END OF FUNCTION + +echo "global_var = $global_var" # global_var = + # Function "func" has not yet been called, + #+ so $global_var is not visible here. + +func +echo "global_var = $global_var" # global_var = 37 + # Has been set by function call. + + + + + + + + + + Local variables make recursion possible. + Local variables permit recursion, @@ -17259,12 +17714,9 @@ exit 0 # This script will not exit normally. resource-intensive and executes slowly, and is therefore generally not appropriate to use in a script. - - + - - - + @@ -18869,6 +19321,8 @@ fi Shell Wrappers + + A wrapper is a shell script that embeds a system command or utility, that saves a set of parameters passed to to that command. Wrapping a script around a complex @@ -19324,6 +19778,21 @@ exit 0 + + + Shell Scripting Under Windows + + Even users running that other OS can + run UNIX-like shell scripts, and therefore benefit + from many of the lessons of this book. The + Cygwin package from Cygnus and the MKS utilities from + Mortice Kern Associates add shell scripting capabilities to + Windows. + + + @@ -19896,7 +20365,7 @@ exit 0 The O'Reilly books on Perl. (Actually, any O'Reilly books.) - ----------------------------------------------------------------------- + --- @@ -20025,8 +20494,8 @@ exit 0 - There is some nice material on I/O redirection () in There is some nice material on I/O redirection in chapter 10 of the textutils documentation at the University of @@ -20040,7 +20509,7 @@ exit 0 Hohensee has written the osimpa i386 assembler entirely as Bash scripts. - ------------------------------------------------------------------------- + --- @@ -20052,6 +20521,14 @@ exit 0 + + + The comp.os.unix.shell + newsgroup. + + + The manpages for bash and @@ -20318,12 +20795,14 @@ exit 0 From the command line and in a shell script, a sed operation may require quoting and certain options. - sed -e '/^$/d' -# The -e option causes the next string to be interpreted as an editing instruction. -# (If passing only a single instruction to "sed", the "-e" is optional.) -# The "strong" quotes ('') protect the RE characters in the instruction -# from reinterpretation as special characters by the body of the script. + sed -e '/^$/d' $filename +# The -e option causes the next string to be interpreted as an editing instruction. +# (If passing only a single instruction to "sed", the "-e" is optional.) +# The "strong" quotes ('') protect the RE characters in the instruction +#+ from reinterpretation as special characters by the body of the script. # (This reserves RE expansion of the instruction for sed.) +# +# Operates on the text contained in file $filename. Sed uses the option @@ -20331,7 +20810,7 @@ exit 0 of instructions. If there is only a single instruction contained in the string, then this option may be omitted. - sed -n '/xzy/p' + sed -n '/xzy/p' $filename # The -n option tells sed to print only those lines matching the pattern. # Otherwise all input lines would print. # The -e option not necessary here since there is only a single editing instruction. @@ -20422,6 +20901,7 @@ exit 0 + @@ -20455,11 +20935,11 @@ exit 0 Strong quoting (single quotes) and curly brackets enclose segments of awk code within a shell script. - awk '{print $3}' -# Prints field #3 to stdout. + awk '{print $3}' $filename +# Prints field #3 of file $filename to stdout. -awk '{print $1 $5 $6}' -# Prints fields #1, #5, and #6. +awk '{print $1 $5 $6}' $filename +# Prints fields #1, #5, and #6 of file $filename. We have just seen the awk print command in action. The only other feature of awk we need to deal with @@ -20469,8 +20949,8 @@ awk '{print $1 $5 $6}' { total += ${column_number} } This adds the value of column_number to the running total of total. Finally, to print - total, there needs to be an END - command to terminate the processing. + total, there is an END command + block, executed after the script has processed all its input. END { print total } Corresponding to the END, there is a @@ -20491,6 +20971,7 @@ awk '{print $1 $5 $6}' + @@ -20878,6 +21359,71 @@ read -p "$(gettext -s "Enter the value: ")" var + + History Commands + + The Bash shell provides command-line tools for editing and + manipulating a user's command history. This + is primarily a convenience, a means of saving keystrokes. + + Bash history commands: + + history + fc + + + + + bash$ history + 1 mount /mnt/cdrom + 2 cd /mnt/cdrom + 3 ls + ... + + + + Internal variables associated with Bash history commands: + + $HISTCMD + $HISTCONTROL + $HISTIGNORE + $HISTFILE + $HISTFILESIZE + $HISTSIZE + !! + !$ + !# + !N + !-N + !STRING + !?STRING? + ^STRING^string^ + + + + Unfortunately, the Bash history tools find no use in scripting. + #!/bin/bash +# history.sh +# Attempt to use 'history' command in a script. + +history + +# Script produces no output. +# History commands do not work within a script. + + + + bash$ ./history.sh +(no output) + + + + + + + + + A Sample <filename>.bashrc</filename> File @@ -21591,11 +22137,11 @@ Smith,Tom,404 Polk Ave.,Los Angeles,CA,90003,(213) 879-5612 Hyun Jin Cha has done a Korean - translation of an earlier version of this book. - A Portuguese translation will soon commence. If you wish to - translate it into another language, please feel free to do so, - subject to the terms stated above. The author would appreciate - being notified of such efforts. + translation of an earlier version of this book. Spanish, + Portuguese, and French translations are underway. If you wish to + translate this document into another language, please feel free + to do so, subject to the terms stated above. The author would + appreciate being notified of such efforts. If this document is printed as a hard-copy book, the author requests a courtesy copy. This is a request, not a requirement. diff --git a/LDP/guide/docbook/abs-guide/ex56.sh b/LDP/guide/docbook/abs-guide/ex56.sh index 5ae8877e..ad156fb1 100644 --- a/LDP/guide/docbook/abs-guide/ex56.sh +++ b/LDP/guide/docbook/abs-guide/ex56.sh @@ -4,7 +4,7 @@ echo "This precedes the embedded Perl script within \"$0\"." echo "===============================================================" -perl -e 'print "This is an embedded Perl script\n"' +perl -e 'print "This is an embedded Perl script.\n";' # Like sed, Perl also uses the "-e" option. echo "===============================================================" diff --git a/LDP/guide/docbook/abs-guide/ex62.sh b/LDP/guide/docbook/abs-guide/ex62.sh index 5415027e..4658e8c5 100644 --- a/LDP/guide/docbook/abs-guide/ex62.sh +++ b/LDP/guide/docbook/abs-guide/ex62.sh @@ -2,17 +2,24 @@ func () { - local a=23 - echo - echo "a in function = $a" + local loc_var=23 # Declared local. echo + echo "\"loc_var\" in function = $loc_var" + global_var=999 # Not declared local. + echo "\"global_var\" in function = $global_var" } func # Now, see if local 'a' exists outside function. -echo "a outside function = $a" # Nope, 'a' not visible globally. echo +echo "\"loc_var\" outside function = $loc_var" + # "loc_var" outside function = + # Nope, $loc_var not visible globally. +echo "\"global_var\" outside function = $global_var" + # "global_var" outside function = 999 + # $global_var is visible globally. +echo exit 0 diff --git a/LDP/guide/docbook/abs-guide/ex9.sh b/LDP/guide/docbook/abs-guide/ex9.sh index 5340c515..30d511c7 100644 --- a/LDP/guide/docbook/abs-guide/ex9.sh +++ b/LDP/guide/docbook/abs-guide/ex9.sh @@ -25,9 +25,15 @@ echo ${hello} #Identical to above. echo "$hello" echo "${hello}" -# hello="A B C D" +echo + +hello="A B C D" +echo $hello +echo "$hello" # Now, echo $hello and echo "$hello" give different results. -# Quoting variable preserves whitespace. +# Quoting a variable preserves whitespace. + +echo echo '$hello' # Variable referencing disabled by single quotes, diff --git a/LDP/guide/docbook/abs-guide/symlinks.sh b/LDP/guide/docbook/abs-guide/symlinks.sh index b8f4ae21..5d93084b 100644 --- a/LDP/guide/docbook/abs-guide/symlinks.sh +++ b/LDP/guide/docbook/abs-guide/symlinks.sh @@ -12,10 +12,10 @@ fi echo "symbolic links in directory \"$directory\"" -for file in $( find $directory -type l ) # -type l = symbolic links +for file in "$( find $directory -type l )" # -type l = symbolic links do echo "$file" -done | sort # Otherwise file list is unsorted. +done | sort # Otherwise file list is unsorted. # As Dominik 'Aeneas' Schnitzer points out, #+ failing to quote $( find $directory -type l ) diff --git a/LDP/guide/docbook/abs-guide/symlinks2.sh b/LDP/guide/docbook/abs-guide/symlinks2.sh index 2171812e..7572581c 100644 --- a/LDP/guide/docbook/abs-guide/symlinks2.sh +++ b/LDP/guide/docbook/abs-guide/symlinks2.sh @@ -13,10 +13,10 @@ fi echo "symbolic links in directory \"$directory\"" -for file in $( find $directory -type l ) # -type l = symbolic links +for file in "$( find $directory -type l )" # -type l = symbolic links do echo "$file" -done | sort > "$OUTFILE" # stdout of loop -# ^^^^^^^^^^^^ redirected to save file. +done | sort > "$OUTFILE" # stdout of loop +# ^^^^^^^^^^^^ redirected to save file. exit 0 diff --git a/LDP/guide/docbook/abs-guide/weirdvars.sh b/LDP/guide/docbook/abs-guide/weirdvars.sh index 847b9745..c1a9a24a 100644 --- a/LDP/guide/docbook/abs-guide/weirdvars.sh +++ b/LDP/guide/docbook/abs-guide/weirdvars.sh @@ -5,9 +5,11 @@ var="'(]\\{}\$\"" echo $var # '(]\{}$" echo "$var" # '(]\{}$" Doesn't make a difference. +echo + IFS='\' -echo $var # '(]\{}$" \ converted to space. -echo "$var" # '(] {}$" +echo $var # '(] {}$" \ converted to space. +echo "$var" # '(]\{}$" # Examples above supplied by S.C.