contributed-scripts.html

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

HTML
2,144
字号
  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; 31&nbsp;  exit 0</PRE></FONT></TD></TR></TABLE><HR></DIV><P>+</P><P>Stephane Chazelas捐献了这个脚本, 用来展示如何不使用数组来产生素数</P><DIVCLASS="EXAMPLE"><HR><ANAME="PRIMES"></A><P><B>例子 A-16. 使用模操作符来产生素数</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><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 uses 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" gets 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 0 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;#  Exercise: Rewrite this script without recursion, for faster execution.</PRE></FONT></TD></TR></TABLE><HR></DIV><P>+</P><P>这是Jordi Sanfeliu的<EM>tree</EM>脚本的升级版, 由Rick Boivie编写. </P><DIVCLASS="EXAMPLE"><HR><ANAME="TREE"></A><P><B>例子 A-17. <BCLASS="COMMAND">tree</B>: 显示目录树</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><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></FONT></TD></TR></TABLE><HR></DIV><P>经过Noah Friedman的授权, 他的<EM>string			function</EM>脚本可以在本书中使用, 		这个脚本本质上就是复制了一些C库的字符串操作函数.       </P><DIVCLASS="EXAMPLE"><HR><ANAME="STRING"></A><P><B>例子 A-18. <BCLASS="COMMAND">string functions</B>: C风格的字符串函数</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#!/bin/bash  2&nbsp;  3&nbsp;# string.bash --- bash emulation of string(3) library routines  4&nbsp;# Author: Noah Friedman &#60;friedman@prep.ai.mit.edu&#62;  5&nbsp;# ==&#62;     Used with his kind permission in this document.  6&nbsp;# Created: 1992-07-01  7&nbsp;# Last modified: 1993-09-29  8&nbsp;# Public domain  9&nbsp; 10&nbsp;# Conversion to bash v2 syntax done by Chet Ramey 11&nbsp; 12&nbsp;# Commentary: 13&nbsp;# Code: 14&nbsp; 15&nbsp;#:docstring strcat: 16&nbsp;# Usage: strcat s1 s2 17&nbsp;# 18&nbsp;# Strcat appends the value of variable s2 to variable s1.  19&nbsp;# 20&nbsp;# Example: 21&nbsp;#    a="foo" 22&nbsp;#    b="bar" 23&nbsp;#    strcat a b 24&nbsp;#    echo $a 25&nbsp;#    =&#62; foobar 26&nbsp;# 27&nbsp;#:end docstring: 28&nbsp; 29&nbsp;###;;;autoload   ==&#62; Autoloading of function commented out. 30&nbsp;function strcat () 31&nbsp;{ 32&nbsp;    local s1_val s2_val 33&nbsp; 34&nbsp;    s1_val=${!1}                        # indirect variable expansion 35&nbsp;    s2_val=${!2} 36&nbsp;    eval "$1"=\'"${s1_val}${s2_val}"\' 37&nbsp;    # ==&#62; eval $1='${s1_val}${s2_val}' avoids problems, 38&nbsp;    # ==&#62; if one of the variables contains a single quote. 39&nbsp;} 40&nbsp; 41&nbsp;#:docstring strncat: 42&nbsp;# Usage: strncat s1 s2 $n 43&nbsp;#  44&nbsp;# Line strcat, but strncat appends a maximum of n characters from the value 45&nbsp;# of variable s2.  It copies fewer if the value of variabl s2 is shorter 46&nbsp;# than n characters.  Echoes result on stdout. 47&nbsp;# 48&nbsp;# Example: 49&nbsp;#    a=foo 50&nbsp;#    b=barbaz 51&nbsp;#    strncat a b 3 52&nbsp;#    echo $a 53&nbsp;#    =&#62; foobar 54&nbsp;# 55&nbsp;#:end docstring: 56&nbsp; 57&nbsp;###;;;autoload 58&nbsp;function strncat () 59&nbsp;{ 60&nbsp;    local s1="$1" 61&nbsp;    local s2="$2" 62&nbsp;    local -i n="$3" 63&nbsp;    local s1_val s2_val 64&nbsp; 65&nbsp;    s1_val=${!s1}                       # ==&#62; indirect variable expansion 66&nbsp;    s2_val=${!s2} 67&nbsp; 68&nbsp;    if [ ${#s2_val} -gt ${n} ]; then 69&nbsp;       s2_val=${s2_val:0:$n}            # ==&#62; substring extraction 70&nbsp;    fi 71&nbsp; 72&nbsp;    eval "$s1"=\'"${s1_val}${s2_val}"\' 73&nbsp;    # ==&#62; eval $1='${s1_val}${s2_val}' avoids problems, 74&nbsp;    # ==&#62; if one of the variables contains a single quote. 75&nbsp;} 76&nbsp; 77&nbsp;#:docstring strcmp: 78&nbsp;# Usage: strcmp $s1 $s2 79&nbsp;# 80&nbsp;# Strcmp compares its arguments and returns an integer less than, equal to, 81&nbsp;# or greater than zero, depending on whether string s1 is lexicographically 82&nbsp;# less than, equal to, or greater than string s2. 83&nbsp;#:end docstring: 84&nbsp; 85&nbsp;###;;;autoload 86&nbsp;function strcmp () 87&nbsp;{ 88&nbsp;    [ "$1" = "$2" ] &#38;&#38; return 0 89&nbsp; 90&nbsp;    [ "${1}" '&#60;' "${2}" ] &#62; /dev/null &#38;&#38; return -1 91&nbsp; 92&nbsp;    return 1 93&nbsp;} 94&nbsp; 95&nbsp;#:docstring strncmp: 96&nbsp;# Usage: strncmp $s1 $s2 $n 97&nbsp;#  98&nbsp;# Like strcmp, but makes the comparison by examining a maximum of n 99&nbsp;# characters (n less than or equal to zero yields equality).100&nbsp;#:end docstring:101&nbsp;102&nbsp;###;;;autoload103&nbsp;function strncmp ()104&nbsp;{105&nbsp;    if [ -z "${3}" -o "${3}" -le "0" ]; then106&nbsp;       return 0107&nbsp;    fi108&nbsp;   109&nbsp;    if [ ${3} -ge ${#1} -a ${3} -ge ${#2} ]; then110&nbsp;       strcmp "$1" "$2"111&nbsp;       return $?112&nbsp;    else113&nbsp;       s1=${1:0:$3}114&nbsp;       s2=${2:0:$3}115&nbsp;       strcmp $s1 $s2116&nbsp;       return $?117&nbsp;    fi118&nbsp;}119&nbsp;120&nbsp;#:docstring strlen:121&nbsp;# Usage: strlen s122&nbsp;#123&nbsp;# Strlen returns the number of characters in string literal s.124&nbsp;#:end docstring:125&nbsp;126&nbsp;###;;;autoload127&nbsp;function strlen ()128&nbsp;{129&nbsp;    eval echo "\${#${1}}"130&nbsp;    # ==&#62; Returns the length of the value of the variable131&nbsp;    # ==&#62; whose name is passed as an argument.132&nbsp;}133&nbsp;134&nbsp;#:docstring strspn:135&nbsp;# Usage: strspn $s1 $s2136&nbsp;# 137&nbsp;# Strspn returns the length of the maximum initial segment of string s1,138&nbsp;# which consists entirely of characters from string s2.139&nbsp;#:end docstring:140&nbsp;141&nbsp;###;;;autoload142&nbsp;function strspn ()143&nbsp;{144&nbsp;    # Unsetting IFS allows whitespace to be handled as normal chars. 145&nbsp;    local IFS=146&nbsp;    local result="${1%%[!${2}]*}"147&nbsp; 148&nbsp;    echo ${#result}149&nbsp;}150&nbsp;151&nbsp;#:docstring strcspn:152&nbsp;# Usage: strcspn $s1 $s2153&nbsp;#154&nbsp;# Strcspn returns the length of the maximum initial segment of string s1,155&nbsp;# which consists entirely of characters not from string s2.156&nbsp;#:end docstring:157&nbsp;158&nbsp;###;;;autoload159&nbsp;function strcspn ()160&nbsp;{161&nbsp;    # Unsetting IFS allows whitspace to be handled as normal chars. 162&nbsp;    local IFS=163&nbsp;    local result="${1%%[${2}]*}"164&nbsp; 165&nbsp;    echo ${#result}166&nbsp;}167&nbsp;168&nbsp;#:docstring strstr:169&nbsp;# Usage: strstr s1 s2170&nbsp;# 171&nbsp;# Strstr echoes a substring starting at the first occurrence of string s2 in172&nbsp;# string s1, or nothing if s2 does not occur in the string.  If s2 points to173&nbsp;# a string of zero length, strstr echoes s1.174&nbsp;#:end docstring:175&nbsp;176&nbsp;###;;;autoload177&nbsp;function strstr ()178&nbsp;{179&nbsp;    # if s2 points to a string of zero length, strstr echoes s1180&nbsp;    [ ${#2} -eq 0 ] &#38;&#38; { echo "$1" ; return 0; }181&nbsp;182&nbsp;    # strstr echoes nothing if s2 does not occur in s1183&nbsp;    case "$1" in184&nbsp;    *$2*) ;;185&nbsp;    *) return 1;;186&nbsp;    esac187&nbsp;188&nbsp;    # use the pattern matching code to strip off the match and everything189&nbsp;    # following it190&nbsp;    first=${1/$2*/}191&nbsp;192&nbsp;    # then strip off the first unmatched portion of the string193&nbsp;    echo "${1##$first}"194&nbsp;}195&nbsp;196&nbsp;#:docstring strtok:197&nbsp;# Usage: strtok s1 s2198&nbsp;#199&nbsp;# Strtok considers the string s1 to consist of a sequence of zero or more200&nbsp;# text tokens separated by spans of one or more characters from the201&nbsp;# separator string s2.  The first call (with a non-empty string s1202&nbsp;# specified) echoes a string consisting of the first token on stdout. The203&nbsp

⌨️ 快捷键说明

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