contributed-scripts.html

来自「BASH Shell 编程 经典教程 《高级SHELL脚本编程》中文版」· HTML 代码 · 共 2,144 行 · 第 1/5 页

HTML
2,144
字号
306&nbsp;# Load initial array with contents of startup file.307&nbsp;initial=( `cat "$startfile" | sed -e '/#/d' | tr -d '\n' |\308&nbsp;sed -e 's/\./\. /g' -e 's/_/_ /g'` )309&nbsp;# Delete lines containing '#' comment character.310&nbsp;# Remove linefeeds and insert space between elements.311&nbsp;312&nbsp;clear          # Clear screen.313&nbsp;314&nbsp;echo #         Title315&nbsp;echo "======================="316&nbsp;echo "    $GENERATIONS generations"317&nbsp;echo "           of"318&nbsp;echo "\"Life in the Slow Lane\""319&nbsp;echo "======================="320&nbsp;321&nbsp;322&nbsp;# -------- Display first generation. --------323&nbsp;Gen0=`echo ${initial[@]}`324&nbsp;display "$Gen0"           # Display only.325&nbsp;echo; echo326&nbsp;echo "Generation $generation  -  $alive alive"327&nbsp;# -------------------------------------------328&nbsp;329&nbsp;330&nbsp;let "generation += 1"     # Increment generation count.331&nbsp;echo332&nbsp;333&nbsp;# ------- Display second generation. -------334&nbsp;Cur=`echo ${initial[@]}`335&nbsp;next_gen "$Cur"          # Update &#38; display.336&nbsp;# ------------------------------------------337&nbsp;338&nbsp;let "generation += 1"     # Increment generation count.339&nbsp;340&nbsp;# ------ Main loop for displaying subsequent generations ------341&nbsp;while [ "$generation" -le "$GENERATIONS" ]342&nbsp;do343&nbsp;  Cur="$avar"344&nbsp;  next_gen "$Cur"345&nbsp;  let "generation += 1"346&nbsp;done347&nbsp;# ==============================================================348&nbsp;349&nbsp;echo350&nbsp;351&nbsp;exit 0   # END352&nbsp;353&nbsp;354&nbsp;355&nbsp;# The grid in this script has a "boundary problem."356&nbsp;# The the top, bottom, and sides border on a void of dead cells.357&nbsp;# Exercise: Change the script to have the grid wrap around,358&nbsp;# +         so that the left and right sides will "touch,"      359&nbsp;# +         as will the top and bottom.360&nbsp;#361&nbsp;# Exercise: Create a new "gen0" file to seed this script.362&nbsp;#           Use a 12 x 16 grid, instead of the original 10 x 10 one.363&nbsp;#           Make the necessary changes to the script,364&nbsp;#+          so it will run with the altered file.365&nbsp;#366&nbsp;# Exercise: Modify this script so that it can determine the grid size367&nbsp;#+          from the "gen0" file, and set any variables necessary368&nbsp;#+          for the script to run.369&nbsp;#           This would make unnecessary any changes to variables370&nbsp;#+          in the script for an altered grid size.</PRE></FONT></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="GEN0DATA"></A><P><B>例子 A-11. <SPANCLASS="QUOTE">"Game of Life"</SPAN>的数据文件</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;# This is an example "generation 0" start-up file for "life.sh".  2&nbsp;# --------------------------------------------------------------  3&nbsp;#  The "gen0" file is a 10 x 10 grid using a period (.) for live cells,  4&nbsp;#+ and an underscore (_) for dead ones. We cannot simply use spaces  5&nbsp;#+ for dead cells in this file because of a peculiarity in Bash arrays.  6&nbsp;#  [Exercise for the reader: explain this.]  7&nbsp;#  8&nbsp;# Lines beginning with a '#' are comments, and the script ignores them.  9&nbsp;__.__..___ 10&nbsp;___._.____ 11&nbsp;____.___.. 12&nbsp;_._______. 13&nbsp;____._____ 14&nbsp;..__...___ 15&nbsp;____._____ 16&nbsp;___...____ 17&nbsp;__.._..___ 18&nbsp;_..___..__</PRE></FONT></TD></TR></TABLE><HR></DIV><P>+++</P><P>下面的两个脚本是由多伦多大学的Mark Moraes编写的.     请参考附件文件<SPANCLASS="QUOTE">"Moraes-COPYRIGHT"</SPAN>,     详细的指明了授权与约定. </P><DIVCLASS="EXAMPLE"><HR><ANAME="BEHEAD"></A><P><B>例子 A-12. <BCLASS="COMMAND">behead</B>: 去掉信件与新消息的头</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#! /bin/sh  2&nbsp;# Strips off the header from a mail/News message i.e. till the first  3&nbsp;# empty line  4&nbsp;# Mark Moraes, University of Toronto  5&nbsp;  6&nbsp;# ==&#62; These comments added by author of this document.  7&nbsp;  8&nbsp;if [ $# -eq 0 ]; then  9&nbsp;# ==&#62; If no command line args present, then works on file redirected to stdin. 10&nbsp;	sed -e '1,/^$/d' -e '/^[ 	]*$/d' 11&nbsp;	# --&#62; Delete empty lines and all lines until  12&nbsp;	# --&#62; first one beginning with white space. 13&nbsp;else 14&nbsp;# ==&#62; If command line args present, then work on files named. 15&nbsp;	for i do 16&nbsp;		sed -e '1,/^$/d' -e '/^[ 	]*$/d' $i 17&nbsp;		# --&#62; Ditto, as above. 18&nbsp;	done 19&nbsp;fi 20&nbsp; 21&nbsp;# ==&#62; Exercise: Add error checking and other options. 22&nbsp;# ==&#62; 23&nbsp;# ==&#62; Note that the small sed script repeats, except for the arg passed. 24&nbsp;# ==&#62; Does it make sense to embed it in a function? Why or why not?</PRE></FONT></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="FTPGET"></A><P><B>例子 A-13. <BCLASS="COMMAND">ftpget</B>: 通过ftp下载文件</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#! /bin/sh   2&nbsp;# $Id: ftpget,v 1.2 91/05/07 21:15:43 moraes Exp $   3&nbsp;# Script to perform batch anonymous ftp. Essentially converts a list of  4&nbsp;# of command line arguments into input to ftp.  5&nbsp;# ==&#62; This script is nothing but a shell wrapper around "ftp" . . .  6&nbsp;# Simple, and quick - written as a companion to ftplist   7&nbsp;# -h specifies the remote host (default prep.ai.mit.edu)   8&nbsp;# -d specifies the remote directory to cd to - you can provide a sequence   9&nbsp;# of -d options - they will be cd'ed to in turn. If the paths are relative,  10&nbsp;# make sure you get the sequence right. Be careful with relative paths -  11&nbsp;# there are far too many symlinks nowadays.   12&nbsp;# (default is the ftp login directory) 13&nbsp;# -v turns on the verbose option of ftp, and shows all responses from the  14&nbsp;# ftp server.   15&nbsp;# -f remotefile[:localfile] gets the remote file into localfile  16&nbsp;# -m pattern does an mget with the specified pattern. Remember to quote  17&nbsp;# shell characters.   18&nbsp;# -c does a local cd to the specified directory 19&nbsp;# For example,  20&nbsp;# 	ftpget -h expo.lcs.mit.edu -d contrib -f xplaces.shar:xplaces.sh \ 21&nbsp;#		-d ../pub/R3/fixes -c ~/fixes -m 'fix*'  22&nbsp;# will get xplaces.shar from ~ftp/contrib on expo.lcs.mit.edu, and put it in 23&nbsp;# xplaces.sh in the current working directory, and get all fixes from 24&nbsp;# ~ftp/pub/R3/fixes and put them in the ~/fixes directory.  25&nbsp;# Obviously, the sequence of the options is important, since the equivalent 26&nbsp;# commands are executed by ftp in corresponding order 27&nbsp;# 28&nbsp;# Mark Moraes &#60;moraes@csri.toronto.edu&#62;, Feb 1, 1989  29&nbsp;# 30&nbsp; 31&nbsp; 32&nbsp;# ==&#62; These comments added by author of this document. 33&nbsp; 34&nbsp;# PATH=/local/bin:/usr/ucb:/usr/bin:/bin 35&nbsp;# export PATH 36&nbsp;# ==&#62; Above 2 lines from original script probably superfluous. 37&nbsp; 38&nbsp;E_BADARGS=65 39&nbsp; 40&nbsp;TMPFILE=/tmp/ftp.$$ 41&nbsp;# ==&#62; Creates temp file, using process id of script ($$) 42&nbsp;# ==&#62; to construct filename. 43&nbsp; 44&nbsp;SITE=`domainname`.toronto.edu 45&nbsp;# ==&#62; 'domainname' similar to 'hostname' 46&nbsp;# ==&#62; May rewrite this to parameterize this for general use. 47&nbsp; 48&nbsp;usage="Usage: $0 [-h remotehost] [-d remotedirectory]... [-f remfile:localfile]... \ 49&nbsp;		[-c localdirectory] [-m filepattern] [-v]" 50&nbsp;ftpflags="-i -n" 51&nbsp;verbflag= 52&nbsp;set -f 		# So we can use globbing in -m 53&nbsp;set x `getopt vh:d:c:m:f: $*` 54&nbsp;if [ $? != 0 ]; then 55&nbsp;	echo $usage 56&nbsp;	exit $E_BADARGS 57&nbsp;fi 58&nbsp;shift 59&nbsp;trap 'rm -f ${TMPFILE} ; exit' 0 1 2 3 15 60&nbsp;# ==&#62; Delete tempfile in case of abnormal exit from script. 61&nbsp;echo "user anonymous ${USER-gnu}@${SITE} &#62; ${TMPFILE}" 62&nbsp;# ==&#62; Added quotes (recommended in complex echoes). 63&nbsp;echo binary &#62;&#62; ${TMPFILE} 64&nbsp;for i in $*   # ==&#62; Parse command line args. 65&nbsp;do 66&nbsp;	case $i in 67&nbsp;	-v) verbflag=-v; echo hash &#62;&#62; ${TMPFILE}; shift;; 68&nbsp;	-h) remhost=$2; shift 2;; 69&nbsp;	-d) echo cd $2 &#62;&#62; ${TMPFILE};  70&nbsp;	    if [ x${verbflag} != x ]; then 71&nbsp;	        echo pwd &#62;&#62; ${TMPFILE}; 72&nbsp;	    fi; 73&nbsp;	    shift 2;; 74&nbsp;	-c) echo lcd $2 &#62;&#62; ${TMPFILE}; shift 2;; 75&nbsp;	-m) echo mget "$2" &#62;&#62; ${TMPFILE}; shift 2;; 76&nbsp;	-f) f1=`expr "$2" : "\([^:]*\).*"`; f2=`expr "$2" : "[^:]*:\(.*\)"`; 77&nbsp;	    echo get ${f1} ${f2} &#62;&#62; ${TMPFILE}; shift 2;; 78&nbsp;	--) shift; break;; 79&nbsp;	esac 80&nbsp;        # ==&#62; 'lcd' and 'mget' are ftp commands. See "man ftp" . . . 81&nbsp;done 82&nbsp;if [ $# -ne 0 ]; then 83&nbsp;	echo $usage 84&nbsp;	exit $E_BADARGS 85&nbsp;        # ==&#62; Changed from "exit 2" to conform with style standard. 86&nbsp;fi 87&nbsp;if [ x${verbflag} != x ]; then 88&nbsp;	ftpflags="${ftpflags} -v" 89&nbsp;fi 90&nbsp;if [ x${remhost} = x ]; then 91&nbsp;	remhost=prep.ai.mit.edu 92&nbsp;	# ==&#62; Change to match appropriate ftp site. 93&nbsp;fi 94&nbsp;echo quit &#62;&#62; ${TMPFILE} 95&nbsp;# ==&#62; All commands saved in tempfile. 96&nbsp; 97&nbsp;ftp ${ftpflags} ${remhost} &#60; ${TMPFILE} 98&nbsp;# ==&#62; Now, tempfile batch processed by ftp. 99&nbsp;100&nbsp;rm -f ${TMPFILE}101&nbsp;# ==&#62; Finally, tempfile deleted (you may wish to copy it to a logfile).102&nbsp;103&nbsp;104&nbsp;# ==&#62; Exercises:105&nbsp;# ==&#62; ---------106&nbsp;# ==&#62; 1) Add error checking.107&nbsp;# ==&#62; 2) Add bells &#38; whistles.</PRE></FONT></TD></TR></TABLE><HR></DIV><P>+</P><P>Antek Sawicki捐献了下面的脚本, 这个脚本非常聪明的使用了参数替换操作符, 		我们在<AHREF="parameter-substitution.html">Section 9.3</A>中讨论了参数替换操作符. </P><DIVCLASS="EXAMPLE"><HR><ANAME="PW"></A><P><B>例子 A-14. <BCLASS="COMMAND">password</B>: 产生随机的8个字符的密码</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#!/bin/bash  2&nbsp;# May need to be invoked with  #!/bin/bash2  on older machines.  3&nbsp;#  4&nbsp;# Random password generator for Bash 2.x by Antek Sawicki &#60;tenox@tenox.tc&#62;,  5&nbsp;# who generously gave permission to the document author to use it here.  6&nbsp;#  7&nbsp;# ==&#62; Comments added by document author ==&#62;  8&nbsp;  9&nbsp; 10&nbsp;MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 11&nbsp;# ==&#62; Password will consist of alphanumeric characters. 12&nbsp;LENGTH="8" 13&nbsp;# ==&#62; May change 'LENGTH' for longer password. 14&nbsp; 15&nbsp; 16&nbsp;while [ "${n:=1}" -le "$LENGTH" ] 17&nbsp;# ==&#62; Recall that := is "default substitution" operator. 18&nbsp;# ==&#62; So, if 'n' has not been initialized, set it to 1. 19&nbsp;do 20&nbsp;	PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}" 21&nbsp;	# ==&#62; Very clever, but tricky. 22&nbsp; 23&nbsp;	# ==&#62; Starting from the innermost nesting... 24&nbsp;	# ==&#62; ${#MATRIX} returns length of array MATRIX. 25&nbsp; 26&nbsp;	# ==&#62; $RANDOM%${#MATRIX} returns random number between 1 27&nbsp;	# ==&#62; and [length of MATRIX] - 1. 28&nbsp; 29&nbsp;	# ==&#62; ${MATRIX:$(($RANDOM%${#MATRIX})):1} 30&nbsp;	# ==&#62; returns expansion of MATRIX at random position, by length 1.  31&nbsp;	# ==&#62; See {var:pos:len} parameter substitution in Chapter 9. 32&nbsp;	# ==&#62; and the associated examples. 33&nbsp; 34&nbsp;	# ==&#62; PASS=... simply pastes this result onto previous PASS (concatenation). 35&nbsp; 36&nbsp;	# ==&#62; To visualize this more clearly, uncomment the following line 37&nbsp;	#                 echo "$PASS" 38&nbsp;	# ==&#62; to see PASS being built up, 39&nbsp;	# ==&#62; one character at a time, each iteration of the loop. 40&nbsp; 41&nbsp;	let n+=1 42&nbsp;	# ==&#62; Increment 'n' for next pass. 43&nbsp;done 44&nbsp; 45&nbsp;echo "$PASS"      # ==&#62; Or, redirect to a file, as desired. 46&nbsp; 47&nbsp;exit 0</PRE></FONT></TD></TR></TABLE><HR></DIV><P>+</P><P><ANAME="ZFIFO"></A>James R. Van Zandt捐献了这个脚本,       使用命名管道, 用他的话来说, <SPANCLASS="QUOTE">"引用与转义的真正练习"</SPAN>. </P><DIVCLASS="EXAMPLE"><HR><ANAME="FIFO"></A><P><B>例子 A-15. <BCLASS="COMMAND">fifo</B>: 使用命名管道来做每日的备份</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><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;

⌨️ 快捷键说明

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