This commit is contained in:
gferg 2011-05-03 15:38:48 +00:00
parent af8ec1eeb2
commit b20be133ec
30 changed files with 1703 additions and 353 deletions

View File

@ -0,0 +1,102 @@
#!/bin/bash
# Author: Sigurd Solaas, 20 Apr 2011
# Used in ABS Guide with permission.
# Requires version 4.2+ of Bash.
key="no value yet"
while true; do
clear
echo "Bash Extra Keys Demo. Keys to try:"
echo
echo "* Insert, Delete, Home, End, Page_Up and Page_Down"
echo "* The four arrow keys"
echo "* Tab, enter, escape, and space key"
echo "* The letter and number keys, etc."
echo
echo " d = show date/time"
echo " q = quit"
echo "================================"
echo
# Convert the separate home-key to home-key_num_7:
if [ "$key" = $'\x1b\x4f\x48' ]; then
key=$'\x1b\x5b\x31\x7e'
# Quoted string-expansion construct.
fi
# Convert the separate end-key to end-key_num_1.
if [ "$key" = $'\x1b\x4f\x46' ]; then
key=$'\x1b\x5b\x34\x7e'
fi
case "$key" in
$'\x1b\x5b\x32\x7e') # Insert
echo Insert Key
;;
$'\x1b\x5b\x33\x7e') # Delete
echo Delete Key
;;
$'\x1b\x5b\x31\x7e') # Home_key_num_7
echo Home Key
;;
$'\x1b\x5b\x34\x7e') # End_key_num_1
echo End Key
;;
$'\x1b\x5b\x35\x7e') # Page_Up
echo Page_Up
;;
$'\x1b\x5b\x36\x7e') # Page_Down
echo Page_Down
;;
$'\x1b\x5b\x41') # Up_arrow
echo Up arrow
;;
$'\x1b\x5b\x42') # Down_arrow
echo Down arrow
;;
$'\x1b\x5b\x43') # Right_arrow
echo Right arrow
;;
$'\x1b\x5b\x44') # Left_arrow
echo Left arrow
;;
$'\x09') # Tab
echo Tab Key
;;
$'\x0a') # Enter
echo Enter Key
;;
$'\x1b') # Escape
echo Escape Key
;;
$'\x20') # Space
echo Space Key
;;
d)
date
;;
q)
echo Time to quit...
echo
exit 0
;;
*)
echo You pressed: \'"$key"\'
;;
esac
echo
echo "================================"
unset K1 K2 K3
read -s -N1 -p "Press a key: "
K1="$REPLY"
read -s -N2 -t 0.001
K2="$REPLY"
read -s -N1 -t 0.001
K3="$REPLY"
key="$K1$K2$K3"
done
exit $?

View File

