From 27db22da76bd98825bf2e21fbc007352251777b0 Mon Sep 17 00:00:00 2001 From: tille <> Date: Mon, 5 Sep 2005 12:15:43 +0000 Subject: [PATCH] Corrected typos, incorporated reader remarks. --- .../docbook/Bash-Beginners-Guide/abook.xml | 81 ++++------------ .../docbook/Bash-Beginners-Guide/chap1.xml | 6 -- .../docbook/Bash-Beginners-Guide/chap10.xml | 18 +--- .../docbook/Bash-Beginners-Guide/chap11.xml | 4 - .../docbook/Bash-Beginners-Guide/chap12.xml | 14 ++- .../docbook/Bash-Beginners-Guide/chap2.xml | 11 --- .../docbook/Bash-Beginners-Guide/chap3.xml | 29 ++---- .../docbook/Bash-Beginners-Guide/chap4.xml | 3 - .../docbook/Bash-Beginners-Guide/chap5.xml | 4 - .../docbook/Bash-Beginners-Guide/chap6.xml | 13 +-- .../docbook/Bash-Beginners-Guide/chap7.xml | 24 +++-- .../docbook/Bash-Beginners-Guide/chap8.xml | 6 +- .../docbook/Bash-Beginners-Guide/chap9.xml | 95 ++++--------------- .../docbook/Bash-Beginners-Guide/gloss.xml | 7 -- .../Bash-Beginners-Guide/index-gloss.xml | 10 +- 15 files changed, 76 insertions(+), 249 deletions(-) diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/abook.xml b/LDP/guide/docbook/Bash-Beginners-Guide/abook.xml index 5f46cc8d..4639d91c 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/abook.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/abook.xml @@ -29,16 +29,16 @@ Machtelt Garrels -Xalasys.com +CoreSequence.com
-tille wants no spam _at_ xalasys dot com +tille@coresequence.com
-Version 1.6 Last updated 20050301 +Version 1.1 Last updated 20040615 Linux Scripts @@ -51,12 +51,6 @@ bash scripting Scripting -awk -sed -variables -functions -loops -conditionals @@ -70,7 +64,6 @@ The primary reason for writing this document is that a lot of readers feel the existing HOWTO to be too short and incomplete, while the Bash Scripting guide is too much of a reference work. There is nothing in between these two extremes. I also wrote this guide on the general principal that not enough free basic courses are available, though they should be. This is a practical guide which, while not always being too serious, tries to give real-life instead of theoretical examples. I partly wrote it because I don't get excited with stripped down and over-simplified examples written by people who know what they are talking about, showing some really cool Bash feature so much out of its context that you cannot ever use it in practical circumstances. You can read that sort of stuff after finishing this book, which contains exercises and examples that will help you survive in the real world. From my experience as UNIX/Linux user, system administrator and trainer, I know that people can have years of daily interaction with their systems, without having the slightest knowledge of task automation. Thus they often think that UNIX is not userfriendly, and even worse, they get the impression that it is slow and old-fashioned. This problem is another one that can be remedied by this guide. -
@@ -90,58 +83,18 @@ Adding/removing software on your system See Introduction to Linux (or your local TLDP mirror) if you haven't mastered one or more of these topics. Additional information can be found in your system documentation (man and info pages), or at the Linux Documentation Project. -
+
-New versions and availability - -The most recent edition can be found at . You should find the same version at . - -This guide is available in print from Fultus.com. - -
Bash Guide for Beginners front cover - - - - - - - - -Front cover of the Bash guide, red highlighted code on blue background. - - -
+New versions of this guide +The most recent edition can be found at . You should find the same version at .
+
Revision History - - 1.6 - 2005-03-01 - MG - Minor debugging, added more keywords, info about new Bash 3.0, took out blank image. - - - 1.5 - 2004-12-06 - MG - Changes because of new domain, minor corrections. - - - 1.4 - 2004-10-18 - MG - Debugging, added a couple of notes in chap9, replaced screenshots with screen sections. Corrected some typos. - - - 1.3 - 2004-07-09 - MG - Added tracer image 1x1 pixel http://tille.xalasys.com/images/blank-bash.png, added textobjects for all pictures, fixed wrong links in index, made signal list more clear. - 1.2 2004-06-15 @@ -185,36 +138,36 @@ Thanks to all the friends who helped (or tried to) and to my husband; your encou Gerg Ferguson, for ideas on the title Mendel Leo Cooper, for making room #linux.be, for keeping my feet on the ground -Frank Wang, for his detailed remarks on all the things I did wrong ;-) Special thanks to Tabatha Marshall, who volunteered to do a complete review and spell and grammar check. We make a great team: she works when I sleep. And vice versa ;-) -
+
Feedback Missing information, missing links, missing characters, remarks? Mail it to -
tille wants no spam _at_ xalasys dot com
+
tille@coresequence.com
the maintainer of this document.
-
+
Copyright information -Copyright © 2003-2005 Machtelt Garrels. +Copyright © 2003 Machtelt Garrels. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the Invariant Sections being "New versions of this document", "Contributions", "Feedback" and "Copyright information", with no Front-Cover Texts and no Back-Cover Texts. A copy of the license is included in entitled "GNU Free Documentation License". The author and publisher have made every effort in the preparation of this book to ensure the accuracy of the information. However, the information contained in this book is offered without warranty, either express or implied. Neither the author nor the publisher nor any dealer or distributor will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book. The logos, trademarks and symbols used in this book are the properties of their respective owners. -
+
What do you need? bash, available from http://www.gnu.org/directory/GNU/. The Bash shell is available on nearly every Linux system, and can these days be found on a wide variety of UNIX systems. Compiles easily if you need to make your own, tested on a wide variety of UNIX, Linux, MS Windows and other systems. +
Conventions used in this document @@ -298,14 +251,15 @@ is the heart of the system. within this guide. -The author +The author Clickable link to an external web resource. -
+ +
Organization of this document This guide discusses concepts useful in the daily life of the serious Bash user. While a basic knowledge of the usage of the shell is required, we start with a discussion of the basic shell components and practices in the first three chapters. @@ -352,7 +306,8 @@ next chapter. : Catching signals: introduction to process signalling, trapping user-sent signals. -
+ + diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap1.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap1.xml index e09705f6..aaa084d7 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap1.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap1.xml @@ -51,7 +51,6 @@ in the active terminal. The system finds the directory where the name occurs us [mia@post21 ~]$ - Advantages of the Bourne Again SHell @@ -244,7 +243,6 @@ the shell expansions or by the let built-in. - Executing commands @@ -349,7 +347,6 @@ the shell expansions or by the let built-in. - Developing good scripts @@ -508,7 +505,6 @@ exit 0 The case statement often used in this kind of script is described in . - Summary @@ -521,7 +517,6 @@ exit 0 Bash behaves different when in interactive mode and also has a POSIX compliant and a restricted mode. Shell commands can be split up in three groups: the shell functions, shell built-ins and existing commands in a directory on your system. Bash supports additional built-ins not found in the plain Bourne shell. Shell scripts consist of these commands arranged as shell syntax dictates. Scripts are read and executed line per line and should have a logical structure. - Exercises @@ -549,7 +544,6 @@ exit 0 How many processes are currently running on your system? Use ps and wc, the first line of output of ps is not a process! How to display the system hostname? Only the name, nothing more! - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap10.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap10.xml index 799f0d92..380c6bf2 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap10.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap10.xml @@ -74,7 +74,7 @@ declare -- OTHERVAR="blah" As soon as you restrict assignment of values to a variable, it can only hold that type of data. Possible restrictions are either integer, constant or array. See the Bash info pages for information on return status. -Constants +Constants In Bash, constants are created by making a variable read-only. The readonly built-in marks each specified variable as unchangeable. The syntax is: readonly VARIABLE(s) The values of these variables can then no longer be changed by subsequent assignment. If the option is given, each variable refers to a shell function; see . If is specified, each variable refers to an array of variables. If no arguments are given, or if is supplied, a list of all read-only variables is displayed. Using the option, the output can be reused as input. @@ -86,7 +86,6 @@ declare -- OTHERVAR="blah" bash: TUX: readonly variable - Array variables Creating arrays @@ -149,14 +148,8 @@ one three four # $Id$ # $Log$ -# Revision 1.5 2004/12/06 12:27:09 tille -# changes for new domainname, minor corrections -# -# Revision 1.6 2004/10/18 18:58:06 tille -# debugging, typos removed, replaced screenshots in chap9 with screen sections. -# -# Revision 1.5 2004/06/24 14:02:48 tille -# dded tracer image +# Revision 1.2 2004/06/15 13:28:57 tille +# more markup, correction of some errors and typos, added alphabetical index # # Revision 1.4 2004/06/15 08:47:12 tille # more markup, index @@ -268,7 +261,6 @@ Reminder: the list of demos is here: EOF - Operations on variables Arithmetic on variables @@ -370,7 +362,7 @@ avery ${VAR##WORD} These constructs are used for deleting the pattern matching the expansion of WORD in VAR. WORD is expanded to produce a pattern just as in file name expansion. If the pattern matches the beginning of the expanded value of VAR, then the result of the expansion is the expanded value of VAR with the shortest matching pattern (#) or the longest matching pattern (indicated with ##). If VAR is * or @, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. -If VAR is an array variable subscribed with * or @, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. This is shown in the examples below: +If VAR is an array variable subscribed with * or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. This is shown in the examples below: [bob in ~] echo ${ARRAY[*]} one two one three one four @@ -410,13 +402,11 @@ thisisaverylongstring More information can be found in the Bash info pages. - Summary Normally, a variable can hold any type of data, unless variables are declared explicitly. Constant variables are set using the readonly built-in command. An array holds a set of variables. If a type of data is declared, then all elements in the array will be set to hold only this type of data. Bash features allow for substitution and transformation of variables on the fly. Standard operations include calculating the length of a variable, arithmetic on variables, substituting variable content and substituting part of the content. - Exercises Here are some brain crackers: diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap11.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap11.xml index 4d8dad4b..28225177 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap11.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap11.xml @@ -100,7 +100,6 @@ dir () } - Examples of functions in scripts Recycling @@ -218,12 +217,10 @@ echo -e "Remote backup `date` SUCCESS\n----------" >> "$LOGFILE" is equivalent to command > file 2>&1 - Summary Functions provide an easy way of grouping commands that you need to execute repetitively. When a function is running, the positional parameters are changed to those of the function. When it stops, they are reset to those of the calling program. Functions are like mini-scripts, and just like a script, they generate exit or return codes. While this was a short chapter, it contains important knowledge needed for achieving the ultimate state of laziness that is the typical goal of any system administrator. - Exercises @@ -234,7 +231,6 @@ echo -e "Remote backup `date` SUCCESS\n----------" >> "$LOGFILE" Create a subdirectory in your home directory in which you can store function definitions. Put a couple of functions in that directory. Useful functions might be, amongs others, that you have the same commands as on DOS or a commercial UNIX when working with Linux, or vice versa. These functions should then be imported in your shell environment when ~/.bashrc is read. - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap12.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap12.xml index bccccd8a..43facb3c 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap12.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap12.xml @@ -34,9 +34,11 @@ Standard key combinationMeaning -Ctrl+CThe interrupt signal, sends SIGINT to the job running in the foreground. -Ctrl+YThe delayed suspend character. Causes a running process to be stopped when it attempts to read input from the terminal. Control is returned to the shell, the user can foreground, background or kill the process. Delayed suspend is only available on operating systems supporting this feature. -Ctrl+ZThe suspend signal, sends a SIGTSTP to a running program, thus stopping it and returning control to the shell. +Ctrl+CThe interrupt signal. +Ctrl+SSuspend output (XOFF) +Ctrl+QResume output (XON) +Ctrl+YThe delayed suspend character. Causes a running process to be stopped when it attempts to read input from the terminal. Control is returned to the shell, the user can foreground, background or kill the process. +Ctrl+ZThe suspend character. Stops a running program and returns control to the shell. @@ -70,8 +72,7 @@ SIGKILL and SIGSTOP SIGKILL and SIGSTOP can not be caught, blocked or ignored. -When killing a process or series of processes, it is common sense to start trying with the least dangerous signal, SIGTERM. That way, programs that care about an orderly shutdown get the chance to follow the procedures that they have been designed to execute when getting the SIGTERM signal, such as cleaning up and closing open files. If you send a SIGKILL to a process, you remove any chance for the process to do a tidy cleanup and shutdown, which might have unfortunate consequences. -But if a clean termination does not work, the INT orKILL signals might be the only way. For instance, when a process does not die using Ctrl+C, it is best to use the kill on that process ID: +When killing a process or series of processes, it is common sense to start trying with the least dangerous signal, SIGTERM. If that does not work, use the INT orKILL signals. For instance, when a process does not die using Ctrl+C, it is best to use the kill on that process ID: maud: ~> ps | grep stuck_process maud 5607 2214 0 20:05 pts/5 00:00:02 stuck_process @@ -143,12 +144,10 @@ exit 0 - Summary Signals can be sent to your programs using the kill command or keyboard shortcuts. These signals can be caught, upon which action can be performed, using the trap statement. Some programs ignore signals. The only signal that no program can ignore is the KILL signal. - Exercises A couple of practical examples: @@ -156,6 +155,5 @@ exit 0 Create a script that writes a boot image to a diskette using the dd utility. If the user tries to interrupt the script using Ctrl+C, display a message that this action will make the diskette unusable. Write a script that automates the installation of a third-party package of your choice. The package must be downloaded from the Internet. It must be decompressed, unarchived and compiled if these actions are appropriate. Only the actual installation of the package should be uninterruptable. - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap2.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap2.xml index f6a647d5..426d7507 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap2.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap2.xml @@ -30,9 +30,6 @@ - -Example script using statements like "echo hello", "echo hello $USER" and "VARIABLE=value". - @@ -106,7 +103,6 @@ I'm giving you back your prompt now. willy:~/scripts> - Script basics Which shell will run the script? @@ -194,10 +190,6 @@ And this is a number: I'm giving you back your prompt now. + echo -Future Bash Features -There is now a full-fledged debugger for Bash, available at SourceForge. Right now however, you need a patched version of bash-2.05. The new debugging features might become available in bash-3.0. - - Debugging on part(s) of the script Using the set Bash built-in you can run in normal mode those portions of the script of which you are sure they are without fault, and display debugging information only for troublesome zones. Say we are not sure what the w command will do in the example commented-script1.sh, then we could enclose it in the script like this: @@ -288,13 +280,11 @@ echo "debug message: now attempting to start w command"; w echo "Variable VARNAME is now set to $VARNAME." - Summary A shell script is a reusable series of commands put in an executable text file. Any text editor can be used to write scripts. Scripts start with #! followed by the path to the shell executing the commands from the script. Comments are added to a script for your own future reference, and also to make it understandable for other users. It is better to have too many explanations than not enough. Debugging a script can be done using shell options. Shell options can be used for partial debugging or for analyzing the entire script. Inserting echo commands at strategic locations is also a common troubleshooting technique. - Exercises This exercise will help you to create your first script. @@ -306,6 +296,5 @@ echo "Variable VARNAME is now set to $VARNAME." Run the script in normal mode and in debug mode. It should run without errors. Make errors in your script: see what happens if you misspell commands, if you leave out the first line or put something unintelligible there, or if you misspell shell variable names or write them in lower case characters after they have been declared in capitals. Check what the debug comments say about this. - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap3.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap3.xml index c20caa26..c1e5042f 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap3.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap3.xml @@ -222,9 +222,6 @@ clear - -Prompt 1 is "franky ~>; prompt is then changed with "export PS1="\[\033[1;42m\]$USER is in \w\[\033[0m\] " resulting in a green reverse video prompt displaying username and present working directory in humanly readable form. Prompt for root is set using a similar PS1 configuration to be bright red reverse video. - Most shell scripts execute in a private environment: variables are not inherited by child processes unless they are exported by the parent shell. Sourcing a file containing shell commands is a way of applying changes to your own environment and setting variables in the current shell. @@ -241,7 +238,6 @@ export PS1="[some value]" echo "PS1 is now set to $PS1" - Variables @@ -259,7 +255,7 @@ CFLAGS=-O2 -fomit-frame-pointer COLORTERM=gnome-terminal CXXFLAGS=-O2 -fomit-frame-pointer DISPLAY=:0 -DOMAIN=hq.xalasys.com +DOMAIN=hq.soti.org e= TOR=vi FCEDIT=vi @@ -275,7 +271,7 @@ HISTFILESIZE=5000 history_control=ignoredups HISTSIZE=2000 HOME=/nethome/franky -HOSTNAME=octarine.hq.xalasys.com +HOSTNAME=octarine.hq.soti.org INPUTRC=/etc/inputrc IRCNAME=franky JAVA_HOME=/usr/java/j2sdk1.4.0 @@ -309,7 +305,7 @@ PATH=/nethome/franky/bin.Linux:/nethome/franky/bin:/usr/local/bin:/usr/local/sbi PS1=\[\033[1;44m\]franky is in \w\[\033[0m\] PS2=More input> PWD=/nethome/franky -SESSION_MANAGER=local/octarine.hq.xalasys.com:/tmp/.ICE-unix/22106 +SESSION_MANAGER=local/octarine.hq.soti.org:/tmp/.ICE-unix/22106 SHELL=/bin/bash SHELL_LOGIN=--login SHLVL=2 @@ -341,7 +337,7 @@ YACC=bison -y Below is a diff file made by comparing printenv and set output, after leaving out the functions which are also displayed by the set command: franky ~> diff set.sorted printenv.sorted | grep "<" | awk '{ print $2 }' -BASE=/nethome/franky/.Shell/hq.xalasys.com/octarine.aliases +BASE=/nethome/franky/.Shell/hq.soti.org/octarine.aliases BASH=/bin/bash BASH_VERSINFO=([0]="2" BASH_VERSION='2.05b.0(1)-release' @@ -713,7 +709,6 @@ echo backup succeeded > $LOGFILE The above is purely an example that everybody can understand, using a small directory and a host on the same subnet. Depending on your bandwidth, the size of the directory and the location of the remote server, it can take an awful lot of time to make backups using this mechanism. For larger directories and lower bandwidth, use rsync to keep the directories at both ends synchronized. - Quoting characters @@ -771,7 +766,6 @@ I'd say: "Go for it!" A double-quoted string preceded by a dollar sign will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted. - Shell expansion @@ -851,7 +845,7 @@ Thu Feb 6 10:06:20 CET 2003 Arithmetic expansion Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:$(( EXPRESSION )) The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, command substitution, and quote removal. Arithmetic substitutions may be nested. -Evaluation of arithmetic expressions is done in fixed-width integers with no check for overflow - although division by zero is trapped and recognized as an error. The operators are the same as in the C programming language. In order of decreasing precedence, the list looks like this: +Evaluation of arithmetic expressions is done in fixed-width integers with no check for overflow - although division by zero is trapped and recognized as an error. The operators are roughly the same as in the C programming language. In order of decreasing precedence, the list looks like this: Arithmetic operators @@ -868,7 +862,7 @@ Thu Feb 6 10:06:20 CET 2003 + and -addition, subtraction << and >>left and right bitwise shifts <=, >=, < and >comparison operators -== and !==equality and inequality +== and !=equality and inequality &bitwise AND ^bitwise exclusive OR |bitwise OR @@ -904,7 +898,7 @@ leading 0x or 0X denotes hexadecimal. Otherwise, Word splitting The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting. -The shell treats each character of $IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IF is unset, or its value is exactly '<space><tab><newline>', the default, then any sequence of IFS characters serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters space and Tab are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IF whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs. +The shell treats each character of $IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly '<space><tab><newline>', the default, then any sequence of IFS characters serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters space and Tab are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IF whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs. Explicit null arguments ("" or '') are retained. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained. Expansion and word splittingIf no expansion occurs, no splitting is performed. @@ -913,7 +907,6 @@ leading 0x or 0X denotes hexadecimal. Otherwise, When a pattern is used for file name generation, the character . at the start of a file name or immediately following a slash must be matched explicitly, unless the shell option is set. When matching a file name, the slash character must always be matched explicitly. In other cases, the . character is not treated specially. The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. The file names . and .. are always ignored, even when GLOBIGNORE is set. However, setting GLOBIGNORE has the effect of enabling the shell option, so all other file names beginning with a . will match. To get the old behavior of ignoring file names beginning with a ., make .* one of the patterns in GLOBIGNORE. The option is disabled when GLOBIGNORE is unset. - Aliases @@ -946,8 +939,8 @@ alias ping='ping -vc1' alias sb='ssh blubber' alias sl='ls' alias ss='ssh octarine' -alias sss='ssh -C server1.us.xalasys.com' -alias sssu='ssh -C -l root server1.us.xalasys.com' +alias sss='ssh -C server1.us.soti.org' +alias sssu='ssh -C -l root server1.us.soti.org' alias tar='gtar' alias tmp='cd /tmp' alias unaliasall='unalias -a' @@ -991,7 +984,6 @@ bash: dh: command not found Functions are fasterAliases are looked up after functions and thus resolving is slower. While aliases are easier to understand, shell functions are preferred over aliases for almost every purpose. - More Bash options Displaying options @@ -1068,7 +1060,6 @@ bash: VAR: unbound variable -rw-rw-r-- 1 willy willy 0 Feb 27 13:37 * - @@ -1078,7 +1069,6 @@ bash: VAR: unbound variable Except for the reserved Bourne shell, Bash and special parameters, variable names can be chosen more or less freely. Because a lot of characters have double or even triple meanings, depending on the environment, Bash uses a system of quoting to take away special meaning from one or multiple characters when special treatment is not wanted. Bash uses various methods of expanding command line entries in order to determine which commands to execute. - Exercises For this exercise, you will need to read the useradd man pages, because we are going to use the /etc/skel directory to hold default shell configuration files, which are copied to the home directory of each newly added user. @@ -1096,6 +1086,5 @@ bash: VAR: unbound variable Write a script in which you assign two integer values to two variables. The script should calculate the surface of a rectangle which has these proportions. It should be aired with comments and generate elegant output. Don't forget to chmod your scripts! - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap4.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap4.xml index 2942cb81..a164ad9f 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap4.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap4.xml @@ -178,7 +178,6 @@ for i in /etc/profile.d/*.sh ; do - Pattern matching using Bash features Character ranges @@ -224,7 +223,6 @@ drwxrwxr-x 4 cathy cathy 4096 Jul 11 2002 OpenOffice.org1.0/ Regular expressions are powerful tools for selecting particular lines from files or output. A lot of UNIX commands use regular expressions: vim, perl, the PostgreSQL database and so on. They can be made available in any language or application using external libraries, and they even found their way to non-UNIX systems. For instance, regular expressions are used in the Excell spreadsheet that comes with the MicroSoft Windows Office suite. In this chapter we got the feel of the grep command, which is indispensable in any UNIX environment. The grep command can do much more than the few tasks we discussed here; we only used it as an example for regular expressions. The GNU grep version comes with plenty of documentation, which you are strongly advised to read! Bash has built-in features for matching patterns and can recognize character classes and ranges. - Exercises These exercises will help you master regular expressions. @@ -243,7 +241,6 @@ drwxrwxr-x 4 cathy cathy 4096 Jul 11 2002 OpenOffice.org1.0/ Make a script that checks whether a user exists in /etc/passwd. For now, you can specify the user name in the script, you don't have to work with arguments and conditionals at this stage. Display configuration files in /etc that contain numbers in their names. - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap5.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap5.xml index 2395039c..91c5779a 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap5.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap5.xml @@ -222,7 +222,6 @@ This is the final line. grep sed * - Non-interactive editing Reading sed commands from a file @@ -297,12 +296,10 @@ line3 Easy sed Advanced editors, supporting syntax highlighting, can recognize sed syntax. This can be a great help if you tend to forget backslashes and such. - Summary The sed stream editor is a powerful command line tool, which can handle streams of data: it can take input lines from a pipe. This makes it fit for non-interactive use. The sed editor uses vi-like commands and accepts regular expressions. The sed tool can read commands from the command line or from a script. It is often used to perform find-and-replace actions on lines containing a pattern. - Exercises These exercises are meant to further demonstrate what sed can do. @@ -316,6 +313,5 @@ line3 A long listing of the root directory, /, is used for input. Create a file holding sed commands that check for symbolic links and plain files. If a file is a symbolic link, precede it with a line like --This is a symlink--. If the file is a plain file, add a string on the same line, adding a comment like <--- this is a plain file. Create a script that shows lines containing trailing white spaces from a file. This script should use a sed script and show sensible information to the user. - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap6.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap6.xml index 537c3e79..78ae90dd 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap6.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap6.xml @@ -45,14 +45,11 @@ contain function definitions, loops, conditions and other programming constructs - -Fields as interpreted by awk: first column is $1, second column is $2 and so on. - In the output of ls , there are 9 columns. The print statement uses these fields as follows: -kelly@octarine ~/test> ls | awk '{ print $9 $5 }' +kelly@octarine ~/test> ls | awk '{ print $5 $9 }' 160orig 121script.sed 120temp_file @@ -125,9 +122,9 @@ Partition /home : 70% full! Slashes need to be escaped, because they have a special meaning to the awk program. -Below another example where we search the /etc directory for files ending in .conf and starting with either a or x, using extended regular expressions: +Below another example where we search the /etc directory for files ending in .conf and starting with either a or x: -kelly is in /etc> ls | awk '/\<(a|x).*\.conf$/ { print $9 }' +kelly is in /etc> ls | awk '/\<[a|x].*\.conf$/ { print $9 }' amd.conf antivir.conf xcdroast.conf @@ -187,7 +184,6 @@ Partition /usr : 97% full! Syntax highlighting Awk is a programming language. Its syntax is recognized by most editors that can do syntax highlighting for other languages, such as C, Bash, HTML, etc. - Gawk variables As awk is processing the input file, it uses several variables. Some are editable, some are read-only. @@ -318,7 +314,7 @@ Total revenue: 19500 kelly@octarine ~/html> cat make-html-from-text.awk BEGIN { print "<html>\n<head><title>Awk-generated HTML</title></head>\n<body bgcolor=\"#ffffff\">\n<pre>" } { print $0 } -END { print "</pre>\n</body>\n</html>" } +END { print "</pre>\n</body>\n</html<" } And the command to execute is also much more straightforward when using awk instead of sed: @@ -339,7 +335,6 @@ END { print "</pre>\n</body>\n</html>" } The gawk utility interprets a special-purpose programming language, handling simple data-reformatting jobs with just a few lines of code. It is the free version of the general UNIX awk command. This tools reads lines of input data and can easily recognize columned output. The print program is the most common for filtering and formatting defined fields. On-the-fly variable declaration is straightforward and allows for simple calculation of sums, statistics and other operations on the processed input stream. Variables and commands can be put in awk scripts for background processing. - Exercises diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap7.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap7.xml index b72379bc..9094d68f 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap7.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap7.xml @@ -175,7 +175,7 @@ not a local account anny > echo $num 201 -anny > if [ "num" > 150 ] +anny > if [ "num" > "150" ] More input> then echo ; echo "you've worked hard enough for today." More input> echo ; fi @@ -211,9 +211,15 @@ fi With Bash, you can shorten this type of construct. The compact equivalent of the above test is as follows: -[ "$(whoami)" != 'root' ] && echo you are using a non-privileged account +[ "$(whoami)" != 'root' ] && ( echo you are using a non-privileged account; exit 1 ) -Regular expressions may also be used: +Real Programmers +Most programmers will even prefer to use test, which is equivalent to using the square brackets, like this: + +test "$(whoami)" != 'root' && ( echo you are using a non-privileged account; exit 1) + + +Regular expressions may also be used in comparisons: anny > gender="female" @@ -268,9 +274,6 @@ your account is managed from the local /etc/passwd file - -Simple if/then/else/fi construct: if [ "$1" == fish ]; then echo "Tux likes this"; else echo "Tux wants fish!"; fi - Here's another example, using two arguments: @@ -364,7 +367,7 @@ fi CONSEQUENT-COMMANDS; elif MORE-TEST-COMMANDS; then MORE-CONSEQUENT-COMMANDS; -else ALTERNATE-CONSEQUENT-COMMANDS; +else ALTERNATE-CONSEQUENT-COMMANDS; then fi The TEST-COMMANDS list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed. If TEST-COMMANDS returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding MORE-CONSEQUENT-COMMANDS is executed and the command completes. If else is followed by an ALTERNATE-CONSEQUENT-COMMANDS list, and the final command in the final if or elif clause has a non-zero exit status, then ALTERNATE-CONSEQUENT-COMMANDS is executed. The return status is the exit status of the last command executed, or zero if no condition tested true. @@ -390,7 +393,7 @@ fi Nested if statements -Inside the if statement, you can use another if statement. You may use as many levels of nested ifs as you can logically manage. +Inside the if statement, you can use another if statement. You may virtually use as many levels of nested ifs as you can logically manage (actually the number of nested ifs is limited to 2500, but it is dubious that anybody would ever need that many). This is an example testing leap years: anny ~/testdir> cat testleap.sh @@ -427,9 +430,6 @@ This is not a leap year. - -year=`date +%Y`; if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ("$year" % 100 != "0") )); then echo "this is a leap year."; else echo "not a leap year"; fi - We use the double brackets for testing an arithmetic expression, see . This is equivalent to the let statement. You will get stuck using angular brackets here, if you try something like $[$year % 400], because here, the angular brackets don't represent an actual command by themselves. @@ -609,7 +609,6 @@ esac In this chapter we learned how to build conditions into our scripts so that different actions can be undertaken upon success or failure of a command. The actions can be determined using the if statement. This allows you to perform arithmetic and string comparisons, and testing of exit code, input and files needed by the script. A simple if/then/fi test often preceeds commands in a shell script in order to prevent output generation, so that the script can easily be run in the background or through the cron facility. More complex definitions of conditions are usually put in a case statement. Upon successful condition testing, the script can explicitly inform the parent using the exit 0 status. Upon failure, any other number may be returned. Based on the return code, the parent program can take appropriate action. - Exercises Here are some ideas to get you started using if in scripts: @@ -625,6 +624,5 @@ esac The script should also check for available diskspace. Keep in mind that at any given moment you could have the data in your home directory, the data in the .tar file and the data in the compressed archive all together on your disk. If there is not enough diskspace, exit with an error message in the log file. The script should clean up the compressed archive before it exits. - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap8.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap8.xml index fcb74f04..b428c142 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap8.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap8.xml @@ -152,7 +152,6 @@ Usage of the feed script: ./feed.sh food-on-menu animal-name
For more information about the printf command and the way it allows you to format output, see the Bash info pages.
-
Catching user input Using the read built-in command @@ -570,12 +569,10 @@ Transaction(s) Complete - Summary In this chapter, we learned how to provide user comments and how to prompt for user input. This is usually done using the echo/read combination. We also discussed how files can be used as input and output using file descriptors and redirection, and how this can be combined with getting input from the user. We stressed the importance of providing ample message for the users of our scripts. As always when others use your scripts, it is better to give too much information than not enough. Here documents is a type of shell construct that allows creation of lists, holding choices for the users. This construct can also be used to execute otherwise interactive tasks in the background, without intervention. - Exercises These exercises are practical applications of the constructs discussed in this chapter. When writing the scripts, you may test by using a test directory that does not contain too much data. Write each step, then test that portion of code, rather than writing everything at once. @@ -593,7 +590,7 @@ Transaction(s) Complete Compress the backup using any compression tool. Inform the user that the script is doing this, because it might take some time, during which the user might start worrying if no output appears on the screen. Print a message informing the user about the size of the compressed backup. -See info tar or Introduction to Linux, chapter 9: Preparing your data for background information. +See info tar or Introduction to Linux, chapter 9: Preparing your data for background information. Write a script called simple-useradd.sh that adds a local user to the system. This script should: @@ -607,6 +604,5 @@ Transaction(s) Complete Rewrite the script from so that it reads input from the user instead of taking it from the first argument. - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/chap9.xml b/LDP/guide/docbook/Bash-Beginners-Guide/chap9.xml index 364520fc..3a5f480d 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/chap9.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/chap9.xml @@ -55,7 +55,6 @@ done Since we don't do a line count here, there is no way of knowing the line number from which to start deleting lines until reaching the end. The problem is solved using tac, which reverses the lines in a file. - The while loop What is it? @@ -84,31 +83,14 @@ done Nested while loops The example below was written to copy pictures that are made with a webcam to a web directory. Every five minutes a picture is taken. Every hour, a new directory is created, holding the images for that hour. Every day, a new directory is created containing 24 subdirectories. The script runs in the background. - -#!/bin/bash - -# This script copies files from my homedirectory into the webserver directory. -# (use scp and SSH keys for a remote directory) -# A new directory is created every hour. - -PICSDIR=/home/carol/pics -WEBDIR=/var/www/carol/webcam - -while true; do - DATE=`date +%Y%m%d` - HOUR=`date +%H` - mkdir $WEBDIR/"$DATE" - - while [ $HOUR -ne "00" ]; do - DESTDIR=$WEBDIR/"$DATE"/"$HOUR" - mkdir "$DESTDIR" - mv $PICDIR/*.jpg "$DESTDIR"/ - sleep 3600 - HOUR=`date +%H` - done -done - - +
Nested while loops - picturesort.sh + + + + + + +
Note the use of the true statement. This means: continue execution until we are forcibly interrupted (with kill or Ctrl+C). This small script can be used for simulation testing; it generates files: @@ -121,10 +103,7 @@ touch pic-`date +%s`.jpg sleep 300 done -Note the use of the date command to generate all kinds of file and directory names. See the man page for more. -Use the system -The previous example is for the sake of demonstration. Regular checks can easily be achieved using the system's cron facility. Do not forget to redirect output and errors when using scripts that are executed from your crontab! - +Note the use of the date command to generate all kinds of file and directory names.
Using keyboard input to control the while loop This script can be interrupted by the user when a Ctrl+C sequence is entered: @@ -198,7 +177,6 @@ echo "Exiting."
-
The until loop What is it? @@ -210,43 +188,16 @@ echo "Exiting." Example An improved picturesort.sh script (see ), which tests for available disk space. If not enough disk space is available, remove pictures from the previous months: - -#!/bin/bash - -# This script copies files from my homedirectory into the webserver directory. -# A new directory is created every hour. -# If the pics are taking up too much space, the oldest are removed. - -while true; do - DISKFUL=$(df -h $WEBDIR | grep -v File | awk '{print $5 }' | cut -d "%" -f1 -) - - until [ $DISKFUL -ge "90" ]; do - - DATE=`date +%Y%m%d` - HOUR=`date +%H` - mkdir $WEBDIR/"$DATE" - - while [ $HOUR -ne "00" ]; do - DESTDIR=$WEBDIR/"$DATE"/"$HOUR" - mkdir "$DESTDIR" - mv $PICDIR/*.jpg "$DESTDIR"/ - sleep 3600 - HOUR=`date +%H` - done - - DISKFULL=$(df -h $WEBDIR | grep -v File | awk '{ print $5 }' | cut -d "%" -f1 -) - done - - TOREMOVE=$(find $WEBDIR -type d -a -mtime +30) - for i in $TOREMOVE; do - rm -rf "$i"; - done - -done - +
More nested while loops - safesort.sh + + + + + + +
Note the initialization of the HOUR and DISKFULL variables and the use of options with ls and date in order to obtain a correct listing for TOREMOVE.
-
I/0 redirection and loops Input redirection @@ -279,7 +230,6 @@ done Files are compressed before they are moved into the archive directory. - Break and continue The break built-in @@ -419,7 +369,6 @@ new name for TEST is test The tr is part of the textutils package; it can perform all kinds of character transformations. - Making menus with the select built-in General @@ -488,7 +437,6 @@ rm "$QUIT" Any statement within a select construct can be another select loop, enabling (a) submenu(s) within a menu. By default, the PS3 variable is not changed when entering a nested select loop. If you want a different prompt in the submenu, be sure to set it at the appropriate time(s). - The shift built-in What does it do? @@ -515,6 +463,7 @@ while (( "$#" )); do if [[ "$(ls $1)" == "" ]]; then echo "Empty directory, nothing to be done." + shift else find $1 -type f -a -atime +365 -exec rm -i {} \; fi @@ -523,11 +472,6 @@ shift done --exec vs. xargs -The above find command can be replaced with the following: -find | xargs [commands_to_execute_on_found_files -The xargs command builds and executes command lines from standard input. This has the advantage that the command line is filled until the system limit is reached. Only then will the command to execute be called, in the above example this would be rm. If there are more arguments, a new command line will be used, until that one is full or until there are no more arguments. The same thing using find calls on the command to execute on the found files every time a file is found. Thus, using xargs greatly speeds up your scripts and the performance of your machine. - In the next example, we modified the script from so that it accepts multiple packages to install at once: #!/bin/bash @@ -543,14 +487,12 @@ while (($#)); do done - Summary In this chapter, we discussed how repetitive commands can be incorporated in loop constructs. Most common loops are built using the for, while or until statements, or a combination of these commands. The for loop executes a task a defined number of times. If you don't know how many times a command should execute, use either until or while to specify when the loop should end. Loops can be interrupted or reiterated using the break and continue statements. A file can be used as input for a loop using the input redirection operator, loops can also read output from commands that is fed into the loop using a pipe. The select construct is used for printing menus in interactive scripts. Looping through the command line arguments to a script can be done using the shift statement. - Exercises Remember: when building scripts, work in steps and test each step before incorporating it in your script. @@ -571,6 +513,5 @@ done - diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/gloss.xml b/LDP/guide/docbook/Bash-Beginners-Guide/gloss.xml index 7d87fcfb..b148036b 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/gloss.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/gloss.xml @@ -1386,13 +1386,6 @@ X - - xargs - - Build and execute command lines from standard input. - - - xauth diff --git a/LDP/guide/docbook/Bash-Beginners-Guide/index-gloss.xml b/LDP/guide/docbook/Bash-Beginners-Guide/index-gloss.xml index 05e09510..897e91af 100644 --- a/LDP/guide/docbook/Bash-Beginners-Guide/index-gloss.xml +++ b/LDP/guide/docbook/Bash-Beginners-Guide/index-gloss.xml @@ -139,7 +139,7 @@ character classes - , + , @@ -255,7 +255,7 @@ else - + @@ -338,7 +338,7 @@ exit - + @@ -380,7 +380,7 @@ file name expansion - + @@ -948,7 +948,7 @@ standard output - +