From e32f343590310f38b5515d332cf11cdc9f90090b Mon Sep 17 00:00:00 2001 From: gferg <> Date: Thu, 8 Nov 2007 15:53:07 +0000 Subject: [PATCH] new --- LDP/guide/docbook/abs-guide/INDEX00.sgml | 3008 +++++++++++++++++ LDP/guide/docbook/abs-guide/ascii.c | 38 + LDP/guide/docbook/abs-guide/brownian.sh | 115 + LDP/guide/docbook/abs-guide/ex68a.sh | 36 + LDP/guide/docbook/abs-guide/from.sh | 24 + .../docbook/abs-guide/insertion-sort.bash | 65 + LDP/guide/docbook/abs-guide/opprec-table.sgml | 177 + LDP/guide/docbook/abs-guide/rand-string.sh | 29 + LDP/guide/docbook/abs-guide/splitcopy.sh | 25 + 9 files changed, 3517 insertions(+) create mode 100644 LDP/guide/docbook/abs-guide/INDEX00.sgml create mode 100644 LDP/guide/docbook/abs-guide/ascii.c create mode 100644 LDP/guide/docbook/abs-guide/brownian.sh create mode 100644 LDP/guide/docbook/abs-guide/ex68a.sh create mode 100644 LDP/guide/docbook/abs-guide/from.sh create mode 100644 LDP/guide/docbook/abs-guide/insertion-sort.bash create mode 100644 LDP/guide/docbook/abs-guide/opprec-table.sgml create mode 100644 LDP/guide/docbook/abs-guide/rand-string.sh create mode 100644 LDP/guide/docbook/abs-guide/splitcopy.sh diff --git a/LDP/guide/docbook/abs-guide/INDEX00.sgml b/LDP/guide/docbook/abs-guide/INDEX00.sgml new file mode 100644 index 00000000..e5245ec5 --- /dev/null +++ b/LDP/guide/docbook/abs-guide/INDEX00.sgml @@ -0,0 +1,3008 @@ + This index / glossary / quick-reference lists many of the + important topics covered in the text. Terms are arranged in + approximate sorting order, reshuffled as + necessary for enhanced clarity. + + Note that commands are indexed + in Part 4. + + * * * + + + ^ (caret) + Beginning-of-line, in a Regular Expression + + + ~ Tilde + + + + ~ + home directory, corresponds + to $HOME + + + + + + ~/ + Current user's + home directory + + + + ~+ + Current + working directory + + + + ~- + Previous + working directory + + + + + + + + = Equals sign + + + + = + Variable assignment operator + + + + = + String comparison operator + + + == + String comparison operator + + + + + =~ + Regular Expression + match operator + + Example + script + + + + + + + + + + < Left angle bracket + + + Is-less-than + String comparison + + Integer comparison within + double parentheses + + + + Redirection + + + < + stdin + + + << + Here document + + + <<< + Here string + + + <> + Opening a file for + both reading and writing + + + + + + + + > Right angle bracket + + + Is-greater-than + String comparison + Integer comparison, + within double parentheses + + + + Redirection + + > + Redirect + stdout to a file + + + >> + Redirect + stdout to a file, + but append + + + i>&j + Redirect + file descriptor + i to + file descriptor + j + + >&j + Redirect + stdout to + file descriptor + j + + >&2 + Redirect + stdout of a command to + stderr + + 2>&1 + Redirect + stderr + to stdout + + &> + Redirect + both stdout + and stderr of a command to a + file + + :> file + Truncate file + to zero length + + + + + + + + + | + Pipe, a device for passing the output + of a command to another command or to the shell + || + Logical OR test operator + + + + - (dash) + + + + Prefix to default + parameter, in parameter + substitution + + Prefix to option + flag + + + Indicating + redirection from + stdin or stdout + + + + -- (double-dash) + Prefix to + long command options + + C-style + variable decrement within double + parentheses + + + + + + + + ; (semicolon) + + As command + separator + \; + Escaped semicolon, + terminates a find + command + ;; + Double-semicolon, terminator in a + case option + + + Required when ... + do + keyword is on the first line of + loop + + terminating curly-bracketed + code block + + + + + : + Colon, null + command, equivalent to the + true Bash builtin + + + :> file + Truncate file + to zero length + + + ! + Negation operator, inverts exit status of a test or command + + != + not-equal-to + String comparison operator + + + + ? (question mark) + + + + Match zero or one characters, + in an Extended Regular + Expression + Single-character + wild card, + in globbing + In a + C-style + Trinary operator + + + + + + // + Double forward slash, + behavior of cd command toward + + + + . (dot / period) + + + + . + Load a file (into a script), + equivalent to source command + + + + . + Match single character, + in a Regular Expression + + + + . + Current working + directory + + + ./ + Current working + directory + + + + .. + Parent + directory + + + + + + + + ' ... ' + (single quotes) + strong + quoting + + " ... " + (double quotes) + weak + quoting + + + + () Parentheses + + + ( ... ) + Command group; + starts a + subshell + ( ... ) + Enclose group + of Extended Regular + Expressions + + >( ... ) + <( ... ) + Process substitution + + + ... ) + Terminates test-condition + in case construct + (( ... )) + Double parentheses, + in arithmetic expansion + + + + [ Left bracket, + test construct + + [ ]Brackets + + Array + element + Enclose character set + to match in a Regular + Expression + Test construct + + + + + [[ ... ]] + Double brackets, + extended test construct + + $ + Anchor, + in a Regular Expression + $ + Prefix to a variable name + $( ... ) + Command substitution, + setting a variable with output of a command, + using parentheses notation + ` ... ` + Command substitution, + using backquotes + notation + + + ${ ... } Variable manipulation / evaluation + + + ${var} + Value of a variable + + ${#var} + Length of a variable + + + ${#@} + ${#*} + Number of + positional + parameters + + + ${parameter?err_msg} + Parameter-unset + message + + + ${parameter-default} + ${parameter:-default} + ${parameter=default} + ${parameter:=default} + Set default + parameter + + + ${parameter+alt_value} + ${parameter:+alt_value} + Alternate value + of parameter, if set + + + + ${!var} + Indirect referencing of a variable, + new notation + + + + ${!varprefix*} + ${!varprefix@} + Match + names of all previously declared + variables beginning with varprefix + + + + ${string:position} + ${string:position:length} + Substring + extraction + + + ${var#Pattern} + ${var##Pattern} + Substring + removal + + + ${var%Pattern} + ${var%%Pattern} + Substring + removal + + + ${string/substring/replacement} + ${string//substring/replacement} + ${string/#substring/replacement} + ${string/%substring/replacement} + Substring + replacement + + + + + \ + Escape the character following + + \< ... \> + Angle brackets, + escaped, + word boundary in a Regular + Expression + \{ N \} + Curly brackets, + escaped, + number of character sets to match in an Extended RE + \; + Semicolon, + escaped, + terminates a find + command + \$$ Indirect + reverencing of a variable, old-style notation + Escaping + a newline, + to write a multi-line command + + + + & + + + + &> + Redirect + both stdout + and stderr of a command to a + file + + + >&j + Redirect + stdout to + file descriptor + j + + >&2 + Redirect + stdout of a command to + stderr + + + i>&j + Redirect + file descriptor + i to + file descriptor + j + + 2>&1 + Redirect + stderr to + stdout + + Closing file + descriptors + + n<&- + Close input file descriptor + n + 0<&-, + <&- + Close stdin + n>&- + Close output file descriptor + n + 1>&-, + >&- + Close stdout + + + + && + Logical AND + test operator + + + Command & + Run job in + background + + + + + + + # + Hashmark, + special symbol beginning a script + comment + + #! + Sha-bang, + special string starting a + shell script + + + * Asterisk + + + + Wild + card, + in globbing + + + + Any number of characters + in a Regular Expression + + + + ** + Exponentiation, + arithmetic operator + + + + + + % Percent sign + + + + Modulo, division-remainder + arithmetic operation + + + + Substring removal + (pattern matching) operator + + + + + + + Plus sign + + Character + match, in an extended Regular + Expression + Prefix to + alternate parameter, in + parameter substitution + ++ + C-style + variable increment, within double + parentheses + + + * * * + + Shell Variables + + $_ + Last argument to previous + command + $- + Flags passed to script, using set + $! + Process ID + of last background job + $? + Exit + status of a command + $@ + All the positional parameters, as separate + words + $* + All the positional parameters, as a single + word + $$ + Process ID of the + script + $# + Number of arguments passed to a + function, or to the script + itself + $0 + Filename of the script + $1 + First argument passed to script + $9 + Ninth argument passed to script + Table + of shell variables + + + + * * * * * * + + -a + Logical AND + compound comparison test + Advanced Bash Scripting Guide, + where to download + + Alias + + Removing an + alias, using + unalias + + + And list + + + To supply default command-line + argument + + + Angle brackets, + escaped, + \< . . . \> + word boundary in a Regular + Expression + Anonymous + here document, using + : + + + Arithmetic expansion + + + variations of + + + + Arithmetic operators + + + combination operators, C-style + += + -= + *= + /= + %= + + + In certain contexts, + += can also function as a string + concatenation operator. + + + + + + Arrays + + Bracket notation + + Concatenating, + example script + Copying + + Declaring + declare -a + array_name + + Embedded + arrays + Empty + arrays, empty elements, example + script + Indirect references + + + + Initialization + array=( element1 element2 ... elementN) + Example + script + Using command + substitution + + + Loading a + file into an array + Multidimensional, + simulating + Nesting and + embedding + Notation + and usage + Number of elements in + ${#array_name[@]} + ${#array_name[*]} + Operations + Passing + an array to a + function + As + return value from + a function + Special properties, + example script + String operations, + example script + unset deletes array + elements + + + + awk field-oriented text + processing language + + + rand(), + random function + String + manipulation + Using + export to pass a variable to an + embedded awk script + + + + * * * + + Backquotes, + used in command + substitution + Base conversion, + example script + + + Bash + + + Bad scripting + practices + Basics reviewed, + script example + + Command-line + options + Table + + Features that classic + Bourne shell lacks + + Internal variables + + + Version 2 + + Version 3 + + + + + + $BASH_SUBSHELL + Basic commands, external + Batch processing + + bc, calculator utility + + In a here + document + Template + for calculating a script variable + + + Bison utility + Bitwise operators + + Blocks of code + + + Redirection + Script + example: + redirecting output of a a code block + + + + Brace expansion + + Extended, + {a..z} + + + + Brackets, [ ] + + Array + element + Enclose character set + to match in a Regular + Expression + Test construct + + + + Brackets, curly, {}, + used in + + Code + block + + find + Extended Regular + Expressions + Positional + parameters + xargs + + + + + break + loop control command + + Parameter + (optional) + + + Builtins in + Bash + + Do not fork a subprocess + + + + * * * + + case + construct + + Command-line parameters, + handling + Globbing, + filtering strings with + + + cat, + concatentate file(s) + + Abuse of + cat + scripts + Less efficient than + redirecting stdin + Piping the output + of, to a read + Uses of + + + + Child processes + Colon, : , + equivalent to the true Bash + builtin + + Colorizing scripts + + Table of + color escape sequences + Template, + colored text on colored background + + + Comma operator, + linking commands or operations + + Command substitution + + + + $( ... ), + preferred notation + + Backquotes + Extending the + Bash toolset + Invokes a + subshell + Nesting + Removes trailing newlines + + Setting variable from loop output + + Word splitting + + + Comment headers, + special purpose + + Commenting out blocks of code + + Using an anonymous here + document + Using an + if-then construct + + + + + Compound comparison + operators + continue loop control command + + + Control characters + + Control-C, + break + Control-D, + terminate / log out / erase + Control-H, + rubout + Control-M, + Carriage return + + + + C-style syntax + , for handling variables + + Curly brackets {} + + in + find command + in an + Extended Regular + Expression + in + xargs + + + * * * + + Daemons, in UNIX-type OS + + dc, calculator utility + + dd, data + duplicator command + + + Conversions + Copying raw data + to/from devices + File deletion, + secure + Keystrokes, capturing + Options + Random access on a data + stream + Swapfiles, initializing + Thread on + www.linuxquestions.org + + + + Debugging scripts + + Tools + Trapping at + exit + Trapping + signals + + + Decimal number, + Bash interprets numbers as + + declare builtin + + options + + + Default parameters + + + /dev directory + + + /dev/null + pseudo-device file + + /dev/urandom + pseudo-device file, generating pseudorandom numbers + with + + /dev/zero, + pseudo-device file + + + + + dialog, + utility for generating dialog boxes in + a script + $DIRSTACK + directory stack + Disabled commands, + in restricted shells + do keyword, + begins execution of commands within a loop + done keyword, + terminates a loop + DOS batch + files, converting to shell scripts + DOS + commands, UNIX equivalents of + (table) + dot files, + hidden setup and configuration files + Double brackets + [[ ... ]] test + construct + Double quotes + " ... " weak quoting + Double-spacing a text + file, using sed + + * * * + + -e + File exists test + + echo + + Feeding commands down + a pipe + Setting a variable + using command + substitution + /bin/echo, + external echo command + + + elif, Contraction + of else and if + esac, keyword terminating + case construct + Environmental + variables + -eq , + is-equal-to integer + comparison test + Eratosthenes, + Sieve of, algorithm for generating prime numbers + Escaped characters, + special meanings of + $EUID, + Effective user ID + + eval, + Combine and evaluate expression(s), + with variable expansion + + Effects + of, Example script + Forces + reevaluation of + arguments + Risk of + using + + + exec command, + using in redirection + + + + Exit and Exit status + + exit + command + + + Exit status + (exit code, return + status of a command) + Table, + Exit + codes with special meanings + Out of range + + Specified by a function + return + Successful, + 0 + + + + + + Export, + to make available variables to child processes + + Passing a variable + to an embedded awk + script + + + + expr, + Expression evaluator + + Substring + extraction + Substring + index (numerical position in + string) + Substring + matching + + + + Extended Regular + Expressions + + ? (question mark) + Match zero / one characters + + ( ... ) + Group + of expressions + \{ N \} + Curly brackets, + escaped, + number of character sets to match + + + Character + match + + + * * * + + false, + returns unsuccessful (1) exit status + File descriptors + + Closing + + n<&- + Close input file descriptor n + 0<&-, + <&- + Close stdin + + n>&- + Close output file descriptor n + 1>&-, + >&- + Close stdout + + + + File handles in + C, similarity to + + + + find + + {} + Curly + brackets + \; + Escaped + semicolon + + + Filter, + feeding output back to same filter + Floating point numbers, + Bash does not recognize + fold, a filter to wrap lines of + text + Forking a child + process + for + loops + + Functions + + Arguments + passed referred to by position + Capturing + the return value of a function + using echo + Definition + must precede first call to function + Exit + status + + Local variables + and recursion + + Passing + an array to a + function + Passing pointers + to a function + Recursion + Redirecting + stdin + of a function + + + return + + + Returning an array from + a function + + return + range limits, workarounds + + + shift + arguments passed to a function + + + * * * + + getopt, + external command for parsing script + command-line arguments + + Emulated + in a script + + + getopts, + Bash builtin for parsing script + command-line arguments + + $OPTIND / + $OPTARG + + + Globbing, + filename expansion + -ge , + greater-than or equal + integer comparison test + -gt , + greater-than integer + comparison test + $GROUPS, + Groups user belongs to + + * * * + + Hashing, creating lookup keys + in a table + + Example + script + + + head, echo + to stdout lines at the beginning of a text + file + help, gives usage summary of + a Bash builtin + + + Here + documents + + + + + Anonymous + here documents, using : + Commenting out + blocks of code + Self-documenting + scripts + + bc in a here + document + + cat + scripts + Command + substitution + ex + scripts + Function, + supplying input to + + + Here + strings + Prepending text + Using + read + + + Limit + string + Closing limit + string may not be indented + Dash option + to limit string, + + Literal + text output, + for generating program code + + + Parameter + substitution + Disabling + parameter substitution + + + Passing + parameters + Temporary + files + Using + vi non-interactively + + + + $HOME, + user's home directory + $HOSTNAME, + system host name + + * * * + + + if [ condition ]; then ... + test construct + + + + if-grep, + if and grep + in combination + Fixup + for if-grep test + + + + + + $IFS, + Internal field separator variable + + Defaults to + whitespace + + + Integer comparison + operators + in, + keyword preceding + [list] in a for + loop + Initialization table, + /etc/inittab + Interactive script, test for + I/O redirection + + + Indirect referencing of variables + + New notation, introduced + in version 2 of Bash + + Example script + + + + Iteration + + * * * + + Job IDs, table + + jot, + Emit a sequence of integers. Equivalent to seq. + + Random sequence + generation + + + * * * + + Keywords + + kill, + terminate a process by process ID + + Options (, + ) + + + killall, + terminate a process by name + killall + script in /etc/rc.d/init.d + + * * * + + -le , + less-than or equal + integer comparison test + let, + setting and carrying out arithmetic operations on variables + Limit string, + in a here document + $LINENO, + variable indicating the line number where + it appears in a script + + Link, file + (using ln command) + + Invoking script with multiple names, + using ln + symbolic + links, ln -s + + + List constructs + + + And + list + Or + list + + + Local variables + + and recursion + + + Localization + + Logical operators + (&&, ||, + etc.) + Logout file, + the ~/.bash_logout file + + + Loops + + + break + loop control command + continue loop + control command + + + C-style + loop within double + parentheses + for loop + while loop + + + do (keyword), + begins execution of commands within a loop + done (keyword), + terminates a loop + + + for + loops + for arg + in [list]; + do + + Command + substitution to generate + [list] + Filename expansion + in [list] + Multiple parameters + in each [list] element + Omitting + [list], defaults to + positional parameters + Parameterizing + [list] + Redirection + + + in, + (keyword) preceding [list] in a + for loop + Nested + loops + Running a + loop in the background, + script example + + + Semicolon required, when do is on first line + of loop + for + loop + while + loop + + + until loop + until [ condition-is-true ]; do + + + while + loop + while [ condition ]; do + + Function call + inside test brackets + Multiple conditions + Omitting test + brackets + Redirection + + while read construct + + + Which type of loop to + use + + + + + Loopback devices + + In /dev directory + Mounting an ISO image + + + + -lt , + less-than integer + comparison test + + * * * + + m4, macro processing language + $MACHTYPE, + Machine type + Magic number, + marker at the head of a file indicating the file type + Makefile, + file containing the list of dependencies used by make command + + Modulo, arithmetic + remainder operator + + Application: Generating + prime numbers + + Mortgage calculations, + example script + + * * * + + -n + String not + null test + Named pipe, a temporary + FIFO buffer + + Example + script + + + nc, netcat, + a toolkit for TCP and UDP ports + -ne, + not-equal-to integer comparison test + Negation operator, + !, reverses the sense of a test + netstat, Network + statistics + nl, a filter to number lines of + text + Noclobber, + option to Bash to prevent overwriting + of files + null variable + assignment, avoiding + + * * * + + -o + Logical OR + compound comparison test + od, octal + dump + $OLDPWD + Previous working directory + + Operator + + Definition + of + Precedence + + + Options, + passed to shell or script on command line or by set command + Or + list + Or logical operator, + || + + * * * + + + + Parameter + substitution + + + + ${parameter+alt_value} + ${parameter:+alt_value} + Alternate value + of parameter, if set + + + ${parameter-default} + ${parameter:-default} + ${parameter=default} + ${parameter:=default} + Default + parameters + + ${!varprefix*} + ${!varprefix@} + Parameter + name match + + + ${parameter?err_msg} + Parameter-unset message + + + ${parameter} + Value of + parameter + + + Script + example + Table + of parameter + substitution + + + + + Parent / child process + problem, a child process cannot + export variables to a parent process + + + Parentheses + + Command + group + Enclose group + of Extended Regular + Expressions + Double parentheses, + in arithmetic expansion + + + + $PATH, + the path (location of system + binaries) + Perl, programming language + + Combined in the + same file with a Bash script + Embedded in a + Bash script + Using eval + with + + + PID, + process ID + + + Pipe, | , + a device for passing the output of a command to another command + or to the shell + + + Avoiding + unnecessary commands in a + pipe + Pipefail, + set -o pipefail + option to indicate exit status + within a pipe + $PIPESTATUS, + exit status of last executed + pipe + Piping output of a command + to a script + Redirecting + stdin, rather than using + cat in a + pipe + + + + Pitfalls + + + - + (dash) is not redirection + operator + // + (double forward slash), behavior of cd command toward + #!/bin/sh + script header disables extended Bash + features + Abuse of + cat + CGI + programming, using scripts for + Closing limit string + in a here document, + indenting + DOS-type newlines + (\r\n) crash a script + eval, risk of + using + Execute permission + lacking for commands within a script + Export + problem, child process + to parent process + Extended + Bash features not + available + Failing to + quote variables + within test brackets + GNU + command set, in cross-platform scripts + null + variable assignment + + Numerical and string + comparison operators not + equivalent + = + and -eq not + interchangeable + + Omitting + terminal semicolon, + in a curly-bracketed code block + + Piping + echo + to a loop + echo + to read + tail + to grep + + suid + commands inside a script + Undocumented + Bash features, + danger of + Uninitialized + variables + Variable names, + inappropriate + Variables in a + subshell, scope + limited + Whitespace, + misuse of + + + + + + + Portability issues + in shell scripting + + Setting path + and umask + Using whatis + + + + + Positional parameters + + + $@, + as separate words + $*, + as a single word + + + + POSIX, + Portable Operating System Interface / + UNIX + + + Character + classes + + + + $PPID, + process ID of parent process + Precedence, operator + Prepending + lines at head of a file, script + example + + + Prime numbers + + Generating primes + without using arrays + Sieve of + Eratosthenes + + + printf, + formatted print command + /proc directory + + Running processes, + files describing + Writing to + files in /proc, + warning + + + + Process + + Process + ID (PID) + + + + Process substitution + + To compare contents of + directories + To supply stdin of a + command + Template + + + Prompt + + + + $PS1, Main + prompt, seen at command + line + + $PS2, + Secondary prompt + + + + Pseudo-code, + as problem-solving method + $PWD, + Current working directory + + * * * + + Question mark, ? + + Character + match in an Extended Regular + Expression + Single-character + wild card, + in globbing + In a + C-style + Trinary operator + + + + Quoting + + + Character + string + + Variables + within test + brackets + + Whitespace, + using quoting to + preserve + + + + + * * * + + + Random numbers + + + + /dev/urandom + + + + rand(), + random function in awk + + $RANDOM, Bash + function that returns a pseudorandom integer + + Random sequence + generation, using date + command + Random sequence + generation, using jot + + Random string, + generating + + + + + + + + rcs + + + + read, set value of a + variable from stdin + + + Detecting + arrow keys + Options + Piping + output of cat + to read + Prepending + text + + Problems piping echo + to read + Redirection from a + file to read + $REPLY, + default read variable + Timed + input + + while read + construct + + + Recursion + + Local + variables + + + + + Redirection + + + Code + blocks + exec + <filename, + to reassign + file descriptors + Introductory-level + explanation of I/O + redirection + + Open a file for both + reading and writing + <>filename + + read + input redirected from a file + + + stderr to + stdout + 2>&1 + + stdin / + stdout, + using - + + stdinof a + function + + stdout to a file + > ... >> + + + + + stdout to + file descriptor + j + >&j + + + file descriptori to + file descriptor + j + i>&j + + + stdout + of a command to stderr + >&2 + + stdout + and stderr + of a command to a file + &> + + tee, redirect to a file + output of command(s) partway through a pipe + + + + + Reference Cards + + Miscellaneous + constructs + Parameter + substitution/expansion + Special shell + variables + String + operations + Test operators + Binary comparison + Files + + + + + + Regular + Expressions + + ^ (caret) + Beginning-of-line + + $ (dollar sign) + Anchor + + . (dot) + Match single + character + * (asterisk) + Any number of + characters + [ ] (brackets) Enclose character set + to match + \ (backslash) Escape, interpret following + character literally + \< ... \> + (angle brackets, escaped) + Word boundary + + Extended + REs + + + Character + match + \{ \} Escaped + curly brackets + [: :] POSIX character classes + + + + $REPLY, + Default value associated with read + command + Restricted shell, + shell (or script) with certain commands disabled + return, + command that terminates a function + + run-parts + + Running scripts + in sequence, without user intervention + + + * * * + + Scope of a variable, + definition + Script options, + set at command line + Scripting routines, + library of useful definitions and functions + Secondary prompt, + $PS2 + + Security issues + + nmap, + network mapper + / port scanner + sudo + suid + commands inside a script + Viruses, + trojans, and worms in scripts + Writing + secure scripts + + + + + sed, + pattern-based programming language + + Table, + basic operators + Table, + examples of operators + + + select, + construct for menu building + + in + list omitted + + + + Semicolon required, + when do + keyword is on first line of loop + + When + terminating curly-bracketed + code block + + + seq, + Emit a sequence of integers. Equivalent to jot. + + set, + Change value of internal script variables + + Shell script, + definition of + Shell wrapper, + script embedding a command or utility + shift, reassigning + positional parameters + $SHLVL, + shell level, depth to which the shell + (or script) is nested + shopt, + change shell options + Signal, + a message sent to a process + + Simulations + + Brownian + motion + Galton + board + Horserace + Life, + game of + PI, + approximating by firing cannonballs + Pushdown + stack + + + Single quotes + (' ... ') strong quoting + Socket, a communication + node associated with an I/O port + + Sorting + + Bubble + sort + Insertion + sort + + + source, + execute a script or, within a script, import a file + + Passing positional + parameters + + + Spam, dealing with + + Example + script + Example + script + Example + script + Example + script + + + Special characters + Stack, emulating a push-down, Example + script + Startup files, Bash + + stdin + and stdout + + + Strings + + + + =~ + String match operator + + + Comparison + Length + ${#string} + Manipulation + Manipulation, + using awk + + + Protecting strings + from expansion and/or reinterpretation, + script example + Unprotecting + strings, + script example + + + + Substring extraction + ${string:position} + ${string:position:length} + Using + expr + + + Substring + index (numerical position in + string) + Substring + matching, using + expr + + + Substring + removal + ${var#Pattern} + ${var##Pattern} + ${var%Pattern} + ${var%%Pattern} + + + + Substring replacement + ${string/substring/replacement} + ${string//substring/replacement} + ${string/#substring/replacement} + ${string/%substring/replacement} + + + Script + example + + + Table + of string/substring manipulation and + extraction operators + + + + + Strong quoting + ' ... ' + + Stylesheet + for writing scripts + + + Subshell + + Command list within + parentheses + Variables, + $BASH_SUBSHELL and + $SHLVL + + + Variables in a subshell + + scope + limited, but ... + + ... can be accessed outside + the subshell? + + + + + + + su Substitute + user, log on as a different user or as + root + suid (set user + id) file flag + + suid + commands inside a script, not advisable + + + Symbolic links + + Swapfiles + + * * * + + tail, echo + to stdout lines at the (tail) end of a text + file + tee, redirect to a file + output of command(s) partway through a pipe + + Terminals + + setserial + setterm + stty + wall + + + test command + + Bash + builtin + external + command, /usr/bin/test + (equivalent to /usr/bin/[) + + + Test constructs + + + Test operators + + + -a + Logical AND + compound comparison + -e + File exists + -eq + is-equal-to (integer + comparison) + -f + File is a regular + file + -ge + greater-than or equal + (integer comparison) + -gt + greater-than (integer + comparison) + -le + less-than or equal + (integer comparison) + -lt + less-than + (integer comparison) + -n + not-zero-length + (string comparison) + -ne + not-equal-to + (integer comparison) + -o + Logical OR + compound comparison + -u + suid + flag set, file test + -z + is-zero-length + (string comparison) + + = + is-equal-to + (string comparison) + == + is-equal-to + (string comparison) + < + less-than + (string comparison) + < + less-than, + (integer comparison, within + double parentheses) + + <= + less-than-or-equal, + (integer comparison, within + double parentheses) + + > + greater-than + (string comparison) + > + greater-than, + (integer comparison, within + double parentheses) + >= + greater-than-or-equal, + (integer comparison, within + double parentheses) + + || + Logical OR + && + Logical AND + + ! + Negation operator, inverts exit status of a + test + != + not-equal-to + (string comparison) + + + Tables of test + operators + Binary comparison + File + + + + + Timed input + + Using + read -t + Using + stty + Using + timing loop + Using + $TMOUT + + + + + Tips and hints + for Bash scripts + + + Array, as + return value from + a function + + + Comment blocks + Using anonymous + here documents + Using if-then + constructs + + + Comment headers, + special purpose + C-style syntax , + for handling variables + Double-spacing a text + file + Filter, + feeding output back to same + filter + Function + return value + workarounds + if-grep + test fixup + Library + of useful definitions and + functions + null + variable assignment, avoiding + Passing + an array to a + function + Prepending + lines at head of a file + Pseudo-code + Script as embedded + command + rcs + Running scripts in + sequence without user intervention, using run-parts + + Script portability + Setting path + and umask + Using whatis + + + + Setting script variable + to a block of embedded sed or + awk code + Subshell variable, + accessing outside the subshell + + Testing a variable + to see if it contains only digits + Tracking script usage + Widgets, invoking from a + script + + + + + $TMOUT, + Timeout interval + + tr, character translation filter + + DOS to Unix text file + conversion + Options + Soundex, example + script + Variants + + + Trap, + specifying an action upon receipt of a signal + Trinary operator, + C-style + true, + returns successful (0) exit status + typeset builtin + + options + + + * * * + + $UID, + User ID number + unalias, + to remove an alias + uname, + output system information + Uninitialized variables + uniq, + filter to remove duplicate lines from a sorted file + unset, + delete a shell variable + until loop + until [ condition-is-true ]; do + + * * * + + Variables + + + + Array operations on + + + Assignment + Script + example + Script + example + Script + example + + + Bash + internal variables + Block of sed or + awk code, setting a variable + to + + C-style + + increment/decrement/trinary operations + + Change value of internal script variables + using set + declare, + to restrict the properties of variables + Deleting a shell variable + using unset + Environmental + Expansion / Substring + replacement operators + + + Indirect + referencing + eval variable1=\$$variable2 + + Newer notation + ${!variable} + + + Length + ${#var} + lvalue + Manipulating and + expanding + Name + and value of a variable, + distinguishing between + null + variable assignment, avoiding + + Quoting + within test + brackets + to preserve + whitespace + + rvalue + Setting to null + value + In + subshell + not visible to parent shell + Testing a variable + if it contains only digits + Undeclared, + error message + Uninitialized + + Unsetting + Untyped + + + + * * * + + wait, + suspend script execution + + To remedy + script hang + + + + Weak quoting + " ... " + + + while loop + while [ condition ]; do + + + while read + construct + + + Whitespace, + spaces, tabs, and newline characters + + $IFS defaults + to + Inappropriate use + of + Preceding closing + limit string in a here + document, error + Preceding script + comments + Quoting, + to preserve whitespace within strings + or variables + + + who, information about logged on users + + w + whoami + logname + + + Widgets + + * * * + + xargs, + Filter for grouping arguments + + + Curly brackets + + Limiting arguments passed + Options + Processes arguments one at a time + + Whitespace, handling + + + * * * + + yes + + * * * + + -z + String is + null + Zombie, + a process that has terminated, but not yet been killed by its + parent diff --git a/LDP/guide/docbook/abs-guide/ascii.c b/LDP/guide/docbook/abs-guide/ascii.c new file mode 100644 index 00000000..0007423d --- /dev/null +++ b/LDP/guide/docbook/abs-guide/ascii.c @@ -0,0 +1,38 @@ +/*********************************************/ +/* ascii.c */ +/* Generate ASCII table */ +/* To build: gcc -O2 ascii.c -o ascii-table */ +/* */ +/* This utterly trivial program written by */ +/* Mendel Cooper, 04/07 */ +/* I'm not proud of it, but it does the job. */ +/* License: Public Domain */ +/*********************************************/ + +#include <stdio.h> + +#define MAX 255 /* FF hex */ +#define FILENAME "ASCII.txt" /* Outfile name */ + +int main() + { + int i; + FILE *fp; + + fp = fopen (FILENAME, "a" ); + + for( i = 1; i <= MAX; i++ ) { + fprintf( fp, "%5d ", i ); + fputc( i, fp ); + fprintf( fp, " " ); + if ( i % 5 == 0 ) + fprintf( fp, "\n" ); + } + + fprintf( fp, "\n" ); + + return (0); + } /* Outfile needs a bit of hand-editing for tidying up. */ + +/* Try rewriting this as a shell script. */ +/* Not so easy, huh? */ diff --git a/LDP/guide/docbook/abs-guide/brownian.sh b/LDP/guide/docbook/abs-guide/brownian.sh new file mode 100644 index 00000000..5328bd13 --- /dev/null +++ b/LDP/guide/docbook/abs-guide/brownian.sh @@ -0,0 +1,115 @@ +#!/bin/bash +# brownian.sh +# Author: Mendel Cooper +# Reldate: 10/26/07 +# License: GPL3 + +# ---------------------------------------------------------------- +# This script models Brownian motion: +#+ the random wanderings of tiny particles in a fluid, +#+ as they are impacted by random currents and collisions. +#+ This is also known as the "Drunkard's Walk." + +# It can also be considered as a highly simplified simulation of a +#+ Galton Board, a slanted board with a pattern of pegs, +#+ down which rolls a succession of marbles, one at a time. +#+ At the bottom is a row of slots or catch basins in which +#+ the marbles finally come to rest. +# Think of it as a kind of bare-bones Pachinko game. +# As you see by running the script, +#+ most of the marbles cluster around the center slot. +#+ This mirrors the expected "Normal Distribution." +# As a Galton Board simulation, this script +#+ disregards such parameters as +#+ board tilt-angle, rolling friction of the marbles, +#+ angles of impact, and elasticity of the pegs. +# How much of a difference does that make? +# ---------------------------------------------------------------- + +PASSES=500 # Number of particle interactions / marbles. +ROWS=10 # Number of "collisions" (or horizontal peg rows). +RANGE=3 # We want 0 - 2 output range from $RANDOM. +POS=0 # Left/right position. + +declare -a Slots # Array holding cumulative results of passes. +NUMSLOTS=21 # How many slots at bottom of board? + + +Initialize_Slots () { # Zero out all elements of array. +for i in $( seq $NUMSLOTS ) +do + Slots[$i]=0 +done + +echo # Blank line at beginning of run. + } + + +Show_Slots () { +echo -n " " +for i in $( seq $NUMSLOTS ) # Pretty-print array elements. +do + printf "%3d" ${Slots[$i]} # Three spaces per result. +done + +echo # Row of slots: +echo " |__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|" +echo " ^^" +echo # Note that if the count within any particular slot exceeds 99, + #+ it messes up the display. + # Running only(!) 500 passes usually avoids this. + } + + +Move () { # Move one unit right / left, or stay put. + Move=$RANDOM # How random is $RANDOM? Let's see. ... + let "Move %= RANGE" # Normalize into range of 0 - 2. + case "$Move" in + 0 ) ;; # Do nothing, i.e., stay in place. + 1 ) ((POS--));; # Left. + 2 ) ((POS++));; # Right. + * ) echo -n "Error ";; # Should never happen. + esac + } + + +Play () { # Single pass (inner loop). +i=0 +while [ $i -lt $ROWS ] # One event per row. +do + Move + ((i++)); +done + +SHIFT=11 # Why 11, and not 10? +let "POS += $SHIFT" # Shift "zero position" to center. +(( Slots[$POS]++ )) # DEBUG: echo $POS + } + + +Run () { # Outer loop. +p=0 +while [ $p -lt $PASSES ] +do + Play + (( p++ )) + POS=0 # Reset to zero. Why? +done + } + + +# -------------- +# main () +Initialize_Slots +Run +Show_Slots +# -------------- + +exit $? + +# Exercises: +# --------- +# 1) Show the results in a vertical bar graph, or as an alternative, +#+ a scattergram. +# 2) Alter the script to use /dev/urandom instead of $RANDOM. +# Does this make the results more random? diff --git a/LDP/guide/docbook/abs-guide/ex68a.sh b/LDP/guide/docbook/abs-guide/ex68a.sh new file mode 100644 index 00000000..bcd9e6b4 --- /dev/null +++ b/LDP/guide/docbook/abs-guide/ex68a.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Optimized Sieve of Eratosthenes +# Script by Jared Martin, with very minor changes by ABS Guide author. +# Used in ABS Guide with permission (thanks!). + +# Based on script in Advanced Bash Scripting Guide. +# http://tldp.org/LDP/abs/html/arrays.html#PRIMES0 (ex68.sh). + +# http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf (reference) +# Check results against http://primes.utm.edu/lists/small/1000.txt + +# Necessary but not sufficient would be, e.g., +# (($(sieve 7919 | wc -w) == 1000)) && echo "7919 is the 1000th prime" + +UPPER_LIMIT=${1:?"Need an upper limit of primes to search."} + +Primes=( '' $(seq ${UPPER_LIMIT}) ) + +typeset -i i t +Primes[i=1]='' # 1 is not a prime. +until (( ( i += 1 ) > (${UPPER_LIMIT}/i) )) # Need check only ith-way. + do # Why? + if ((${Primes[t=i*(i-1), i]})) + # Obscure, but instructive, use of numeric eval in subscript. + then + until (( ( t += i ) > ${UPPER_LIMIT} )) + do Primes[t]=; done + fi + done + +# echo ${Primes[*]} +echo # Change to original script for pretty-printing (80-col. display). +printf "%8d" ${Primes[*]} +echo; echo + +exit $? diff --git a/LDP/guide/docbook/abs-guide/from.sh b/LDP/guide/docbook/abs-guide/from.sh new file mode 100644 index 00000000..6d86ebcf --- /dev/null +++ b/LDP/guide/docbook/abs-guide/from.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# from.sh + +# Emulates the useful "from" utility in Solaris, BSD, etc. +# Echoes the "From" header line in all messages +#+ in your e-mail directory. + + +MAILDIR=~/mail/* # No quoting of variable. Why? +GREP_OPTS="-H -A 5 --color" # Show file, plus extra context lines + #+ and display "From" in color. +TARGETSTR="^From" # "From" at beginning of line. + +for file in $MAILDIR # No quoting of variable. +do + grep $GREP_OPTS "$TARGETSTR" "$file" + # ^^^^^^^^^^ # Again, do not quote this variable. + echo +done + +exit $? + +# Might wish to pipe the output of this script to 'more' or +#+ redirect it to a file . . . diff --git a/LDP/guide/docbook/abs-guide/insertion-sort.bash b/LDP/guide/docbook/abs-guide/insertion-sort.bash new file mode 100644 index 00000000..3e91353a --- /dev/null +++ b/LDP/guide/docbook/abs-guide/insertion-sort.bash @@ -0,0 +1,65 @@ +#!/bin/bash +# insertion-sort.bash: Insertion sort implementation in Bash +# Heavy use of Bash array features: +#+ (string) slicing, merging, etc +# URL: http://www.lugmen.org.ar/~jjo/jjotip/insertion-sort.bash.d +#+ /insertion-sort.bash.sh +# +# Author: JuanJo Ciarlante <jjo@irrigacion.gov.ar> +# Lightly reformatted by ABS Guide author. +# License: GPLv2 +# Used in ABS Guide with author's permission (thanks!). +# +# Test with: ./insertion-sort.bash -t +# Or: bash insertion-sort.bash -t +# The following *doesn't* work: +# sh insertion-sort.bash -t +# Why not? Hint: which Bash-specific features are disabled +#+ when running a script by 'sh script.sh'? +# +: ${DEBUG:=0} # Debug, override with: DEBUG=1 ./scriptname . . . +# Parameter substitution -- set DEBUG to 0 if not previously set. + +# Global array: "list" +typeset -a list +# Load whitespace-separated numbers from stdin. +if [ "$1" = "-t" ]; then +DEBUG=1 + read -a list < <( od -Ad -w24 -t u2 /dev/urandom ) # Random list. +# ^ ^ process substition +else + read -a list +fi +numelem=${#list[*]} + +# Shows the list, marking the element whose index is $1 +#+ by surrounding it with the two chars passed as $2. +# Whole line prefixed with $3. +showlist() + { + echo "$3"${list[@]:0:$1} ${2:0:1}${list[$1]}${2:1:1} ${list[@]:$1+1}; + } + +# Loop _pivot_ -- from second element to end of list. +for(( i=1; i<numelem; i++ )) do + ((DEBUG))&&showlist i "[]" " " + # From current _pivot_, back to first element. + for(( j=i; j; j-- )) do + # Search for the 1st elem. less than current "pivot" . . . + [[ "${list[j-1]}" -le "${list[i]}" ]] && break + done + (( i==j )) && continue ## No insertion was needed for this element. + # . . . Move list[i] (pivot) to the left of list[j]: + list=(${list[@]:0:j} ${list[i]} ${list[j]}\ + # {0,j-1} {i} {j} + ${list[@]:j+1:i-(j+1)} ${list[@]:i+1}) + # {j+1,i-1} {i+1,last} + ((DEBUG))&&showlist j "<>" "*" +done + + +echo +echo "------" +echo $'Result:\n'${list[@]} + +exit $? diff --git a/LDP/guide/docbook/abs-guide/opprec-table.sgml b/LDP/guide/docbook/abs-guide/opprec-table.sgml new file mode 100644 index 00000000..7bb89c6d --- /dev/null +++ b/LDP/guide/docbook/abs-guide/opprec-table.sgml @@ -0,0 +1,177 @@ + + Operator Precedence + + + + Operator + Meaning + Comments + + + + + + + HIGHEST PRECEDENCE + + + + post-increment, post-decrement + C-style operators + + + + pre-increment, pre-decrement + + + + + + + + + + negation + logical / bitwise, inverts sense of following + operator + + + + + + + + + exponentiation + arithmetic + operation + + + + multiplication, division, modulo + arithmetic operation + + + + addition, subtraction + arithmetic operation + + + + + + + + + left, right shift + bitwise + + + + + + + + + unary comparison + string is/is-not null + + + + unary comparison + files + + + + compound comparison + string and integer + + + + compound comparison + files + + + + equality / inequality + test operators, string and integer + + + + + + + + + AND + bitwise + + + + XOR + exclusive OR, bitwise + + + + OR + bitwise + + + + + + + + + AND + logical, compound + comparison + + + + OR + logical, compound + comparison + + + + + + + + + trinary + operator + C-style + + + + assignment + (do not confuse with equality + test) + + + + combination + assignment + times-equal, divide-equal, mod-equal, etc. + + + + + + + + + comma + links a sequence of operations + + + + + LOWEST PRECEDENCE + + + +
diff --git a/LDP/guide/docbook/abs-guide/rand-string.sh b/LDP/guide/docbook/abs-guide/rand-string.sh new file mode 100644 index 00000000..2d443834 --- /dev/null +++ b/LDP/guide/docbook/abs-guide/rand-string.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# rand-string.sh +# Generating an 8-character "random" string. + +if [ "-n $1" ] # If command line argument present, +then #+ then set start-string to it. + str0="$1" +else # Else use PID of script as start-string. + str0="$$" +fi + +POS=2 # Starting from position 2 in the string. +LEN=8 # Extract eight characters. + +str1=$( echo "$str0" | md5sum | md5sum ) +# Doubly scramble: ^^^^^^ ^^^^^^ + +randstring="${str1:$POS:$LEN}" +# Can parameterize ^^^^ ^^^^ + +echo "$randstring" + +exit $? + +# bozo$ ./rand-string.sh my-password +# 1bdd88c4 + +# No, this is is not recommended +#+ as a method of generating hack-proof passwords. diff --git a/LDP/guide/docbook/abs-guide/splitcopy.sh b/LDP/guide/docbook/abs-guide/splitcopy.sh new file mode 100644 index 00000000..74c60fb4 --- /dev/null +++ b/LDP/guide/docbook/abs-guide/splitcopy.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# splitcopy.sh + +# A script that splits itself into chunks, +#+ then reassembles the chunks into an exact copy +#+ of the original script. + +CHUNKSIZE=4 # Size of first chunk of split files. +OUTPREFIX=xx # csplit prefixes, by default, + #+ files with "xx" ... + +csplit "$0" "$CHUNKSIZE" + +# Some comment lines for padding . . . +# Line 15 +# Line 16 +# Line 17 +# Line 18 +# Line 19 +# Line 20 + +cat "$OUTPREFIX"* > "$0.copy" # Concatenate the chunks. +rm "$OUTPREFIX"* # Get rid of the chunks. + +exit $?