@ -7,15 +7,149 @@
==================================================================
Current version = 6.2
Dated 03/17/10
Current version = 6.3
Dated 04/30/12
http://bash.webofcrafts.net/abs-guide-latest.tar.bz2
http://bash.webofcrafts.net/abs-guide.pdf
--------------------------------------------------------------------
News: Version 6.2 released!
News: Version 6.3 released!
====================================================================
Version 6.3, Swozzleberry* release
30 April, 2011
1) Added brief coverage of Bash 4.1/4.2 releases.
Read -N.
Negative array indices.
Negative parameter in string extraction.
Bash now recognizes \u unicode escape.
There is a new "lastpipe" shell option.
etc.
2) In "Shell Programming!" chapter,
Fixed the URL on the Christensen quote.
(Thanks, Ilario Fav.)
3) In "Special Characters" chapter,
Revised "?:" trinary-construct entry.
Added $' ... ' entry.
Added definition of ASCII.
4) In the "Tests" chapter,
At "-p" entry, added Carl Anderson's example.
5) In "Introduction to Variables and Parameters" chapter:
In "Variable Substitution" section:
Corrected comment concerning when variables appear "naked."
Removed comment about non-portable behavior of uninitialize
variables in arithmetic expressions.
(Thank you, Jeffery Haemer.)
Added footnote that $0 does not always return the script name.
(Thank you, Gregg Leichtman!)
6) In "Internal Commands and Builtins" chapter,
At "let" entry,
added caution about misleading exit status returned in certain
situations. (Thank you, Evgeniy Ivanov.)
In "Job controls" subsection,
added footnote that "wait" can only take PIDs of child processes
as arguments.
(Thank you, Simon Haller.)
7) In "I/O Redirection" chapter:
Fixed commentary on "ls -yz 2>&1 >> command.log" example.
(Thank you, Teika Kazura.)
8) In "max.sh" example script, fixed comment.
(Thank you, Robert Bruntz.)
9) In the "Bash, versions 2,3, and 4" chapter,
removed the "{X..d..2}" example.
(Thank you, Jeffrey Haemer, for the pointer.)
10) In "Bash, versions 2, 3, and 4" chapter,
In the Version 3.1 section,
At the "+=" entry, added Jeffrey Haemer's $PATH append example.
11) In "Local Variables" section of "Functions" chapter:
Added note about return value of setting local variable.
(Thank you, Evegniy Ivanov.)
12) In "Complex Commands" section of "External Commands" Chapter:
At "xargs" entry:
Added tip about using the -P option to run processes in parallel.
(Thank you, Roberto Polli.)
13) In "Here Documents" chapter:
Added footnote about using <<- to suppress tabs allowing closing limit
string to deviate from the first column on a line.
(Thank you, Dennis Benzinger.)
14) In the "Miscellany" chapter:
Fixed the URL on Moshe Jacobson's utility (changed it to point to
the "ansi-color" script). Then, decided to rehost Jacobson's original
source code on webofcrafts.net.
(Thank you, qun-ying, for pointing out the broken URL.)
15) In the "Variables Revisited" chapter:
In "Parameter Substitution" section:
Revised the "${parameter:?err_msg}" entry, per Kevin LeBlanc
(thanks!).
16) In "Process Substitution" chapter:
Added "psub.bash" example of redirecting output of process
substitution into a loop.
(Thanks, Diego Molina!)
17) Reference cards:
Revisions, per Kevin LeBlanc (thanks!).
18) Added a snippet from Andrzej Szelachowski's ~/.bash_profile file
to the ".bashrc" Appendix.
(Thanks!)
19) In "/dev" section of "/dev and /proc" chapter:
Expanded Mark's command-line time-fetch example into a short script.
20) In "Network" subsection of "System and Administrative Commands,"
Added "iptables" entry.
Moved "nmap" and "netstat" entries here.
21) Added "Network Programming" chapter.
Moved "test-cgi.sh" script here from TODO section.
22) In "Escaping" section of "Quoting" Chapter:
Broke out $' ... ' string-expansion as a separate topic.
(This was a long-overdue fixup.)
23) New scripts:
read-N.sh
here-commsub.sh
neg-array.sh
neg-offset.sh
base64.sh
ip-addresses.sh
lastpipe-option.sh
BashExtraKeys.sh (with thanks to Sigurd Solaas).
Long in-line example at "Unicode" entry,
with tie-in to $' ... ' string-expansion.
24) In "Writing Scripts" section of "Exercises" appendix:
Added "Unicode Table" exercise to Intermediate section.
25) Fixups on various typos.
26) Fixups on scripts.
* Swozzleberry? There really is such a thing?
It's a variant spelling of "swazzle,"
a sort of kazoo-like noisemaker used by puppeteers.
Now, imagine a gourd-like berry that can be used
to make funny sounds. . . .
Version 6.2, Rowanberry release
17 March, 2010

View File

@ -535,6 +535,10 @@
</itemizedlist></para>
<!-- ********************** -->
<para><command>$' ... '</command>
<link linkend="strq">String expansion</link>,
using <firstterm>escaped</firstterm> characters.</para>
<para><command>\ </command>
<link linkend="escp">Escape</link> the character following
<itemizedlist>
@ -881,7 +885,14 @@
<para><link linkend="readarrow">Arrow keys</link>, detecting</para>
<para><link linkend="asciitable">ASCII table</link></para>
<para>ASCII
<itemizedlist>
<listitem><para><link
linkend="asciidef">Definition</link></para></listitem>
<listitem><para><link linkend="asciitable">
Script to generate ASCII table</link></para></listitem>
</itemizedlist>
</para>
<!-- ********************** -->
<para><link linkend="awk">awk</link> field-oriented text
@ -930,8 +941,11 @@
Version 2</link></para></listitem>
<listitem><para><link linkend="bash3ref">
Version 3</link></para></listitem>
<listitem><para><link linkend="bash4ref">
Version 4</link></para></listitem>
<listitem>
<para><link linkend="bash4ref">Version 4</link></para>
<para><link linkend="bash41">Version 4.1</link></para>
<para><link linkend="bash42">Version 4.2</link></para>
</listitem>
</itemizedlist></para>
<!-- ********************** -->
@ -956,7 +970,13 @@
<para><link linkend="biblio">Bibliography</link></para>
<para><link linkend="bisonref">Bison</link> utility</para>
<para><link linkend="bitwsops1">Bitwise operators</link></para>
<para><link linkend="bitwsops1">Bitwise operators</link>
<itemizedlist>
<listitem><para><link linkend="base64">Example script</link>
</para></listitem>
</itemizedlist>
</para>
<para><link linkend="blockdevref">Block devices</link>
<itemizedlist>
@ -1339,8 +1359,17 @@
comparison</link> test</para>
<para><link linkend="primes0">Eratosthenes,
Sieve of</link>, algorithm for generating prime numbers</para>
<para><link linkend="spm">Escaped characters</link>,
special meanings of</para>
special meanings of
<itemizedlist>
<listitem><para>Within <link linkend="strq">$' ... '</link>
string expansion</para></listitem>
<listitem><para><link linkend="unicoderef2">Used with
<firstterm>Unicode</firstterm> characters</link></para></listitem>
</itemizedlist>
</para>
<para><link
linkend="fstabref"><filename>/etc/fstab</filename></link>
(filesystem mount) file</para>
@ -1390,6 +1419,9 @@
<para><link linkend="exitcodesref"><command>Table</command></link>,
<firstterm>Exit
codes</firstterm> with special meanings</para>
<para>
<link linkend="gotchaexitvalanamalies">Anomalous</link>
</para>
<para><link linkend="excoor">Out of range</link></para>
<para><link linkend="pipeex"><firstterm>Pipe</firstterm></link>
exit status</para>
@ -1800,6 +1832,17 @@
</itemizedlist></para>
<!-- ********************** -->
<para><link linkend="iptablesref">iptables</link>,
packet filtering and firewall utility
<itemizedlist>
<listitem><para><link linkend="iptables01">Usage
example</link></para></listitem>
<listitem><para><link linkend="iptables02">Example
script</link></para></listitem>
</itemizedlist></para>
<para><link linkend="iterationref">Iteration</link></para>
<para>* * *</para>
@ -1834,6 +1877,9 @@
<para>* * *</para>
<para><link linkend="lastpiperef">lastpipe</link> shell
option</para>
<para><link linkend="le0ref"> -le </link>,
<firstterm>less-than or equal</firstterm>
<link linkend="icomparison1">integer comparison</link> test</para>
@ -2047,6 +2093,7 @@
linkend="ifthen">test</link></para>
<para><link linkend="netstatref">netstat</link>, Network
statistics</para>
<para><link linkend="networkprogramming">Network programming</link></para>
<para><link linkend="nlref">nl</link>, a filter to number lines of
text</para>
<para><link linkend="noclobberref"><firstterm>Noclobber</firstterm></link>,
@ -2156,7 +2203,13 @@
<para><link linkend="pathref"><varname>$PATH</varname></link>,
the <firstterm>path</firstterm> (location of system
binaries)</para>
binaries)
<itemizedlist>
<listitem><para>Appending directories to <varname>$PATH</varname>
<link linkend="pathappend">using the <varname>+=</varname>
operator</link>.</para></listitem>
</itemizedlist></para>
<para><link linkend="perlref">Perl</link>, programming language
<itemizedlist>
<listitem><para><link linkend="bashandperl0">Combined</link> in the
@ -2236,6 +2289,10 @@
using</para></listitem>
<listitem><para><link linkend="execperm">Execute permission
lacking</link> for commands within a script</para></listitem>
<listitem><para>
<firstterm>Exit status</firstterm>,
<link linkend="gotchaexitvalanamalies">anomalous</link>
</para></listitem>
<listitem><para><link
linkend="parchildprobref"><firstterm>Export</firstterm>
problem</link>, <firstterm>child</firstterm> process
@ -3156,6 +3213,9 @@
the return value</link> of a function, using
<firstterm>echo</firstterm></para></listitem>
<listitem><para><link linkend="cgiscript"><firstterm>CGI</firstterm>
programming</link>, using scripts for</para></listitem>
<listitem>
<para>Comment blocks</para>
<para>Using <link linkend="cblock1"><firstterm>anonymous
@ -3192,6 +3252,9 @@
<listitem><para><link linkend="passarray">Passing
an <firstterm>array</firstterm></link> to a
function</para></listitem>
<listitem><para><varname>$PATH</varname>,
appending to, <link linkend="pathappend">using the
<varname>+=</varname> operator</link>.</para></listitem>
<listitem><para><link
linkend="prependref"><firstterm>Prepending</firstterm></link>
lines at head of a file</para></listitem>
@ -3297,6 +3360,8 @@
to remove an <link linkend="aliasref">alias</link></para>
<para><link linkend="unameref">uname</link>,
output system information</para>
<para><link linkend="unicoderef">Unicode</link>, encoding standard
for representing letters and symbols</para>
<para><link linkend="uninitvar">Uninitialized variables</link> </para>
<para><link linkend="uniqref">uniq</link>,
filter to remove duplicate lines from a sorted file</para>

