⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 contributed-scripts.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 5 页
字号:
   9&nbsp;  10&nbsp;  11&nbsp;MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"  12&nbsp;# ==&#62; Password will consist of alphanumeric characters.  13&nbsp;LENGTH="8"  14&nbsp;# ==&#62; May change 'LENGTH' for longer password.  15&nbsp;  16&nbsp;  17&nbsp;while [ "${n:=1}" -le "$LENGTH" ]  18&nbsp;# ==&#62; Recall that := is "default substitution" operator.  19&nbsp;# ==&#62; So, if 'n' has not been initialized, set it to 1.  20&nbsp;do  21&nbsp;	PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"  22&nbsp;	# ==&#62; Very clever, but tricky.  23&nbsp;  24&nbsp;	# ==&#62; Starting from the innermost nesting...  25&nbsp;	# ==&#62; ${#MATRIX} returns length of array MATRIX.  26&nbsp;  27&nbsp;	# ==&#62; $RANDOM%${#MATRIX} returns random number between 1  28&nbsp;	# ==&#62; and [length of MATRIX] - 1.  29&nbsp;  30&nbsp;	# ==&#62; ${MATRIX:$(($RANDOM%${#MATRIX})):1}  31&nbsp;	# ==&#62; returns expansion of MATRIX at random position, by length 1.   32&nbsp;	# ==&#62; See {var:pos:len} parameter substitution in Chapter 9.  33&nbsp;	# ==&#62; and the associated examples.  34&nbsp;  35&nbsp;	# ==&#62; PASS=... simply pastes this result onto previous PASS (concatenation).  36&nbsp;  37&nbsp;	# ==&#62; To visualize this more clearly, uncomment the following line  38&nbsp;	#                 echo "$PASS"  39&nbsp;	# ==&#62; to see PASS being built up,  40&nbsp;	# ==&#62; one character at a time, each iteration of the loop.  41&nbsp;  42&nbsp;	let n+=1  43&nbsp;	# ==&#62; Increment 'n' for next pass.  44&nbsp;done  45&nbsp;  46&nbsp;echo "$PASS"      # ==&#62; Or, redirect to a file, as desired.  47&nbsp;  48&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>+</P><P><ANAME="ZFIFO"></A>James R. Van Zandt contributed this script      which uses named pipes and, in his words, <SPANCLASS="QUOTE">"really exercises      quoting and escaping."</SPAN></P><DIVCLASS="EXAMPLE"><HR><ANAME="FIFO"></A><P><B>Example A-15. <ICLASS="FIRSTTERM">fifo</I>: Making daily backups, using      named pipes</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# ==&#62; Script by James R. Van Zandt, and used here with his permission.   3&nbsp;   4&nbsp;# ==&#62; Comments added by author of this document.   5&nbsp;   6&nbsp;     7&nbsp;  HERE=`uname -n`    # ==&#62; hostname   8&nbsp;  THERE=bilbo   9&nbsp;  echo "starting remote backup to $THERE at `date +%r`"  10&nbsp;  # ==&#62; `date +%r` returns time in 12-hour format, i.e. "08:08:34 PM".  11&nbsp;    12&nbsp;  # make sure /pipe really is a pipe and not a plain file  13&nbsp;  rm -rf /pipe  14&nbsp;  mkfifo /pipe       # ==&#62; Create a "named pipe", named "/pipe".  15&nbsp;    16&nbsp;  # ==&#62; 'su xyz' runs commands as user "xyz".  17&nbsp;  # ==&#62; 'ssh' invokes secure shell (remote login client).  18&nbsp;  su xyz -c "ssh $THERE \"cat &#62; /home/xyz/backup/${HERE}-daily.tar.gz\" &#60; /pipe"&#38;  19&nbsp;  cd /  20&nbsp;  tar -czf - bin boot dev etc home info lib man root sbin share usr var &#62; /pipe  21&nbsp;  # ==&#62; Uses named pipe, /pipe, to communicate between processes:  22&nbsp;  # ==&#62; 'tar/gzip' writes to /pipe and 'ssh' reads from /pipe.  23&nbsp;  24&nbsp;  # ==&#62; The end result is this backs up the main directories, from / on down.  25&nbsp;  26&nbsp;  # ==&#62;  What are the advantages of a "named pipe" in this situation,  27&nbsp;  # ==&#62;+ as opposed to an "anonymous pipe", with |?  28&nbsp;  # ==&#62;  Will an anonymous pipe even work here?  29&nbsp;  30&nbsp;  # ==&#62;  Is it necessary to delete the pipe before exiting the script?  31&nbsp;  # ==&#62;  How could that be done?  32&nbsp;  33&nbsp;  34&nbsp;  exit 0</PRE></TD></TR></TABLE><HR></DIV><P>+</P><P><ANAME="PRIMES1"></A></P><P>St閜hane Chazelas used the following script to      demonstrate generating prime numbers without arrays.</P><P><ANAME="PRIMES00"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="PRIMES"></A><P><B>Example A-16. Generating prime numbers using the modulo operator</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# primes.sh: Generate prime numbers, without using arrays.   3&nbsp;# Script contributed by Stephane Chazelas.   4&nbsp;   5&nbsp;#  This does *not* use the classic "Sieve of Eratosthenes" algorithm,   6&nbsp;#+ but instead the more intuitive method of testing each candidate number   7&nbsp;#+ for factors (divisors), using the "%" modulo operator.   8&nbsp;   9&nbsp;  10&nbsp;LIMIT=1000                    # Primes, 2 ... 1000.  11&nbsp;  12&nbsp;Primes()  13&nbsp;{  14&nbsp; (( n = $1 + 1 ))             # Bump to next integer.  15&nbsp; shift                        # Next parameter in list.  16&nbsp;#  echo "_n=$n i=$i_"  17&nbsp;   18&nbsp; if (( n == LIMIT ))  19&nbsp; then echo $*  20&nbsp; return  21&nbsp; fi  22&nbsp;  23&nbsp; for i; do                    # "i" set to "@", previous values of $n.  24&nbsp;#   echo "-n=$n i=$i-"  25&nbsp;   (( i * i &#62; n )) &#38;&#38; break   # Optimization.  26&nbsp;   (( n % i )) &#38;&#38; continue    # Sift out non-primes using modulo operator.  27&nbsp;   Primes $n $@               # Recursion inside loop.  28&nbsp;   return  29&nbsp;   done  30&nbsp;  31&nbsp;   Primes $n $@ $n            # Recursion outside loop.  32&nbsp;                              # Successively accumulate positional parameters.  33&nbsp;                              # "$@" is the accumulating list of primes.  34&nbsp;}  35&nbsp;  36&nbsp;Primes 1  37&nbsp;  38&nbsp;exit $?  # Pipe output of the script to 'fmt' for prettier printing.  39&nbsp;  40&nbsp;#  Uncomment lines 16 and 24 to help figure out what is going on.  41&nbsp;  42&nbsp;#  Compare the speed of this algorithm for generating primes  43&nbsp;#+ with the Sieve of Eratosthenes (ex68.sh).  44&nbsp;  45&nbsp;  46&nbsp;#  Exercise: Rewrite this script without recursion, for faster execution.</PRE></TD></TR></TABLE><HR></DIV><P>+</P><P>Rick Boivie's revision of Jordi Sanfeliu's      <SPANCLASS="emphasis"><ICLASS="EMPHASIS">tree</I></SPAN> script.</P><DIVCLASS="EXAMPLE"><HR><ANAME="TREE"></A><P><B>Example A-17. <ICLASS="FIRSTTERM">tree</I>: Displaying a directory tree</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# tree.sh   3&nbsp;   4&nbsp;#  Written by Rick Boivie.   5&nbsp;#  Used with permission.   6&nbsp;#  This is a revised and simplified version of a script   7&nbsp;#+ by Jordi Sanfeliu (and patched by Ian Kjos).   8&nbsp;#  This script replaces the earlier version used in   9&nbsp;#+ previous releases of the Advanced Bash Scripting Guide.  10&nbsp;  11&nbsp;# ==&#62; Comments added by the author of this document.  12&nbsp;  13&nbsp;  14&nbsp;search () {  15&nbsp;for dir in `echo *`  16&nbsp;#  ==&#62; `echo *` lists all the files in current working directory,  17&nbsp;#+ ==&#62; without line breaks.  18&nbsp;#  ==&#62; Similar effect to for dir in *  19&nbsp;#  ==&#62; but "dir in `echo *`" will not handle filenames with blanks.  20&nbsp;do  21&nbsp;  if [ -d "$dir" ] ; then # ==&#62; If it is a directory (-d)...  22&nbsp;  zz=0                    # ==&#62; Temp variable, keeping track of directory level.  23&nbsp;  while [ $zz != $1 ]     # Keep track of inner nested loop.  24&nbsp;    do  25&nbsp;      echo -n "| "        # ==&#62; Display vertical connector symbol,  26&nbsp;                          # ==&#62; with 2 spaces &#38; no line feed in order to indent.  27&nbsp;      zz=`expr $zz + 1`   # ==&#62; Increment zz.  28&nbsp;    done  29&nbsp;  30&nbsp;    if [ -L "$dir" ] ; then # ==&#62; If directory is a symbolic link...  31&nbsp;      echo "+---$dir" `ls -l $dir | sed 's/^.*'$dir' //'`  32&nbsp;      # ==&#62; Display horiz. connector and list directory name, but...  33&nbsp;      # ==&#62; delete date/time part of long listing.  34&nbsp;    else  35&nbsp;      echo "+---$dir"       # ==&#62; Display horizontal connector symbol...  36&nbsp;      # ==&#62; and print directory name.  37&nbsp;      numdirs=`expr $numdirs + 1` # ==&#62; Increment directory count.  38&nbsp;      if cd "$dir" ; then         # ==&#62; If can move to subdirectory...  39&nbsp;        search `expr $1 + 1`      # with recursion ;-)  40&nbsp;        # ==&#62; Function calls itself.  41&nbsp;        cd ..  42&nbsp;      fi  43&nbsp;    fi  44&nbsp;  fi  45&nbsp;done  46&nbsp;}  47&nbsp;  48&nbsp;if [ $# != 0 ] ; then  49&nbsp;  cd $1 # move to indicated directory.  50&nbsp;  #else # stay in current directory  51&nbsp;fi  52&nbsp;  53&nbsp;echo "Initial directory = `pwd`"  54&nbsp;numdirs=0  55&nbsp;  56&nbsp;search 0  57&nbsp;echo "Total directories = $numdirs"  58&nbsp;  59&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>Patsie's version of a directory <ICLASS="FIRSTTERM">tree</I>      script.</P><DIVCLASS="EXAMPLE"><HR><ANAME="TREE2"></A><P><B>Example A-18. <ICLASS="FIRSTTERM">tree2</I>: Alternate directory tree script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# tree2.sh   3&nbsp;   4&nbsp;# Lightly modified/reformatted by ABS Guide author.   5&nbsp;# Included in ABS Guide with permission of script author (thanks!).   6&nbsp;   7&nbsp;## Recursive file/dirsize checking script, by Patsie   8&nbsp;##   9&nbsp;## This script builds a list of files/directories and their size (du -akx)  10&nbsp;## and processes this list to a human readable tree shape  11&nbsp;## The 'du -akx' is only as good as the permissions the owner has.  12&nbsp;## So preferably run as root* to get the best results, or use only on  13&nbsp;## directories for which you have read permissions. Anything you can't  14&nbsp;## read is not in the list.  15&nbsp;  16&nbsp;#* ABS Guide author advises caution when running scripts as root!  17&nbsp;  18&nbsp;  19&nbsp;##########  THIS IS CONFIGURABLE  ##########  20&nbsp;  21&nbsp;TOP=5                   # Top 5 biggest (sub)directories.  22&nbsp;MAXRECURS=5             # Max 5 subdirectories/recursions deep.  23&nbsp;E_BL=80                 # Blank line already returned.  24&nbsp;E_DIR=81                # Directory not specified.  25&nbsp;  26&nbsp;  27&nbsp;##########  DON'T CHANGE ANYTHING BELOW THIS LINE  ##########  28&nbsp;  29&nbsp;PID=$$                            # Our own process ID.  30&nbsp;SELF=`basename $0`                # Our own program name.  31&nbsp;TMP="/tmp/${SELF}.${PID}.tmp"     # Temporary 'du' result.  32&nbsp;  33&nbsp;# Convert number to dotted thousand.  34&nbsp;function dot { echo "            $*" |  35&nbsp;               sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' |  36&nbsp;               tail -c 12; }  37&nbsp;  38&nbsp;# Usage: tree &#60;recursion&#62; &#60;indent prefix&#62; &#60;min size&#62; &#60;directory&#62;  39&nbsp;function tree {  40&nbsp;  recurs="$1"           # How deep nested are we?  41&nbsp;  prefix="$2"           # What do we display before file/dirname?  42&nbsp;  minsize="$3"          # What is the minumum file/dirsize?  43&nbsp;  dirname="$4"          # Which directory are we checking?  44&nbsp;  45&nbsp;# Get ($TOP) biggest subdirs/subfiles from TMP file.  46&nbsp;  LIST=`egrep "[[:space:]]${dirname}/[^/]*$" "$TMP" |  47&nbsp;        awk '{if($1&#62;'$minsize') print;}' | sort -nr | head -$TOP`  48&nbsp;  [ -z "$LIST" ] &#38;&#38; return        # Empty list, then go back.  49&nbsp;  50&nbsp;  cnt=0  51&nbsp;  num=`echo "$LIST" | wc -l`      # How many entries in the list.  52&nbsp;  53&nbsp;  ## Main loop  54&nbsp;  echo "$LIST" | while read size name; do  55&nbsp;    ((cnt+=1))		          # Count entry number.  56&nbsp;    bname=`basename "$name"`      # We only need a basename of the entry.  57&nbsp;    [ -d "$name" ] &#38;&#38; bname="$bname/"  58&nbsp;                                  # If it's a directory, append a slash.  59&nbsp;    echo "`dot $size`$prefix +-$bname"  60&nbsp;                                  # Display the result.  61&nbsp;    #  Call ourself recursively if it's a directory  62&nbsp;    #+ and we're not nested too deep ($MAXRECURS).  63&nbsp;    #  The recursion goes up: $((recurs+1))  64&nbsp;    #  The prefix gets a space if it's the last entry,  65&nbsp;    #+ or a pipe if there are more entries.  66&nbsp;    #  The minimum file/dirsize becomes  67&nbsp;    #+ a tenth of his parent: $((size/10)).  68&nbsp;    # Last argument is the full directory name to check.  69&nbsp;    if [ -d "$name" -a $recurs -lt $MAXRECURS ]; then  70&nbsp;      [ $cnt -lt $num ] \  71&nbsp;        || (tree $((recurs+1)) "$prefix  " $((size/10)) "$name") \  72&nbsp;        &#38;&#38; (tree $((recurs+1)) "$prefix |" $((size/10)) "$name")  73&nbsp;    fi  74&nbsp;  done  75&nbsp;  76&nbsp;  [ $? -eq 0 ] &#38;&#38; echo "           $prefix"  77&nbsp;  # Every time we jump back add a 'blank' line.  78&nbsp;  return $E_BL  79&nbsp;  # We return 80 to tell we added a blank line already.  80&nbsp;}  81&nbsp;  82&nbsp;###                ###  83&nbsp;###  main program  ###  84&nbsp;###                ###  85&nbsp;  86&nbsp;rootdir="$@"  87&nbsp;[ -d "$rootdir" ] ||  88&nbsp;  { echo "$SELF: Usage: $SELF &#60;directory&#62;" &#62;&#38;2; exit $E_DIR; }  89&nbsp;  # We should be called with a directory name.  90&nbsp;  91&nbsp;echo "Building inventory list, please wait ..."  92&nbsp;     # Show "please wait" message.  93&nbsp;du -akx "$rootdir" 1&#62;"$TMP" 2&#62;/dev/null  94&nbsp;     # Build a temporary list of all files/dirs and their size

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -