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

📄 moreadv.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 HTML
📖 第 1 页 / 共 2 页
字号:
  16&nbsp;echo &#62;&#62;logfile  17&nbsp;echo &#62;&#62;logfile  18&nbsp;  19&nbsp;exit 0  20&nbsp;  21&nbsp;#  Note:  22&nbsp;#  ----  23&nbsp;#  As Frank Wang points out,  24&nbsp;#+ unmatched quotes (either single or double quotes) in the source file  25&nbsp;#+ may give xargs indigestion.  26&nbsp;#  27&nbsp;#  He suggests the following substitution for line 15:  28&nbsp;#     tail -$LINES /var/log/messages | tr -d "\"'" | xargs | fmt -s &#62;&#62;logfile  29&nbsp;  30&nbsp;  31&nbsp;  32&nbsp;#  Exercise:  33&nbsp;#  --------  34&nbsp;#  Modify this script to track changes in /var/log/messages at intervals  35&nbsp;#+ of 20 minutes.  36&nbsp;#  Hint: Use the "watch" command. </PRE></TD></TR></TABLE><HR></DIV><P><AHREF="moreadv.html#CURLYBRACKETSREF">As in	      <BCLASS="COMMAND">find</B></A>, a curly bracket	      pair serves as a placeholder for replacement text.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX42"></A><P><B>Example 12-6. Copying files in current directory to another</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# copydir.sh   3&nbsp;   4&nbsp;#  Copy (verbose) all files in current directory ($PWD)   5&nbsp;#+ to directory specified on command line.   6&nbsp;   7&nbsp;E_NOARGS=65   8&nbsp;   9&nbsp;if [ -z "$1" ]   # Exit if no argument given.  10&nbsp;then  11&nbsp;  echo "Usage: `basename $0` directory-to-copy-to"  12&nbsp;  exit $E_NOARGS  13&nbsp;fi    14&nbsp;  15&nbsp;ls . | xargs -i -t cp ./{} $1  16&nbsp;#            ^^ ^^      ^^  17&nbsp;#  -t is "verbose" (output command line to stderr) option.  18&nbsp;#  -i is "replace strings" option.  19&nbsp;#  {} is a placeholder for output text.  20&nbsp;#  This is similar to the use of a curly bracket pair in "find."  21&nbsp;#  22&nbsp;#  List the files in current directory (ls .),  23&nbsp;#+ pass the output of "ls" as arguments to "xargs" (-i -t options),  24&nbsp;#+ then copy (cp) these arguments ({}) to new directory ($1).    25&nbsp;#  26&nbsp;#  The net result is the exact equivalent of  27&nbsp;#+   cp * $1  28&nbsp;#+ unless any of the filenames has embedded "whitespace" characters.  29&nbsp;  30&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="KILLBYNAME"></A><P><B>Example 12-7. Killing processes by name</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# kill-byname.sh: Killing processes by name.   3&nbsp;# Compare this script with kill-process.sh.   4&nbsp;   5&nbsp;#  For instance,   6&nbsp;#+ try "./kill-byname.sh xterm" --   7&nbsp;#+ and watch all the xterms on your desktop disappear.   8&nbsp;   9&nbsp;#  Warning:  10&nbsp;#  -------  11&nbsp;#  This is a fairly dangerous script.  12&nbsp;#  Running it carelessly (especially as root)  13&nbsp;#+ can cause data loss and other undesirable effects.  14&nbsp;  15&nbsp;E_BADARGS=66  16&nbsp;  17&nbsp;if test -z "$1"  # No command line arg supplied?  18&nbsp;then  19&nbsp;  echo "Usage: `basename $0` Process(es)_to_kill"  20&nbsp;  exit $E_BADARGS  21&nbsp;fi  22&nbsp;  23&nbsp;  24&nbsp;PROCESS_NAME="$1"  25&nbsp;ps ax | grep "$PROCESS_NAME" | awk '{print $1}' | xargs -i kill {} 2&#38;&#62;/dev/null  26&nbsp;#                                                       ^^      ^^  27&nbsp;  28&nbsp;# -----------------------------------------------------------  29&nbsp;# Notes:  30&nbsp;# -i is the "replace strings" option to xargs.  31&nbsp;# The curly brackets are the placeholder for the replacement.  32&nbsp;# 2&#38;&#62;/dev/null suppresses unwanted error messages.  33&nbsp;# -----------------------------------------------------------  34&nbsp;  35&nbsp;exit $?</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="WF2"></A><P><B>Example 12-8. <BCLASS="COMMAND">Word frequency analysis</B>		using <BCLASS="COMMAND">xargs</B></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# wf2.sh: Crude word frequency analysis on a text file.   3&nbsp;   4&nbsp;# Uses 'xargs' to decompose lines of text into single words.   5&nbsp;# Compare this example to the "wf.sh" script later on.   6&nbsp;   7&nbsp;   8&nbsp;# Check for input file on command line.   9&nbsp;ARGS=1  10&nbsp;E_BADARGS=65  11&nbsp;E_NOFILE=66  12&nbsp;  13&nbsp;if [ $# -ne "$ARGS" ]  14&nbsp;# Correct number of arguments passed to script?  15&nbsp;then  16&nbsp;  echo "Usage: `basename $0` filename"  17&nbsp;  exit $E_BADARGS  18&nbsp;fi  19&nbsp;  20&nbsp;if [ ! -f "$1" ]       # Check if file exists.  21&nbsp;then  22&nbsp;  echo "File \"$1\" does not exist."  23&nbsp;  exit $E_NOFILE  24&nbsp;fi  25&nbsp;  26&nbsp;  27&nbsp;  28&nbsp;########################################################  29&nbsp;cat "$1" | xargs -n1 | \  30&nbsp;#  List the file, one word per line.   31&nbsp;tr A-Z a-z | \  32&nbsp;#  Shift characters to lowercase.  33&nbsp;sed -e 's/\.//g'  -e 's/\,//g' -e 's/ /\  34&nbsp;/g' | \  35&nbsp;#  Filter out periods and commas, and  36&nbsp;#+ change space between words to linefeed,  37&nbsp;sort | uniq -c | sort -nr  38&nbsp;#  Finally prefix occurrence count and sort numerically.  39&nbsp;########################################################  40&nbsp;  41&nbsp;#  This does the same job as the "wf.sh" example,  42&nbsp;#+ but a bit more ponderously, and it runs more slowly (why?).  43&nbsp;  44&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV></DD><DT><ANAME="EXPRREF"></A><TTCLASS="USERINPUT"><B>expr</B></TT></DT><DD><P>All-purpose expression evaluator:	      Concatenates and evaluates the arguments according	      to the operation given (arguments must be separated	      by spaces). Operations may be arithmetic, comparison,	      string, or logical.</P><DIVCLASS="VARIABLELIST"><DL><DT><TTCLASS="USERINPUT"><B>expr 3 + 5</B></TT></DT><DD><P>returns <TTCLASS="LITERAL">8</TT></P></DD><DT><TTCLASS="USERINPUT"><B>expr 5 % 3</B></TT></DT><DD><P>returns 2</P></DD><DT><TTCLASS="USERINPUT"><B>expr 1 / 0</B></TT></DT><DD><P>returns the error message, <ICLASS="EMPHASIS">expr: division by		    zero</I></P><P>Illegal arithmetic operations not allowed.</P></DD><DT><TTCLASS="USERINPUT"><B>expr 5 \* 3</B></TT></DT><DD><P>returns 15</P><P>The multiplication operator		  must be escaped when used in an arithmetic expression		  with <BCLASS="COMMAND">expr</B>.</P></DD><DT><TTCLASS="USERINPUT"><B>y=`expr $y + 1`</B></TT></DT><DD><P>Increment a variable, with the same effect		    as <TTCLASS="USERINPUT"><B>let y=y+1</B></TT> and		    <TTCLASS="USERINPUT"><B>y=$(($y+1))</B></TT>. This is an		    example of <AHREF="arithexp.html#ARITHEXPREF">arithmetic		    expansion</A>.</P></DD><DT><ANAME="EXPEXTRSUB"></A><TTCLASS="USERINPUT"><B>z=`expr substr		$string $position $length`</B></TT></DT><DD><P>Extract substring of $length characters, starting		    at $position.</P></DD></DL></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="EX45"></A><P><B>Example 12-9. Using <BCLASS="COMMAND">expr</B></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;# Demonstrating some of the uses of 'expr'   4&nbsp;# =======================================   5&nbsp;   6&nbsp;echo   7&nbsp;   8&nbsp;# Arithmetic Operators   9&nbsp;# ---------- ---------  10&nbsp;  11&nbsp;echo "Arithmetic Operators"  12&nbsp;echo  13&nbsp;a=`expr 5 + 3`  14&nbsp;echo "5 + 3 = $a"  15&nbsp;  16&nbsp;a=`expr $a + 1`  17&nbsp;echo  18&nbsp;echo "a + 1 = $a"  19&nbsp;echo "(incrementing a variable)"  20&nbsp;  21&nbsp;a=`expr 5 % 3`  22&nbsp;# modulo  23&nbsp;echo  24&nbsp;echo "5 mod 3 = $a"  25&nbsp;  26&nbsp;echo  27&nbsp;echo  28&nbsp;  29&nbsp;# Logical Operators  30&nbsp;# ------- ---------  31&nbsp;  32&nbsp;#  Returns 1 if true, 0 if false,  33&nbsp;#+ opposite of normal Bash convention.  34&nbsp;  35&nbsp;echo "Logical Operators"  36&nbsp;echo  37&nbsp;  38&nbsp;x=24  39&nbsp;y=25  40&nbsp;b=`expr $x = $y`         # Test equality.  41&nbsp;echo "b = $b"            # 0  ( $x -ne $y )  42&nbsp;echo  43&nbsp;  44&nbsp;a=3  45&nbsp;b=`expr $a \&#62; 10`  46&nbsp;echo 'b=`expr $a \&#62; 10`, therefore...'  47&nbsp;echo "If a &#62; 10, b = 0 (false)"  48&nbsp;echo "b = $b"            # 0  ( 3 ! -gt 10 )  49&nbsp;echo  50&nbsp;  51&nbsp;b=`expr $a \&#60; 10`  52&nbsp;echo "If a &#60; 10, b = 1 (true)"  53&nbsp;echo "b = $b"            # 1  ( 3 -lt 10 )  54&nbsp;echo  55&nbsp;# Note escaping of operators.  56&nbsp;  57&nbsp;b=`expr $a \&#60;= 3`  58&nbsp;echo "If a &#60;= 3, b = 1 (true)"  59&nbsp;echo "b = $b"            # 1  ( 3 -le 3 )  60&nbsp;# There is also a "\&#62;=" operator (greater than or equal to).  61&nbsp;  62&nbsp;  63&nbsp;echo  64&nbsp;echo  65&nbsp;  66&nbsp;  67&nbsp;  68&nbsp;# String Operators  69&nbsp;# ------ ---------  70&nbsp;  71&nbsp;echo "String Operators"  72&nbsp;echo  73&nbsp;  74&nbsp;a=1234zipper43231  75&nbsp;echo "The string being operated upon is \"$a\"."  76&nbsp;  77&nbsp;# length: length of string  78&nbsp;b=`expr length $a`  79&nbsp;echo "Length of \"$a\" is $b."  80&nbsp;  81&nbsp;# index: position of first character in substring  82&nbsp;#        that matches a character in string  83&nbsp;b=`expr index $a 23`  84&nbsp;echo "Numerical position of first \"2\" in \"$a\" is \"$b\"."  85&nbsp;  86&nbsp;# substr: extract substring, starting position &#38; length specified  87&nbsp;b=`expr substr $a 2 6`  88&nbsp;echo "Substring of \"$a\", starting at position 2,\  89&nbsp;and 6 chars long is \"$b\"."  90&nbsp;  91&nbsp;  92&nbsp;#  The default behavior of the 'match' operations is to  93&nbsp;#+ search for the specified match at the ***beginning*** of the string.  94&nbsp;#  95&nbsp;#        uses Regular Expressions  96&nbsp;b=`expr match "$a" '[0-9]*'`               #  Numerical count.  97&nbsp;echo Number of digits at the beginning of \"$a\" is $b.  98&nbsp;b=`expr match "$a" '\([0-9]*\)'`           #  Note that escaped parentheses  99&nbsp;#                   ==      ==              + trigger substring match. 100&nbsp;echo "The digits at the beginning of \"$a\" are \"$b\"." 101&nbsp; 102&nbsp;echo 103&nbsp; 104&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="IMPORTANT"><TABLECLASS="IMPORTANT"WIDTH="90%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/important.png"HSPACE="5"ALT="Important"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>The <AHREF="special-chars.html#NULLREF">:</A> operator	      can substitute for <BCLASS="COMMAND">match</B>. For example,	      <TTCLASS="USERINPUT"><B>b=`expr $a : [0-9]*`</B></TT> is the	      exact equivalent of <TTCLASS="USERINPUT"><B>b=`expr match $a	      [0-9]*`</B></TT> in the above listing.</P><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;echo   4&nbsp;echo "String operations using \"expr \$string : \" construct"   5&nbsp;echo "==================================================="   6&nbsp;echo   7&nbsp;   8&nbsp;a=1234zipper5FLIPPER43231   9&nbsp;  10&nbsp;echo "The string being operated upon is \"`expr "$a" : '\(.*\)'`\"."  11&nbsp;#     Escaped parentheses grouping operator.            ==  ==  12&nbsp;  13&nbsp;#       ***************************  14&nbsp;#+          Escaped parentheses  15&nbsp;#+           match a substring  16&nbsp;#       ***************************  17&nbsp;  18&nbsp;  19&nbsp;#  If no escaped parentheses...  20&nbsp;#+ then 'expr' converts the string operand to an integer.  21&nbsp;  22&nbsp;echo "Length of \"$a\" is `expr "$a" : '.*'`."   # Length of string  23&nbsp;  24&nbsp;echo "Number of digits at the beginning of \"$a\" is `expr "$a" : '[0-9]*'`."  25&nbsp;  26&nbsp;# ------------------------------------------------------------------------- #  27&nbsp;  28&nbsp;echo  29&nbsp;  30&nbsp;echo "The digits at the beginning of \"$a\" are `expr "$a" : '\([0-9]*\)'`."  31&nbsp;#                                                             ==      ==  32&nbsp;echo "The first 7 characters of \"$a\" are `expr "$a" : '\(.......\)'`."  33&nbsp;#         =====                                          ==       ==  34&nbsp;# Again, escaped parentheses force a substring match.  35&nbsp;#  36&nbsp;echo "The last 7 characters of \"$a\" are `expr "$a" : '.*\(.......\)'`."  37&nbsp;#         ====                  end of string operator  ^^  38&nbsp;#  (actually means skip over one or more of any characters until specified  39&nbsp;#+  substring)  40&nbsp;  41&nbsp;echo  42&nbsp;  43&nbsp;exit 0</PRE></TD></TR></TABLE></P></TD></TR></TABLE></DIV></DD></DL></DIV><P>The above script illustrates how	      <BCLASS="COMMAND">expr</B> uses the <ICLASS="EMPHASIS">escaped	      parentheses -- \( ... \) --</I> grouping operator	      in tandem with <AHREF="regexp.html#REGEXREF">regular	      expression</A> parsing to match a substring.	      Here is a another example, this time from <SPANCLASS="QUOTE">"real	      life."</SPAN>	        <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# Strip the whitespace from the beginning and end.   2&nbsp;LRFDATE=`expr "$LRFDATE" : '[[:space:]]*\(.*\)[[:space:]]*$'`   3&nbsp;   4&nbsp;#  From Peter Knowles' "booklistgen.sh" script   5&nbsp;#+ for converting files to Sony Librie format.   6&nbsp;#  (http://booklistgensh.peterknowles.com)</PRE></TD></TR></TABLE>	      </P><P><AHREF="wrapper.html#PERLREF">Perl</A>,	      <AHREF="sedawk.html#SEDREF">sed</A>, and <AHREF="awk.html#AWKREF">awk</A> have far superior string	      parsing facilities.  A short <BCLASS="COMMAND">sed</B> or	      <BCLASS="COMMAND">awk</B> <SPANCLASS="QUOTE">"subroutine"</SPAN> within	      a script (see <AHREF="wrapper.html">Section 33.2</A>) is an attractive	      alternative to <BCLASS="COMMAND">expr</B>.</P><P>See <AHREF="string-manipulation.html">Section 9.2</A> for more on              using <BCLASS="COMMAND">expr</B> in string operations.</P></DIV><H3CLASS="FOOTNOTES">Notes</H3><TABLEBORDER="0"CLASS="FOOTNOTES"WIDTH="100%"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN7354"HREF="moreadv.html#AEN7354">[1]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>And even when <ICLASS="FIRSTTERM">xargs</I> is		not strictly necessary, it can speed up execution of a command		involving batch processing of multiple files.</P></TD></TR></TABLE><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLEWIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><AHREF="external.html">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="index.html">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><AHREF="timedate.html">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">External Filters, Programs and Commands</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="external.html">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Time / Date Commands</TD></TR></TABLE></DIV></BODY></HTML>

⌨️ 快捷键说明

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