Advanced Bash-Scripting Guide (INDEX )

Index

   This index / glossary / quick-reference lists many of the important
   topics covered in the text. Terms are arranged in approximate ASCII
   sorting order, modified as necessary for enhanced clarity.

   Note that commands are indexed in Part 4.

   * * *

   ^ (caret)

     * Beginning-of-line, in a Regular Expression
     * ^
       ^^
       Uppercase conversion in parameter substitution

   ~ 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
     * ;;& ;& Terminators in a case option (version 4+ of Bash).

   : 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

     * Double-quoting the backslash (\) character

   ,

     * Comma operator
     * ,
       ,,
       Lowercase conversion in parameter substitution

   () 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

   $[ ... ] Integer expansion (deprecated)

   ${ ... } 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
     * ${!#}
       Final positional parameter. (This is an indirect reference to
       $#.)
     * ${!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

   $' ... ' String expansion, using escaped characters.

   \ 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
     * ** Extended globbing file-match 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

   Address database, script example

   Advanced Bash Scripting Guide, where to download

   Alias

     * Removing an alias, using unalias

   Anagramming

   And list

     * To supply default command-line argument

   And logical operator &&

   Angle brackets, escaped, \< . . . \> word boundary in a Regular
   Expression

   Anonymous here document, using :

   Archiving

     * rpm
     * tar

   Arithmetic expansion

     * variations of

   Arithmetic operators

     * combination operators, C-style
       += -= *= /= %=

       Note

   In certain contexts, += can also function as a string concatenation
   operator.

   Arrays

     * Associative 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

   Arrow keys, detecting

   ASCII

     * Definition
     * Script to generate ASCII table

   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
     * Version 4
       Version 4.1
       Version 4.2

   .bashrc

   $BASH_SUBSHELL

   Basic commands, external

   Batch files, DOS

   Batch processing

   bc, calculator utility

     * In a here document
     * Template for calculating a script variable

   Bibliography

   Bison utility

   Bitwise operators

     * Example script

   Block devices

     * testing for

   Blocks of code

     * Redirection
       Script example: redirecting output of a a code block

   Brace expansion

     * Extended, {a..z}
     * With increment and zero-padding (new feature in Bash, version 4)

   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

   Character devices

     * testing for

   Checksum

   Child processes

   Colon, : , equivalent to the true Bash builtin

   Colorizing scripts

     * Cycling through the background colors, example script
     * Table of color escape sequences
     * Template, colored text on colored background

   Comma operator, linking commands or operations

   Command-line options

   command_not_found_handle () builtin error-handling function (version
   4+ of Bash)

   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

   Communications and hosts

   Compound comparison operators

   Compression utilities

     * bzip2
     * compress
     * gzip
     * zip

   continue loop control command

   Control characters

     * Control-C, break
     * Control-D, terminate / log out / erase
     * Control-G, BEL (beep)
     * Control-H, rubout
     * Control-J, newline
     * Control-M, carriage return

   Coprocesses

   cron, scheduling daemon

   C-style syntax , for handling variables

   Crossword puzzle solver

   Curly brackets {}

     * in find command
     * in an Extended Regular Expression
     * in xargs

   * * *

   Daemons, in UNIX-type OS

   date

   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
       case-modification options (version 4+ of Bash)

   Default parameters

   /dev directory

     * /dev/null pseudo-device file
     * /dev/urandom pseudo-device file, generating pseudorandom numbers
       with
     * /dev/zero, pseudo-device file

   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

     * and evaluation of octal/hex constants

   Double parentheses (( ... )) arithmetic expansion/evaluation
   construct

   Double quotes " ... " weak quoting

     * Double-quoting the backslash (\) character

   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

   else

   Encrypting files, using openssl

   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

     * Within $' ... ' string expansion
     * Used with Unicode characters

   /etc/fstab (filesystem mount) file

   /etc/passwd (user account) file

   $EUID, Effective user ID

   eval, Combine and evaluate expression(s), with variable expansion

     * Effects of, Example script
     * Forces reevaluation of arguments
     * And indirect references
     * Risk of using
     * Using eval to select among variables

   Evaluation of octal/hex constants within [[ ... ]]

   exec command, using in redirection

   Exercises

   Exit and Exit status

     * exit command
     * Exit status (exit code, return status of a command)
       Table, Exit codes with special meanings
       Anomalous
       Out of range
       Pipe exit status
       Specified by a function return
       Successful, 0
       /usr/include/sysexits.h, system file listing C/C++ standard exit
       codes

   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

   * * *

   factor, decomposes an integer into its prime factors

     * Application: Generating prime numbers

   false, returns unsuccessful (1) exit status

   Field, a group of characters that comprises an item of data

   Files / Archiving

   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

   File encryption

   find

     * {} Curly brackets
     * \; Escaped semicolon

   Filter

     * Using - with file-processing utility as a filter
     * Feeding output of a filter 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
     * Positional parameters
     * Recursion
     * Redirecting stdin of a function
     * return
       Multiple return values from a function, example script
       Returning an array from a function
       return range limits, workarounds
     * shift arguments passed to a function

   * * *

   Games and amusements

     * Anagrams
     * Anagrams, again
     * Crossword puzzle solver
     * Crypto-Quotes
     * Dealing a deck of cards
     * Fifteen Puzzle
     * Horse race
     * Knight's Tour
     * "Life" game
     * Magic Squares
     * Music-playing script
     * Nim
     * Pachinko
     * Perquackey
     * Petals Around the Rose
     * Podcasting
     * Poem
     * Towers of Hanoi
       Graphic version
       Alternate graphic version

   getopt, external command for parsing script command-line arguments

     * Emulated in a script

   getopts, Bash builtin for parsing script command-line arguments

     * $OPTIND / $OPTARG

   Global variable

   Globbing, filename expansion

     * Wild cards
     * Will not match dot files

   Golden Ratio (Phi)

   -ge , greater-than or equal integer comparison test

   -gt , greater-than integer comparison test

   groff, text markup and formatting language

   $GROUPS, Groups user belongs to

   gzip, compression utility

   * * *

   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
       Calculating the Golden Ratio
       Prepending text
       Using read
     * Limit string
       ! as a limit string
       Closing limit string may not be indented
       Dash option to limit string, <<-LimitString
     * Literal text output, for generating program code
     * Parameter substitution
       Disabling parameter substitution
     * Passing parameters
     * Temporary files
     * Using vi non-interactively

   History commands

   $HOME, user's home directory

   Homework assignment solver

   $HOSTNAME, system host name

   * * *

   $Id parameter, in rcs (Revision Control System)

   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

   Inline group, i.e., code block

   Interactive script, test for

   I/O redirection

   Indirect referencing of variables

     * New notation, introduced in version 2 of Bash ( example script)

   iptables, packet filtering and firewall utility

     * Usage example
     * 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 (-l, -9)

   killall, terminate a process by name

   killall script in /etc/rc.d/init.d

   * * *

   lastpipe shell option

   -le , less-than or equal integer comparison test

   let, setting and carrying out arithmetic operations on variables

     * C-style increment and decrement operators

   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

   Loopback device, mounting a file on a block device

   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

   man, manual page (lookup)

     * Man page editor (script)

   mapfile builtin, loads an array with a text file

   Math commands

   Meta-meaning

   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

   Network programming

   nl, a filter to number lines of text

   Noclobber, -C option to Bash to prevent overwriting of files

   NOT logical operator, !

   null variable assignment, avoiding

   * * *

   -o Logical OR compound comparison test

   octal, base-8 numbers

   od, octal dump

   $OLDPWD Previous working directory

   openssl encryption utility

   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
     * Case modification (version 4+ of Bash).
     * 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)

     * Appending directories to $PATH using the += operator.

   Perl, programming language

     * Combined in the same file with a Bash script
     * Embedded in a Bash script

   Perquackey-type anagramming game (Quackey script)

   Petals Around the Rose

   PID, Process ID, an identification number assigned to a running
   process.

   Pipe, | , a device for passing the output of a command to another
   command or to the shell

     * Avoiding unnecessary commands in a pipe
     * Comments embedded within
     * Exit status of 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
     * Double-quoting the backslash (\) character
     * eval, risk of using
     * Execute permission lacking for commands within a script
     * Exit status, anomalous
     * 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
     * let misuse: attempting to set string variables
     * Multiple echo statements in a function whose output is captured
     * 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 (however, this problem can be circumvented)
       tail -f to grep
     * Preserving whitespace within a variable, unintended consequences
     * suid commands inside a script
     * Undocumented Bash features, danger of
     * Uninitialized variables
     * Variable names, inappropriate
     * Variables in a subshell, scope limited
     * Subshell in while-read loop
     * Whitespace, misuse of

   Pointers

     * and file descriptors
     * and functions
     * and indirect references
     * and variables

   Portability issues in shell scripting

     * Setting path and umask
     * A test suite script (Bash versus classic Bourne shell)
     * Using whatis

   Positional parameters

     * $@, as separate words
     * $*, as a single word
     * in functions

   POSIX, Portable Operating System Interface / UNIX

     * --posix option
     * 1003.2 standard
     * Character classes

   $PPID, process ID of parent process

   Precedence, operator

   Prepending lines at head of a file, script example

   Prime numbers

     * Generating primes using the factor command
     * Generating primes using the modulo operator
     * Sieve of Eratosthenes, example script

   printf, formatted print command

   /proc directory

     * Running processes, files describing
     * Writing to files in /proc, warning

   Process

     * Child process
     * Parent process
     * Process ID (PID)

   Process substitution

     * To compare contents of directories
     * To supply stdin of a command
     * Template
     * while-read loop without a subshell

   Programmable completion (tab expansion)

   Prompt

     * $PS1, Main prompt, seen at command line
     * $PS2, Secondary prompt

   Pseudo-code, as problem-solving method

   $PWD, Current working directory

   * * *

   Quackey, a Perquackey-type anagramming game (script)

   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

   readline library

   Recursion

     * Demonstration of
     * Factorial
     * Fibonacci sequence
     * Local variables
     * Script calling itself recursively
     * Towers of Hanoi

   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

   Semaphore

   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

     * Definition
     * Emulating a push-down stack, example script

   Standard Deviation, example script

   Startup files, Bash

   stdin and stdout

   Stopwatch, example script

   Strings

     * =~ String match operator
     * Comparison
     * Length
       ${#string}
     * Manipulation
     * Manipulation, using awk
     * Null string, testing for
     * Protecting strings from expansion and/or reinterpretation, script
       example
       Unprotecting strings, script example
     * strchr(), equivalent of
     * strlen(), equivalent of
     * strings command, find printable strings in a binary or data file
     * 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

   * * *

   Tab completion

   Table lookup, script example

   tail, echo to stdout lines at the (tail) end of a text file

   tar, archiving utility

   tee, redirect to a file output of command(s) partway through a pipe

   Terminals

     * setserial
     * setterm
     * stty
     * tput
     * 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

   Text and text file processing

   Time / Date

   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
     * Capturing the return value of a function, using echo
     * CGI programming, using scripts for
     * Comment blocks
       Using anonymous here documents
       Using if-then constructs
     * Comment headers, special purpose
     * C-style syntax , for manipulating variables
     * Double-spacing a text file
     * Filenames prefixed with a dash, removing
     * 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
     * $PATH, appending to, using the += operator.
     * Prepending lines at head of a file
     * Progress bar template
     * Pseudo-code
     * rcs
     * Redirecting a test to /dev/null to suppress output
     * Running scripts in sequence without user intervention, using
       run-parts
     * Script as embedded command
     * 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
     * Testing whether a command exists, using type
     * Tracking script usage
     * while-read loop without a subshell
     * Widgets, invoking from a script

   $TMOUT, Timeout interval

   Token, a symbol that may expand to a keyword or command

   tput, terminal-control command

   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, var>10?88:99

     * in double-parentheses construct
     * in let construct

   true, returns successful (0) exit status

   typeset builtin

     * options

   * * *

   $UID, User ID number

   unalias, to remove an alias

   uname, output system information

   Unicode, encoding standard for representing letters and symbols

   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 modify the properties of variables
     * Deleting a shell variable using unset
     * Environmental
     * Expansion / Substring replacement operators
     * Indirect referencing
       eval variable1=\$$variable2
       Newer notation
       ${!variable}
     * Integer
     * Integer / string (variables are untyped)
     * Length
       ${#var}
     * Lvalue
     * Manipulating and expanding
     * Name and value of a variable, distinguishing between
     * Null string, testing for
     * 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
     * Typing, restricting the properties of a variable
     * Undeclared, error message
     * Uninitialized
     * Unquoted variable, splitting
     * Unsetting
     * Untyped

   * * *

   wait, suspend script execution

     * To remedy script hang

   Weak quoting " ... "

   while loop

   while [ condition ]; do

     * C-style syntax
     * Calling a function within test brackets
     * Multiple conditions
     * Omitting test brackets
     * while read construct
       Avoiding a subshell

   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
     * [:space:], POSIX character class

   who, information about logged on users

     * w
     * whoami
     * logname

   Widgets

   Wild card characters

     * Asterisk *
     * In [list] constructs
     * Question mark ?
     * Will not match dot files

   Word splitting

     * Definition
     * Resulting from command substitution

   Wrapper, shell

   * * *

   xargs, Filter for grouping arguments

     * Curly brackets
     * Limiting arguments passed
     * Options
     * Processes arguments one at a time
     * Whitespace, handling

   * * *

   yes

     * Emulation

   * * *

   -z String is null

   Zombie, a process that has terminated, but not yet been killed by its
   parent

  Notes

   [1]

   These are referred to as builtins, features internal to the shell.
   [2]

   Although recursion is possible in a shell script, it tends to be slow
   and its implementation is often an ugly kludge.
   [3]

   Many of the features of ksh88, and even a few from the updated ksh93
   have been merged into Bash.
   [4]

   By convention, user-written shell scripts that are Bourne shell
   compliant generally take a name with a .sh extension. System scripts,
   such as those found in /etc/rc.d, do not conform to this
   nomenclature.
   [5]

   Also seen in the literature as she-bang or sh-bang. This derives from
   the concatenation of the tokens sharp (#) and bang (!).
   [6]

   Some flavors of UNIX (those based on 4.2 BSD) allegedly take a
   four-byte magic number, requiring a blank after the ! -- #! /bin/sh.
   [http://www.in-ulm.de/~mascheck/various/shebang/#details] According
   to Sven Mascheck this is probably a myth.
   [7]

   The #! line in a shell script will be the first thing the command
   interpreter (sh or bash) sees. Since this line begins with a #, it
   will be correctly interpreted as a comment when the command
   interpreter finally executes the script. The line has already served
   its purpose - calling the command interpreter.

   If, in fact, the script includes an extra #! line, then bash will
   interpret it as a comment.
#!/bin/bash

echo "Part 1 of script."
a=1

#!/bin/bash
# This does *not* launch a new script.

echo "Part 2 of script."
echo $a  # Value of $a stays at 1.

   [8]

   This allows some cute tricks.

#!/bin/rm
# Self-deleting script.

# Nothing much seems to happen when you run this... except that the file disap
pears.

WHATEVER=85

echo "This line will never print (betcha!)."

exit $WHATEVER  # Doesn't matter. The script will not exit here.
                # Try an echo $? after script termination.
                # You'll get a 0, not a 85.

   Also, try starting a README file with a #!/bin/more, and making it
   executable. The result is a self-listing documentation file. (A here
   document using cat is possibly a better alternative -- see Example
   19-3).
   [9]

   Portable Operating System Interface, an attempt to standardize
   UNIX-like OSes. The POSIX specifications are listed on the Open Group
   site.
   [10]

   To avoid this possibility, a script may begin with a #!/bin/env bash
   sha-bang line. This may be useful on UNIX machines where bash is not
   located in /bin
   [11]

   If Bash is your default shell, then the #! isn't necessary at the
   beginning of a script. However, if launching a script from a
   different shell, such as tcsh, then you will need the #!.
   [12]

   Caution: invoking a Bash script by sh scriptname turns off
   Bash-specific extensions, and the script may therefore fail to
   execute.
   [13]

   A script needs read, as well as execute permission for it to run,
   since the shell needs to be able to read it.
   [14]

   Why not simply invoke the script with scriptname? If the directory
   you are in ($PWD) is where scriptname is located, why doesn't this
   work? This fails because, for security reasons, the current directory
   (./) is not by default included in a user's $PATH. It is therefore
   necessary to explicitly invoke the script in the current directory
   with a ./scriptname.
   [15]

   An operator is an agent that carries out an operation. Some examples
   are the common arithmetic operators, + - * /. In Bash, there is some
   overlap between the concepts of operator and keyword.
   [16]

   American Standard Code for Information Interchange. This is a system
   for encoding text characters (alphabetic, numeric, and a limited set
   of symbols) as numbers that can be stored and manipulated by
   computers. Many of the ASCII characters are represented on a standard
   keyboard.
   [17]

   A PID, or process ID, is a number assigned to a running process. The
   PIDs of running processes may be viewed with a ps command.

   Definition: A process is a currently executing command (or program),
   sometimes referred to as a job.
   [18]

   The shell does the brace expansion. The command itself acts upon the
   result of the expansion.
   [19]

   Exception: a code block in braces as part of a pipe may run as a
   subshell.

ls | { read firstline; read secondline; }
#  Error. The code block in braces runs as a subshell,
#+ so the output of "ls" cannot be passed to variables within the block.
echo "First line is $firstline; second line is $secondline"  # Won't work.

# Thanks, S.C.

   [20]

   Even as in olden times a philtre denoted a potion alleged to have
   magical transformative powers, so does a UNIX filter transform its
   target in (roughly) analogous fashion. (The coder who comes up with a
   "love philtre" that runs on a Linux machine will likely win accolades
   and honors.)
   [21]

   Bash stores a list of commands previously issued from the
   command-line in a buffer, or memory space, for recall with the
   builtin history commands.
   [22]

   A linefeed (newline) is also a whitespace character. This explains
   why a blank line, consisting only of a linefeed, is considered
   whitespace.
   [23]

   Technically, the name of a variable is called an lvalue, meaning that
   it appears on the left side of an assignment statment, as in
   VARIABLE=23. A variable's value is an rvalue, meaning that it appears
   on the right side of an assignment statement, as in VAR2=$VARIABLE.

   A variable's name is, in fact, a reference, a pointer to the memory
   location(s) where the actual data associated with that variable is
   kept.
   [24]

   Note that functions also take positional parameters.
   [25]

   The process calling the script sets the $0 parameter. By convention,
   this parameter is the name of the script. See the manpage (manual
   page) for execv.

   From the command-line, however, $0 is the name of the shell.
bash$ echo $0
bash

tcsh% echo $0
tcsh

   [26]

   If the the script is sourced or symlinked, then this will not work.
   It is safer to check $BASH_Source.
   [27]

   Unless there is a file named first in the current working directory.
   Yet another reason to quote. (Thank you, Harald Koenig, for pointing
   this out.
   [28]

   Encapsulating "!" within double quotes gives an error when used from
   the command line. This is interpreted as a history command. Within a
   script, though, this problem does not occur, since the Bash history
   mechanism is disabled then.

   Of more concern is the apparently inconsistent behavior of \ within
   double quotes, and especially following an echo -e command.

bash$ echo hello\!
hello!
bash$ echo "hello\!"
hello\!


bash$ echo \
>
bash$ echo "\"
>
bash$ echo \a
a
bash$ echo "\a"
\a


bash$ echo x\ty
xty
bash$ echo "x\ty"
x\ty

bash$ echo -e x\ty
xty
bash$ echo -e "x\ty"
x       y

   Double quotes following an echo sometimes escape \. Moreover, the -e
   option to echo causes the "\t" to be interpreted as a tab.

   (Thank you, Wayne Pollock, for pointing this out, and Geoff Lee and
   Daniel Barclay for explaining it.)
   [29]

   "Word splitting," in this context, means dividing a character string
   into separate and discrete arguments.
   [30]

   In those instances when there is no return terminating the function.
   [31]

   A token is a symbol or short string with a special meaning attached
   to it (a meta-meaning). In Bash, certain tokens, such as [ and .
   (dot-command), may expand to keywords and commands.
   [32]

   Per the 1913 edition of Webster's Dictionary:
Deprecate
...

To pray against, as an evil;
to seek to avert by prayer;
to desire the removal of;
to seek deliverance from;
to express deep regret for;
to disapprove of strongly.

   [33]

   Be aware that suid binaries may open security holes. The suid flag
   has no effect on shell scripts.
   [34]

   On Linux systems, the sticky bit is no longer used for files, only on
   directories.
   [35]

   As S.C. points out, in a compound test, even quoting the string
   variable might not suffice. [ -n "$string" -o "$a" = "$b" ] may cause
   an error with some versions of Bash if $string is empty. The safe way
   is to append an extra character to possibly empty variables, [
   "x$string" != x -o "x$a" = "x$b" ] (the "x's" cancel out).
   [36]

   In a different context, += can serve as a string concatenation
   operator. This can be useful for modifying environmental variables.
   [37]

   Side effects are, of course, unintended -- and usually undesirable --
   consequences.
   [38]

   Precedence, in this context, has approximately the same meaning as
   priority
   [39]

   A stack register is a set of consecutive memory locations, such that
   the values stored (pushed) are retrieved (popped) in reverse order.
   The last value stored is the first retrieved. This is sometimes
   called a LIFO (last-in-first-out) or pushdown stack.
   [40]

   The PID of the currently running script is $$, of course.
   [41]

   Somewhat analogous to recursion, in this context nesting refers to a
   pattern embedded within a larger pattern. One of the definitions of
   nest, according to the 1913 edition of Webster's Dictionary,
   illustrates this beautifully: "A collection of boxes, cases, or the
   like, of graduated size, each put within the one next larger."
   [42]

   The words "argument" and "parameter" are often used interchangeably.
   In the context of this document, they have the same precise meaning:
   a variable passed to a script or function.
   [43]

   Within a script, inside a subshell, $$ returns the PID of the script,
   not the subshell.
   [44]

   In this context, typing a variable means to classify it and restrict
   its properties. For example, a variable declared or typed as an
   integer is no longer available for string operations.

declare -i intvar

intvar=23
echo "$intvar"   # 23
intvar=stringval
echo "$intvar"   # 0

   [45]

   True "randomness," insofar as it exists at all, can only be found in
   certain incompletely understood natural phenomena, such as
   radioactive decay. Computers only simulate randomness, and
   computer-generated sequences of "random" numbers are therefore
   referred to as pseudorandom.
   [46]

   The seed of a computer-generated pseudorandom number series can be
   considered an identification label. For example, think of the
   pseudorandom series with a seed of 23 as Series #23.

   A property of a pseurandom number series is the length of the cycle
   before it starts repeating itself. A good pseurandom generator will
   produce series with very long cycles.
   [47]

   This applies to either command-line arguments or parameters passed to
   a function.
   [48]

   Note that $substring and $replacement may refer to either literal
   strings or variables, depending on context. See the first usage
   example.
   [49]

   If $parameter is null in a non-interactive script, it will terminate
   with a 127 exit status (the Bash error code for "command not found").
   [50]

   Iteration: Repeated execution of a command or group of commands,
   usually -- but not always, while a given condition holds, or until a
   given condition is met.
   [51]

   These are shell builtins, whereas other loop commands, such as while
   and case, are keywords.
   [52]

   For purposes of command substitution, a command may be an external
   system command, an internal scripting builtin, or even a script
   function.
   [53]

   In a more technically correct sense, command substitution extracts
   the stdout of a command, then assigns it to a variable using the =
   operator.
   [54]

   In fact, nesting with backticks is also possible, but only by
   escaping the inner backticks, as John Default points out.
   word_count=` wc -w \`echo * | awk '{print $8}'\` `

   [55]

   As Nathan Coulter points out, "while forking a process is a low-cost
   operation, executing a new program in the newly-forked child process
   adds more overhead."
   [56]

   An exception to this is the time command, listed in the official Bash
   documentation as a keyword ("reserved word").
   [57]

   Note that let cannot be used for setting string variables.
   [58]

   To Export information is to make it available in a more general
   context. See also scope.
   [59]

   An option is an argument that acts as a flag, switching script
   behaviors on or off. The argument associated with a particular option
   indicates the behavior that the option (flag) switches on or off.
   [60]

   Technically, an exit only terminates the process (or shell) in which
   it is running, not the parent process.
   [61]

   Unless the exec is used to reassign file descriptors.
   [62]

   Hashing is a method of creating lookup keys for data stored in a
   table. The data items themselves are "scrambled" to create keys,
   using one of a number of simple mathematical algorithms (methods, or
   recipes).

   An advantage of hashing is that it is fast. A disadvantage is that
   collisions -- where a single key maps to more than one data item --
   are possible.

   For examples of hashing see Example A-20 and Example A-21.
   [63]

   The readline library is what Bash uses for reading input in an
   interactive shell.
   [64]

   This only applies to child processes, of course.
   [65]

   The C source for a number of loadable builtins is typically found in
   the /usr/share/doc/bash-?.??/functions directory.

   Note that the -f option to enable is not portable to all systems.
   [66]

   The same effect as autoload can be achieved with typeset -fu.
   [67]

   Dotfiles are files whose names begin with a dot, such as
   ~/.Xdefaults. Such filenames do not appear in a normal ls listing
   (although an ls -a will show them), and they cannot be deleted by an
   accidental rm -rf *. Dotfiles are generally used as setup and
   configuration files in a user's home directory.
   [68]

   This particular feature may not yet be implemented in the version of
   the ext2/ext3 filesystem installed on your system. Check the
   documentation for your Linux distro.
   [69]

   And even when xargs is not strictly necessary, it can speed up
   execution of a command involving batch-processing of multiple files.
   [70]

   This is only true of the GNU version of tr, not the generic version
   often found on commercial UNIX systems.
   [71]

   An archive, in the sense discussed here, is simply a set of related
   files stored in a single location.
   [72]

   A tar czvf ArchiveName.tar.gz * will include dotfiles in
   subdirectories below the current working directory. This is an
   undocumented GNU tar "feature."
   [73]

   The checksum may be expressed as a hexadecimal number, or to some
   other base.
   [74]

   For even better security, use the sha256sum, sha512, and sha1pass
   commands.
   [75]

   This is a symmetric block cipher, used to encrypt files on a single
   system or local network, as opposed to the public key cipher class,
   of which pgp is a well-known example.
   [76]

   Creates a temporary directory when invoked with the -d option.
   [77]

   A daemon is a background process not attached to a terminal session.
   Daemons perform designated services either at specified times or
   explicitly triggered by certain events.

   The word "daemon" means ghost in Greek, and there is certainly
   something mysterious, almost supernatural, about the way UNIX daemons
   wander about behind the scenes, silently carrying out their appointed
   tasks.
   [78]

   This is actually a script adapted from the Debian Linux distribution.
   [79]

   The print queue is the group of jobs "waiting in line" to be printed.
   [80]

   For an excellent overview of this topic, see Andy Vaught's article,
   Introduction to Named Pipes, in the September, 1997 issue of Linux
   Journal.
   [81]

   EBCDIC (pronounced "ebb-sid-ick") is an acronym for Extended Binary
   Coded Decimal Interchange Code. This is an IBM data format no longer
   in much use. A bizarre application of the conv=ebcdic option of dd is
   as a quick 'n easy, but not very secure text file encoder.
cat $file | dd conv=swab,ebcdic > $file_encrypted
# Encode (looks like gibberish).
# Might as well switch bytes (swab), too, for a little extra obscurity.

cat $file_encrypted | dd conv=swab,ascii > $file_plaintext
# Decode.

   [82]

   A macro is a symbolic constant that expands into a command string or
   a set of operations on parameters. Simply put, it's a shortcut or
   abbreviation.
   [83]

   This is the case on a Linux machine or a UNIX system with disk
   quotas.
   [84]

   The userdel command will fail if the particular user being deleted is
   still logged on.
   [85]

   For more detail on burning CDRs, see Alex Withers' article, Creating
   CDs, in the October, 1999 issue of Linux Journal.
   [86]

   The -c option to mke2fs also invokes a check for bad blocks.
   [87]

   Since only root has write permission in the /var/lock directory, a
   user script cannot set a lock file there.
   [88]

   Operators of single-user Linux systems generally prefer something
   simpler for backups, such as tar.
   [89]

   As of the version 4 update of Bash, the -f and -c options take a
   block size of 512 when in POSIX mode. Additionally, there are two new
   options: -b for socket buffer size, and -T for the limit on the
   number of threads.
   [90]

   NAND is the logical not-and operator. Its effect is somewhat similar
   to subtraction.
   [91]

   In Bash and other Bourne shell derivatives, it is possible to set
   variables in a single command's environment.
var1=value1 var2=value2 commandXXX
# $var1 and $var2 set in the environment of 'commandXXX' only.

   [92]

   The killall system script should not be confused with the killall
   command in /usr/bin.
   [93]

   A meta-meaning is the meaning of a term or expression on a higher
   level of abstraction. For example, the literal meaning of regular
   expression is an ordinary expression that conforms to accepted usage.
   The meta-meaning is drastically different, as discussed at length in
   this chapter.
   [94]

   Since sed, awk, and grep process single lines, there will usually not
   be a newline to match. In those cases where there is a newline in a
   multiple line expression, the dot will match the newline.
#!/bin/bash

sed -e 'N;s/.*/[&]/' << EOF   # Here Document
line1
line2
EOF
# OUTPUT:
# [line1
# line2]



echo

awk '{ $0=$1 "\n" $2; if (/line.1/) {print}}' << EOF
line 1
line 2
EOF
# OUTPUT:
# line
# 1


# Thanks, S.C.

exit 0

   [95]

   Filename expansion means expanding filename patterns or templates
   containing special characters. For example, example.??? might expand
   to example.001 and/or example.txt.
   [96]

   A wild card character, analogous to a wild card in poker, can
   represent (almost) any other character.
   [97]

   Filename expansion can match dotfiles, but only if the pattern
   explicitly includes the dot as a literal character.
~/[.]bashrc    #  Will not expand to ~/.bashrc
~/?bashrc      #  Neither will this.
               #  Wild cards and metacharacters will NOT
               #+ expand to a dot in globbing.

~/.[b]ashrc    #  Will expand to ~/.bashrc
~/.ba?hrc      #  Likewise.
~/.bashr*      #  Likewise.

# Setting the "dotglob" option turns this off.

# Thanks, S.C.

   [98]

   Except, as Dennis Benzinger points out, if using <<- to suppress
   tabs.
   [99]

   By convention in UNIX and Linux, data streams and peripherals (device
   files) are treated as files, in a fashion analogous to ordinary
   files.
   [100]

   A file descriptor is simply a number that the operating system
   assigns to an open file to keep track of it. Consider it a simplified
   type of file pointer. It is analogous to a file handle in C.
   [101]

   Using file descriptor 5 might cause problems. When Bash creates a
   child process, as with exec, the child inherits fd 5 (see Chet
   Ramey's archived e-mail,
   [http://groups.google.com/group/gnu.bash.bug/browse_thread/thread/139
   55daafded3b5c/18c17050087f9f37] SUBJECT: RE: File descriptor 5 is
   held open). Best leave this particular fd alone.
   [102]

   An external command invoked with an exec does not (usually) fork off
   a subprocess / subshell.
   [103]

   This has the same effect as a named pipe (temp file), and, in fact,
   named pipes were at one time used in process substitution.
   [104]

   The return command is a Bash builtin.
   [105]

   Otherwise known as redundancy.
   [106]

   Otherwise known as tautology.
   [107]

   Otherwise known as a metaphor.
   [108]

   Otherwise known as a recursive function.
   [109]

   Too many levels of recursion may crash a script with a segfault.
#!/bin/bash

#  Warning: Running this script could possibly lock up your system!
#  If you're lucky, it will segfault before using up all available memory.

recursive_function ()
{
echo "$1"     # Makes the function do something, and hastens the segfault.
(( $1 < $2 )) && recursive_function $(( $1 + 1 )) $2;
#  As long as 1st parameter is less than 2nd,
#+ increment 1st and recurse.
}

recursive_function 1 50000  # Recurse 50,000 levels!
#  Most likely segfaults (depending on stack size, set by ulimit -m).

#  Recursion this deep might cause even a C program to segfault,
#+ by using up all the memory allotted to the stack.


echo "This will probably not print."
exit 0  # This script will not exit normally.

#  Thanks, StИphane Chazelas.

   [110]

   ... as the first word of a command string. Obviously, an alias is
   only meaningful at the beginning of a command.
   [111]

   However, aliases do seem to expand positional parameters.
   [112]

   The entries in /dev provide mount points for physical and virtual
   devices. These entries use very little drive space.

   Some devices, such as /dev/null, /dev/zero, and /dev/urandom are
   virtual. They are not actual physical devices and exist only in
   software.
   [113]

   A block device reads and/or writes data in chunks, or blocks, in
   contrast to a character device, which acesses data in character
   units. Examples of block devices are hard drives, CDROM drives, and
   flash drives. Examples of character devices are keyboards, modems,
   sound cards.
   [114]

   Of course, the mount point /mnt/flashdrive must exist. If not, then,
   as root, mkdir /mnt/flashdrive.

   To actually mount the drive, use the following command: mount
   /mnt/flashdrive

   Newer Linux distros automount flash drives in the /media directory
   without user intervention.
   [115]

   Certain system commands, such as procinfo, free, vmstat, lsdev, and
   uptime do this as well.
   [116]

   By convention, signal 0 is assigned to exit.
   [117]

   Setting the suid permission on the script itself has no effect in
   Linux and most other UNIX flavors.
   [118]

   In this context, "magic numbers" have an entirely different meaning
   than the magic numbers used to designate file types.
   [119]

   Quite a number of Linux utilities are, in fact, shell wrappers. Some
   examples are /usr/bin/pdf2ps, /usr/bin/batch, and /usr/bin/xmkmf.
   [120]

   ANSI is, of course, the acronym for the American National Standards
   Institute. This august body establishes and maintains various
   technical and industrial standards.
   [121]

   This usually means liberal use of functions.
   [122]

   See Marius van Oers' article, Unix Shell Scripting Malware, and also
   the Denning reference in the bibliography.
   [123]

   Or, better yet, #!/bin/env sh.
   [124]

   To be more specific, Bash 4+ has limited support for associative
   arrays. It's a bare-bones implementation, and it lacks the much of
   the functionality of such arrays in other programming languages.
   [125]

   Copyright 1995-2009 by Chester Ramey.
   [126]

   This only works with pipes and certain other special files.
   [127]

   But only in conjunction with readline, i.e., from the command-line.
   [128]

   And while you're at it, consider fixing the notorious piped read
   problem.
   [129]

   This is the notorious flog it to death technique that works so well
   with slow learners, eccentrics, odd ducks, fools and geniuses.
   [130]

   In fact, he is a school dropout with no formal credentials or
   professional experience whatsoever. None. Aside from the ABS Guide,
   his major claim to fame is a First Place in the sack race at the
   Colfax Elementary School Field Day in June, 1958.
   [131]

   Those who can, do. Those who can't . . . get an MCSE.
   [132]

   Sometimes it seems as if he has spent his entire life flouting
   conventional wisdom and defying the sonorous Voice of Authority:
   "Hey, you can't do that!"
   [133]

   E-mails from certain spam-infested TLDs (61, 202, 211, 218, 220,
   etc.) will be trapped by spam filters and deleted unread.
   [134]

   Well, if you absolutely insist, you can try modifying Example A-44 to
   suit your purposes.
   [135]

   It was hard to resist the obvious pun. No slight intended, since the
   book is a pretty decent introduction to the basic concepts of shell
   scripting.
   [136]

   Sed executes without user intervention.
   [137]

   If no address range is specified, the default is all lines.
   [138]

   Its name derives from the initials of its authors, Aho, Weinberg, and
   Kernighan.
   [139]

   Out of range exit values can result in unexpected exit codes. An exit
   value greater than 255 returns an exit code modulo 256. For example,
   exit 3809 gives an exit code of 225 (3809 % 256 = 225).
   [140]

   An update of /usr/include/sysexits.h allocates previously unused exit
   codes from 64 - 78. It may be anticipated that the range of
   unallotted exit codes will be further restricted in the future. The
   author of this document will not do fixups on the scripting examples
   to conform to the changing standard. This should not cause any
   problems, since there is no overlap or conflict in usage of exit
   codes between compiled C/C++ binaries and shell scripts.
   [141]

   This does not apply to csh, tcsh, and other shells not related to or
   descended from the classic Bourne shell (sh).
   [142]

   In older versions of UNIX, passwords were stored in /etc/passwd, and
   that explains the name of the file.
   [143]

   Some early UNIX systems had a fast, small-capacity fixed disk
   (containing /, the root partition), and a second drive which was
   larger, but slower (containing /usr and other partitions). The most
   frequently used programs and utilities therefore resided on the
   small-but-fast drive, in /bin, and the others on the slower drive, in
   /usr/bin.

   This likewise accounts for the split between /sbin and /usr/sbin,
   /lib and /usr/lib, etc.
   [144]

   This works only from the command line, of course, and not within a
   script.
   [145]

   Normally the default parameter completion files reside in either the
   /etc/profile.d directory or in /etc/bash_completion. These autoload
   on system startup. So, after writing a useful completion script, you
   might wish to move it (as root, of course) to one of these
   directories.
   [146]

   It has been extensively documented that programmers are willing to
   put in long hours of effort in order to save ten minutes of
   "unnecessary" labor. This is known as optimization.
   [147]

   Various readers have suggested modifications of the above batch file
   to prettify it and make it more compact and efficient. In the opinion
   of the ABS Guide author, this is wasted effort. A Bash script can
   access a DOS filesystem, or even an NTFS partition (with the help of
   [http://www.ntfs-3g.org] ntfs-3g) to do batch or scripted operations.
   [148]

   For all you clever types who failed intermediate algebra, a
   determinant is a numerical value associated with a multidimensional
   matrix (array of numbers).
For the simple case of a 2 x 2 determinant:

  |a  b|
  |b  a|

The solution is a*a - b*b, where "a" and "b" represent numbers.

   [149]

   The author intends that this book be released into the Public Domain
   after a period of 14 years from initial publication, that is, in
   2014. In the early years of the American republic this was the
   duration statutorily granted to a copyrighted work.

Комментариев нет:

Отправить комментарий