View File

@ -114,11 +114,15 @@ progress-bar.sh
line 30
nim.sh
line 27
paragraph-spac3.sh
line 6
sw.sh
line 5 (comment)
here-commsub.sh
line 5
UseGetOpt.sh: line 4 (comment)
UseGetOpt-2.sh: line 11 (comment)

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,8 @@
# Attempting to use 'echo and 'read'
#+ to assign variables non-interactively.
# shopt -s lastpipe
a=aaa
b=bbb
c=ccc
@ -16,6 +18,12 @@ echo "b = $b" # b = bbb
echo "c = $c" # c = ccc
# Reassignment failed.
### However . . .
## Uncommenting line 6:
# shopt -s lastpipe
##+ fixes the problem!
### This is a new feature in Bash, version 4.2.
# ------------------------------
# Try the following alternative.

View File

@ -0,0 +1,129 @@
#!/bin/bash
# base64.sh: Bash implementation of Base64 encoding and decoding.
#
# Copyright (c) 2011 vladz [vladz@devzero.fr]
# Used in ABSG with permission (thanks!).
#
# Encode or decode original Base64 (and also Base64url)
#+ from STDIN to STDOUT.
#
# Usage:
#
# Encode
# $ ./base64.sh < binary-file > binary-file.base64
# Decode
# $ ./base64.sh -d < binary-file.base64 > binary-file
#
# Reference:
#
# [1] RFC4648 - "The Base16, Base32, and Base64 Data Encodings"
#  http://tools.ietf.org/html/rfc4648#section-5
# The base64_charset[] array contains entire base64 charset,
# and additionally the character "=" ...
base64_charset=( {A..Z} {a..z} {0..9} + / = )
# Nice illustration of brace expansion.
# Uncomment the ### line below to use base64url encoding instead of
#+ original base64.
### base64_charset=( {A..Z} {a..z} {0..9} - _ = )
# Output text width when encoding
#+ (64 characters, just like openssl output).
text_width=64
function display_base64_char {
#  Convert a 6-bit number (between 0 and 63) into its corresponding values
#+ in Base64, then display the result with the specified text width.
printf "${base64_charset[$1]}"; (( width++ ))
(( width % text_width == 0 )) && printf "\n"
}
function encode_base64 {
# Encode three 8-bit hexadecimal codes into four 6-bit numbers.
# We need two local int array variables:
#  c8[]: to store the codes of the 8-bit characters to encode
# c6[]: to store the corresponding encoded values on 6-bit
declare -a -i c8 c6
# Convert hexadecimal to decimal.
c8=( $(printf "ibase=16; ${1:0:2}\n${1:2:2}\n${1:4:2}\n" | bc) )
#  Let's play with bitwise operators
#+ (3x8-bit into 4x6-bits conversion).
(( c6[0] = c8[0] >> 2 ))
(( c6[1] = ((c8[0] & 3) << 4) | (c8[1] >> 4) ))
# The following operations depend on the c8 element number.
case ${#c8[*]} in
3) (( c6[2] = ((c8[1] & 15) << 2) | (c8[2] >> 6) ))
(( c6[3] = c8[2] & 63 )) ;;
2) (( c6[2] = (c8[1] & 15) << 2 ))
(( c6[3] = 64 )) ;;
1) (( c6[2] = c6[3] = 64 )) ;;
esac
for char in ${c6[@]}; do
display_base64_char ${char}
done
}
function decode_base64 {
# Decode four base64 characters into three hexadecimal ASCII characters.
#  c8[]: to store the codes of the 8-bit characters
# c6[]: to store the corresponding Base64 values on 6-bit
declare -a -i c8 c6
# Find decimal value corresponding to the current base64 character.
for current_char in ${1:0:1} ${1:1:1} ${1:2:1} ${1:3:1}; do
[ "${current_char}" = "=" ] && break
position=0
while [ "${current_char}" != "${base64_charset[${position}]}" ]; do
(( position++ ))
done
c6=( ${c6[*]} ${position} )
done
#  Let's play with bitwise operators
#+ (4x8-bit into 3x6-bits conversion).
(( c8[0] = (c6[0] << 2) | (c6[1] >> 4) ))
# The next operations depends on the c6 elements number.
case ${#c6[*]} in
3) (( c8[1] = ( (c6[1] & 15) << 4) | (c6[2] >> 2) ))
(( c8[2] = (c6[2] & 3) << 6 )); unset c8[2] ;;
4) (( c8[1] = ( (c6[1] & 15) << 4) | (c6[2] >> 2) ))
(( c8[2] = ( (c6[2] & 3) << 6) | c6[3] )) ;;
esac
for char in ${c8[*]}; do
printf "\x$(printf "%x" ${char})"
done
}
# main ()
if [ $# -eq 0 ]; then # encode
# Make a hexdump of stdin and reformat in 3-byte groups.
content=$(cat - | xxd -ps -u | sed -r "s/(\w{6})/\1 /g" |
tr -d "\n")
for chars in ${content}; do encode_base64 ${chars}; done
echo
elif [ "$1" = "-d" ]; then # decode
# Reformat STDIN in pseudo 4x6-bit groups.
content=$(cat - | tr -d "\n" | sed -r "s/(.{4})/\1 /g")
for chars in ${content}; do decode_base64 ${chars}; done
else # display usage
echo
printf "Usage: $0 < Infile > Outfile\n"
printf " $0 -d < Infile > Outfile\n"
printf " -d decode\n\n"
fi

View File

@ -0,0 +1,51 @@
# From Andrzej Szelachowski's ~/.bash_profile:
# Note that a variable may require special treatment
#+ if it will be exported.
DARKGRAY='\e[1;30m'
LIGHTRED='\e[1;31m'
GREEN='\e[32m'
YELLOW='\e[1;33m'
LIGHTBLUE='\e[1;34m'
NC='\e[m'
PCT="\`if [[ \$EUID -eq 0 ]]; then T='$LIGHTRED' ; else T='$LIGHTBLUE'; fi;
echo \$T \`"
# For "literal" command substitution to be assigned to a variable,
#+ use escapes and double quotes:
#+ PCT="\` ... \`" . . .
# Otherwise, the value of PCT variable is assigned only once,
#+ when the variable is exported/read from .bash_profile,
#+ and it will not change afterwards even if the user ID changes.
PS1="\n$GREEN[\w] \n$DARKGRAY($PCT\t$DARKGRAY)-($PCT\u$DARKGRAY)-($PCT\!
$DARKGRAY)$YELLOW-> $NC"
# Escape a variables whose value changes:
# if [[ \$EUID -eq 0 ]],
# Otherwise the value of the EUID variable will be assigned only once,
#+ as above.
# When a variable is assigned, it should be called escaped:
#+ echo \$T,
# Otherwise the value of the T variable is taken from the moment the PCT
#+ variable is exported/read from .bash_profile.
# So, in this example it would be null.
# When a variable's value contains a semicolon it should be strong quoted:
# T='$LIGHTRED',
# Otherwise, the semicolon will be interpreted as a command separator.
# Variables PCT and PS1 can be merged into a new PS1 variable:
PS1="\`if [[ \$EUID -eq 0 ]]; then PCT='$LIGHTRED';
else PCT='$LIGHTBLUE'; fi;
echo '\n$GREEN[\w] \n$DARKGRAY('\$PCT'\t$DARKGRAY)-\
('\$PCT'\u$DARKGRAY)-('\$PCT'\!$DARKGRAY)$YELLOW-> $NC'\`"
# The trick is to use strong quoting for parts of old PS1 variable.

View File

@ -1,8 +1,11 @@
#!/bin/bash
# connect-stat.sh
# Note that this script may need modification
#+ to work with a wireless connection.
PROCNAME=pppd # ppp daemon
PROCFILENAME=status # Where to look.
NOTCONNECTED=65
NOTCONNECTED=85
INTERVAL=2 # Update every 2 seconds.
pidno=$( ps ax | grep -v "ps ax" | grep -v grep | grep $PROCNAME |
@ -22,7 +25,7 @@ awk '{ print $1 }' )
if [ -z "$pidno" ] # If no pid, then process is not running.
then
echo "Not connected."
exit $NOTCONNECTED
# exit $NOTCONNECTED
else
echo "Connected."; echo
fi
@ -34,7 +37,7 @@ do
# While process running, then "status" file exists.
then
echo "Disconnected."
exit $NOTCONNECTED
# exit $NOTCONNECTED
fi
netstat -s | grep "packets received" # Get some connect statistics.
@ -54,3 +57,4 @@ exit 0
# ---------
# Improve the script so it exits on a "q" keystroke.
# Make the script more user-friendly in other ways.
# Fix the script to work with wireless/DSL connections.

View File

@ -3,6 +3,10 @@
echo; echo
#############################################################
### First, let's show some basic escaped-character usage. ###
#############################################################
# Escaping a newline.
# ------------------
@ -33,28 +37,40 @@ echo "QUOTATION MARK"
echo -e "\042" # Prints " (quote, octal ASCII character 42).
echo "=============="
# The $'\X' construct makes the -e option unnecessary.
echo; echo "NEWLINE AND BEEP"
echo $'\n' # Newline.
echo $'\a' # Alert (beep).
echo "==============="
echo "---------------"
echo "QUOTATION MARKS"
# Version 2 and later of Bash permits using the $'\nnn' construct.
# Note that in this case, '\nnn' is an octal value.
echo "---------------"
echo; echo; echo
# Here we have seen $'\nnn" string expansion.
# =================================================================== #
# Version 2 of Bash introduced the $'\nnn' string expansion construct.
# =================================================================== #
echo "Introducing the \$\' ... \' string-expansion construct!"
echo
echo $'\t \042 \t' # Quote (") framed by tabs.
# Note that '\nnn' is an octal value.
# It also works with hexadecimal values, in an $'\xhhh' construct.
echo $'\t \x22 \t' # Quote (") framed by tabs.
# Thank you, Greg Keraunen, for pointing this out.
# Earlier Bash versions allowed '\x022'.
echo "==============="
echo
# Assigning ASCII characters to a variable.
# ----------------------------------------
quote=$'\042' # " assigned to a variable.

View File

@ -4,4 +4,4 @@
cd /var/log
cat /dev/null > messages
cat /dev/null > wtmp
echo "Logs cleaned up."
echo "Log files cleaned up."

View File

@ -16,4 +16,6 @@ cat /dev/null > wtmp
echo "Logs cleaned up."
exit # The right and proper method of "exiting" from a script.
exit # The right and proper method of "exiting" from a script.
# A bare "exit" (no parameter) returns the exit status
#+ of the preceding command.

View File

@ -75,7 +75,9 @@ mv mesg.temp messages # Becomes new log directory.
#* No longer needed, as the above method is safer.
cat /dev/null > wtmp # ': > wtmp' and '> wtmp' have the same effect.
echo "Logs cleaned up."
echo "Log files cleaned up."
# Note that there are other log files in /var/log not affected
#+ by this script.
exit 0
# A zero return value from the script upon exit indicates success

View File

@ -29,21 +29,21 @@ fetch_address ()
}
store_address "Charles Jones" "414 W. 10th Ave., Baltimore, MD 21236"
store_address "John Smith" "202 E. 3rd St., New York, NY 10009"
store_address "Wilma Wilson" "1854 Vermont Ave, Los Angeles, CA 90023"
store_address "Lucas Fayne" "414 W. 13th Ave., Baltimore, MD 21236"
store_address "Arvid Boyce" "202 E. 3rd St., New York, NY 10009"
store_address "Velma Winston" "1854 Vermont Ave, Los Angeles, CA 90023"
# Exercise:
# Rewrite the above store_address calls to read data from a file,
#+ then assign field 1 to name, field 2 to address in the array.
# Each line in the file would have a format corresponding to the above.
# Use a while-read loop to read from file, sed or awk to parse the fields.
fetch_address "Charles Jones"
# Charles Jones's address is 414 W. 10th Ave., Baltimore, MD 21236.
fetch_address "Wilma Wilson"
# Wilma Wilson's address is 1854 Vermont Ave, Los Angeles, CA 90023.
fetch_address "John Smith"
# John Smith's address is 202 E. 3rd St., New York, NY 10009.
fetch_address "Lucas Fayne"
# Lucas Fayne's address is 414 W. 13th Ave., Baltimore, MD 21236.
fetch_address "Velma Winston"
# Velma Winston's address is 1854 Vermont Ave, Los Angeles, CA 90023.
fetch_address "Arvid Boyce"
# Arvid Boyce's address is 202 E. 3rd St., New York, NY 10009.
fetch_address "Bozo Bozeman"
# Bozo Bozeman's address is not in database.

View File

@ -15,3 +15,8 @@ echo "Wilma's address is ${address[Wilma]}."
# Wilma's address is 1854 Vermont Ave, Los Angeles, CA 90023.
echo "John's address is ${address[John]}."
# John's address is 202 E. 3rd St., New York, NY 10009.
echo
echo "${!address[*]}" # The array indices ...
# Charles John Wilma

View File

@ -16,10 +16,10 @@
### Variables && sanity check ###
E_NOPARAM=86
E_BADPARAM=87 # Illegal no. of disks passed to script.
E_BADPARAM=87 # Illegal no. of disks passed to script.
E_NOEXIT=88
DISKS=${1:-E_NOPARAM} # Must specify how many disks.
DISKS=${1:-$E_NOPARAM} # Must specify how many disks.
Moves=0
MWIDTH=7

View File

@ -0,0 +1,25 @@
#!/bin/bash
# here-commsub.sh
# Requires Bash version -ge 4.1 ...
multi_line_var=$( cat &lt;&lt;ENDxxx
------------------------------
This is line 1 of the variable
This is line 2 of the variable
This is line 3 of the variable
------------------------------
ENDxxx)
# Rather than what Bash 4.0 requires:
#+ that the terminating limit string and
#+ the terminating close-parenthesis be on separate lines.
# ENDxxx
# )
echo "$multi_line_var"
# Bash still emits a warning, though.
# warning: here-document at line 10 delimited
#+ by end-of-file (wanted `ENDxxx')

View File

@ -0,0 +1,38 @@
#!/bin/bash
# ip-addresses.sh
# List the IP addresses your computer is connected to.
# Inspired by Greg Bledsoe's ddos.sh script,
# Linux Journal, 09 March 2011.
# URL:
# http://www.linuxjournal.com/content/back-dead-simple-bash-complex-ddos
# Greg licensed his script under the GPL2,
#+ and as a derivative, this script is likewise GPL2.
connection_type=TCP # Also try UDP.
field=2 # Which field of the output we're interested in.
no_match=LISTEN # Filter out records containing this. Why?
lsof_args=-ni # -i lists Internet-associated files.
# -n preserves numerical IP addresses.
# What happens without the -n option? Try it.
router="[0-9][0-9][0-9][0-9][0-9]->"
# Delete the router info.
lsof "$lsof_args" | grep $connection_type | grep -v "$no_match" |
awk '{print $9}' | cut -d : -f $field | sort | uniq |
sed s/"^$router"//
# Bledsoe's script assigns the output of a filtered IP list,
# (similar to lines 19-22, above) to a variable.
# He checks for multiple connections to a single IP address,
# then uses:
#
# iptables -I INPUT -s $ip -p tcp -j REJECT --reject-with tcp-reset
#
# ... within a 60-second delay loop to bounce packets from DDOS attacks.
# Exercise:
# --------
# Use the 'iptables' command to extend this script
#+ to reject connection attempts from well-known spammer IP domains.

View File

@ -0,0 +1,20 @@
#!/bin/bash
# lastpipe-option.sh
line='' # Null value.
echo "\$line = "$line"" # $line =
echo
shopt -s lastpipe # Error on Bash version -lt 4.2.
echo "Exit status of attempting to set \"lastpipe\" option is $?"
# 1 if Bash version -lt 4.2, 0 otherwise.
echo
head -1 $0 | read line # Pipe the first line of the script to read.
# ^^^^^^^^^ Not in a subshell!!!
echo "\$line = "$line""
# Older Bash releases $line =
# Bash version 4.2 $line = #!/bin/bash

View File

@ -7,7 +7,7 @@ EQUAL=251 # Return value if both params equal.
#+ params that might be fed to the function.
max2 () # Returns larger of two numbers.
{ # Note: numbers compared must be less than 257.
{ # Note: numbers compared must be less than 250.
if [ -z "$2" ]
then
return $E_PARAM_ERR

View File

@ -0,0 +1,36 @@
#!/bin/bash
# neg-array.sh
# Requires Bash, version -ge 4.2.
array=( zero one two three four five ) # Six-element array.
# Negative array indices now permitted.
echo ${array[-1]} # five
echo ${array[-2]} # four
# ...
echo ${array[-6]} # zero
# Negative array indices count backward from the last element+1.
# But, you cannot index past the beginning of the array.
echo ${array[-7]} # array: bad array subscript
# So, what is this new feature good for?
echo "The last element in the array is "${array[-1]}""
# Which is quite a bit more straightforward than:
echo "The last element in the array is "${array[${#array[*]}-1]}""
echo
# And ...
index=0
let "neg_element_count = 0 - ${#array[*]}"
# Number of elements, converted to a negative number.
while [ $index -gt $neg_element_count ]; do
((index--)); echo -n "${array[index]} "
done # Lists the elements in the array, backwards.
# We have just simulated the "tac" command on this array.
echo

View File

@ -0,0 +1,21 @@
#!/bin/bash
# Bash, version -ge 4.2
# Negative length-index in substring extraction.
# Important: This changes the interpretation of this construct!
stringZ=abcABC123ABCabc
echo ${stringZ} # abcABC123ABCabc
echo ${stringZ:2:3} # cAB
# Count 2 chars forward from string beginning, and extract 3 chars.
# ${string:position:length}
# So far, nothing new, but now ...
echo ${stringZ:3:-6} # ABC123
# ^
# Index 3 chars forward from beginning and 6 chars backward from end,
#+ and extract everything in between.
# ${string:offset-from-front:offset-from-end}
# When the "length" parameter is negative,
#+ it serves as an "offset-from-end" parameter.

View File

@ -57,8 +57,6 @@ let "bad_oct = 081"
# bad_oct = 081: value too great for base (error token is "081")
# Octal numbers use only digits in the range 0 - 7.
exit $? # Thanks, Rich Bartell and Stephane Chazelas, for clarification.
exit $? # Exit value = 1 (error)
$ sh numbers.sh
$ echo $?
$ 1
# Thanks, Rich Bartell and Stephane Chazelas, for clarification.

View File

@ -0,0 +1,20 @@
#!/bin/bash
# psub.bash
# As inspired by Diego Molina (thanks!).
declare -a array0
while read
do
array0[${#array0[@]}]="$REPLY"
done < <( sed -e 's/bash/CRASH-BANG!/' $0 | grep bin | awk '{print $1}' )
echo "${array0[@]}"
exit $?
# ====================================== #
bash psub.bash
#!/bin/CRASH-BANG! done #!/bin/CRASH-BANG!

View File

@ -2,6 +2,7 @@
# random-between.sh
# Random number between two specified values.
# Script by Bill Gradwohl, with minor modifications by the document author.
# Corrections in lines 187 and 189 by Anthony Le Clezio.
# Used with permission.
@ -184,9 +185,9 @@ done
# Let's check the results
for ((i=${minimum}; i<=${maximum}; i+=divisibleBy)); do
[ ${answer[i+displacement]} -eq 0 ] \
[ ${answer[i+disp]} -eq 0 ] \
&& echo "We never got an answer of $i." \
|| echo "${i} occurred ${answer[i+displacement]} times."
|| echo "${i} occurred ${answer[i+disp]} times."
done

View File

@ -0,0 +1,15 @@
#!/bin/bash
# Requires Bash version -ge 4.1 ...
num_chars=61
read -N $num_chars var < $0 # Read first 61 characters of script!
echo "$var"
exit
####### Output of Script #######
#!/bin/bash
# Requires Bash version -ge 4.1 ...
num_chars=61

View File

@ -2,6 +2,8 @@
# readpipe.sh
# This example contributed by Bjon Eriksson.
### shopt -s lastpipe
last="(null)"
cat $0 |
while read line
@ -12,7 +14,9 @@ done
echo
echo "++++++++++++++++++++++"
printf "\nAll done, last: $last\n"
printf "\nAll done, last: $last\n" # The output of this line
#+ changes if you uncomment line 5.
# (Bash, version -ge 4.2 required.)
exit 0 # End of code.
# (Partial) output of script follows.

View File

@ -5,7 +5,7 @@
ARGCOUNT=1 # Expect one arg.
E_WRONGARGS=65
E_WRONGARGS=85
file=/etc/passwd
pattern=$1

View File

@ -45,6 +45,7 @@ do
# Now, retrieve value, using indirect referencing.
echo "There are ${!Inv} of [${!Val} ohm / ${!Pdissip} watt]\
resistors in stock." # ^ ^
# As of Bash 4.2, you can replace "ohm" with \u2126 (using echo -e).
echo "These are located in bin # ${!Loc}."
echo "Their color code is \"${!Ccode}\"."

View File

@ -1,13 +1,12 @@
#!/bin/bash
# May have to change the location for your site.
# (At the ISP's servers, Bash may not be in the usual place.)
# Other places: /usr/bin or /usr/local/bin
# Might even try it without any path in sha-bang.
# test-cgi.sh
# by Michael Zick
# Used with permission
# May have to change the location for your site.
# (At the ISP's servers, Bash may not be in the usual place.)
# Other places: /usr/bin or /usr/local/bin
# Might even try it without any path in sha-bang.
# Disable filename globbing.
set -f