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

📄 internal.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 HTML
📖 第 1 页 / 共 5 页
字号:
  34&nbsp;awk "$awkscript" "$filename"  35&nbsp;  36&nbsp;# Thanks, Stephane Chazelas.  37&nbsp;  38&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="TIP"><TABLECLASS="TIP"WIDTH="90%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/tip.png"HSPACE="5"ALT="Tip"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>It is possible to initialize and export		  variables in the same operation, as in <BCLASS="COMMAND">export		  var1=xxx</B>.</P><P>However, as Greg Keraunen points out, in certain		  situations this may have a different effect than		  setting a variable, then exporting it.</P><P>	        <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="SCREEN"> <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>export var=(a b); echo ${var[0]}</B></TT> <TTCLASS="COMPUTEROUTPUT">(a b)</TT>    <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>var=(a b); export var; echo ${var[0]}</B></TT> <TTCLASS="COMPUTEROUTPUT">a</TT> 	      </PRE></TD></TR></TABLE>	    </P></TD></TR></TABLE></DIV></DD><DT><BCLASS="COMMAND">declare</B>, <BCLASS="COMMAND">typeset</B></DT><DD><P>The <AHREF="declareref.html">declare</A> and	      <AHREF="declareref.html">typeset</A> commands specify	      and/or restrict properties of variables.</P></DD><DT><BCLASS="COMMAND">readonly</B></DT><DD><P>Same as <AHREF="declareref.html">declare -r</A>,	      sets a variable as read-only, or, in effect, as a	      constant. Attempts to change the variable fail with	      an error message. This is the shell analog of the	      <ICLASS="EMPHASIS">C</I> language <BCLASS="COMMAND">const</B>	      type qualifier.</P></DD><DT><ANAME="GETOPTSX"></A><BCLASS="COMMAND">getopts</B></DT><DD><P>This powerful tool parses command-line arguments passed	      to the script. This is the Bash analog of the <AHREF="extmisc.html#GETOPTY">getopt</A> external command and the	      <BCLASS="COMMAND">getopt</B> library function familiar to	      <ICLASS="EMPHASIS">C</I> programmers. It permits passing	      and concatenating multiple options	      <ANAME="AEN6339"HREF="#FTN.AEN6339">[2]</A>	      and associated arguments to a script (for	      example <TTCLASS="USERINPUT"><B>scriptname -abc -e	      /usr/local</B></TT>).</P><P>The <BCLASS="COMMAND">getopts</B> construct uses two implicit	      variables. <TTCLASS="VARNAME">$OPTIND</TT> is the argument	      pointer (<ICLASS="WORDASWORD">OPTion INDex</I>)	      and <TTCLASS="VARNAME">$OPTARG</TT> (<ICLASS="WORDASWORD">OPTion	      ARGument</I>) the (optional) argument attached	      to an option. A colon following the option name in the	      declaration tags that option as having an associated	      argument.</P><P>A <BCLASS="COMMAND">getopts</B> construct usually comes	      packaged in a <AHREF="loops.html#WHILELOOPREF">while	      loop</A>, which processes the options and	      arguments one at a time, then increments the implicit	      <TTCLASS="VARNAME">$OPTIND</TT> variable to step to the	      next.</P><DIVCLASS="NOTE"><TABLECLASS="NOTE"WIDTH="90%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/note.png"HSPACE="5"ALT="Note"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>		<OLTYPE="1"><LI><P>The arguments passed from the command line to		      the script must be preceded by a		      minus (<TTCLASS="OPTION">-</TT>). It is the		      prefixed <TTCLASS="OPTION">-</TT> that lets		      <BCLASS="COMMAND">getopts</B> recognize command-line		      arguments as <ICLASS="EMPHASIS">options</I>.		      In fact, <BCLASS="COMMAND">getopts</B> will not process		      arguments without the prefixed <TTCLASS="OPTION">-</TT>,		      and will terminate option processing at the first		      argument encountered lacking them.</P></LI><LI><P>The <BCLASS="COMMAND">getopts</B> template		      differs slightly from the standard <BCLASS="COMMAND">while</B>		      loop, in that it lacks condition brackets.</P></LI><LI><P>The <BCLASS="COMMAND">getopts</B> construct replaces		     the deprecated <AHREF="extmisc.html#GETOPTY">getopt</A>		     external command.</P></LI></OL>	      </P></TD></TR></TABLE></DIV><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;while getopts ":abcde:fg" Option   2&nbsp;# Initial declaration.   3&nbsp;# a, b, c, d, e, f, and g are the options (flags) expected.   4&nbsp;# The : after option 'e' shows it will have an argument passed with it.   5&nbsp;do   6&nbsp;  case $Option in   7&nbsp;    a ) # Do something with variable 'a'.   8&nbsp;    b ) # Do something with variable 'b'.   9&nbsp;    ...  10&nbsp;    e)  # Do something with 'e', and also with $OPTARG,  11&nbsp;        # which is the associated argument passed with option 'e'.  12&nbsp;    ...  13&nbsp;    g ) # Do something with variable 'g'.  14&nbsp;  esac  15&nbsp;done  16&nbsp;shift $(($OPTIND - 1))  17&nbsp;# Move argument pointer to next.  18&nbsp;  19&nbsp;# All this is not nearly as complicated as it looks &#60;grin&#62;.  20&nbsp;	      </PRE></TD></TR></TABLE></P><DIVCLASS="EXAMPLE"><HR><ANAME="EX33"></A><P><B>Example 11-19. Using <BCLASS="COMMAND">getopts</B> to read the	        options/arguments passed to a script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# Exercising getopts and OPTIND   3&nbsp;# Script modified 10/09/03 at the suggestion of Bill Gradwohl.   4&nbsp;   5&nbsp;   6&nbsp;# Here we observe how 'getopts' processes command line arguments to script.   7&nbsp;# The arguments are parsed as "options" (flags) and associated arguments.   8&nbsp;   9&nbsp;# Try invoking this script with  10&nbsp;# 'scriptname -mn'  11&nbsp;# 'scriptname -oq qOption' (qOption can be some arbitrary string.)  12&nbsp;# 'scriptname -qXXX -r'  13&nbsp;#  14&nbsp;# 'scriptname -qr'    - Unexpected result, takes "r" as the argument to option "q"  15&nbsp;# 'scriptname -q -r'  - Unexpected result, same as above  16&nbsp;# 'scriptname -mnop -mnop'  - Unexpected result  17&nbsp;# (OPTIND is unreliable at stating where an option came from).  18&nbsp;#  19&nbsp;#  If an option expects an argument ("flag:"), then it will grab  20&nbsp;#+ whatever is next on the command line.  21&nbsp;  22&nbsp;NO_ARGS=0   23&nbsp;E_OPTERROR=65  24&nbsp;  25&nbsp;if [ $# -eq "$NO_ARGS" ]  # Script invoked with no command-line args?  26&nbsp;then  27&nbsp;  echo "Usage: `basename $0` options (-mnopqrs)"  28&nbsp;  exit $E_OPTERROR        # Exit and explain usage, if no argument(s) given.  29&nbsp;fi    30&nbsp;# Usage: scriptname -options  31&nbsp;# Note: dash (-) necessary  32&nbsp;  33&nbsp;  34&nbsp;while getopts ":mnopq:rs" Option  35&nbsp;do  36&nbsp;  case $Option in  37&nbsp;    m     ) echo "Scenario #1: option -m-   [OPTIND=${OPTIND}]";;  38&nbsp;    n | o ) echo "Scenario #2: option -$Option-   [OPTIND=${OPTIND}]";;  39&nbsp;    p     ) echo "Scenario #3: option -p-   [OPTIND=${OPTIND}]";;  40&nbsp;    q     ) echo "Scenario #4: option -q-\  41&nbsp; with argument \"$OPTARG\"   [OPTIND=${OPTIND}]";;  42&nbsp;    #  Note that option 'q' must have an associated argument,  43&nbsp;    #+ otherwise it falls through to the default.  44&nbsp;    r | s ) echo "Scenario #5: option -$Option-";;  45&nbsp;    *     ) echo "Unimplemented option chosen.";;   # DEFAULT  46&nbsp;  esac  47&nbsp;done  48&nbsp;  49&nbsp;shift $(($OPTIND - 1))  50&nbsp;#  Decrements the argument pointer so it points to next argument.  51&nbsp;#  $1 now references the first non option item supplied on the command line  52&nbsp;#+ if one exists.  53&nbsp;  54&nbsp;exit 0  55&nbsp;  56&nbsp;#   As Bill Gradwohl states,  57&nbsp;#  "The getopts mechanism allows one to specify:  scriptname -mnop -mnop  58&nbsp;#+  but there is no reliable way to differentiate what came from where  59&nbsp;#+  by using OPTIND."</PRE></TD></TR></TABLE><HR></DIV></DD></DL></DIV><DIVCLASS="VARIABLELIST"><P><B><ANAME="INTSCRBEH1"></A>Script Behavior</B></P><DL><DT><ANAME="SOURCEREF"></A><BCLASS="COMMAND">source</B>, <SPANCLASS="TOKEN">.</SPAN> (<AHREF="special-chars.html#DOTREF">dot</A> command)</DT><DD><P>This command, when invoked from the command line,	      executes a script. Within a script, a	      <TTCLASS="USERINPUT"><B>source file-name</B></TT> loads the	      file <TTCLASS="FILENAME">file-name</TT>. Sourcing a file	      (dot-command) <ICLASS="EMPHASIS">imports</I>	     code into the script, appending to the script (same effect	     as the <TTCLASS="USERINPUT"><B>#include</B></TT> directive in a	     <ICLASS="EMPHASIS">C</I> program). The net result is the	     same as if the <SPANCLASS="QUOTE">"sourced"</SPAN> lines of code were	     physically present in the body of the script. This is useful	     in situations when multiple scripts use a common data file	     or function library.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX38"></A><P><B>Example 11-20. <SPANCLASS="QUOTE">"Including"</SPAN> a data file</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;. data-file    # Load a data file.   4&nbsp;# Same effect as "source data-file", but more portable.   5&nbsp;   6&nbsp;#  The file "data-file" must be present in current working directory,   7&nbsp;#+ since it is referred to by its 'basename'.   8&nbsp;   9&nbsp;# Now, reference some data from that file.  10&nbsp;  11&nbsp;echo "variable1 (from data-file) = $variable1"  12&nbsp;echo "variable3 (from data-file) = $variable3"  13&nbsp;  14&nbsp;let "sum = $variable2 + $variable4"  15&nbsp;echo "Sum of variable2 + variable4 (from data-file) = $sum"  16&nbsp;echo "message1 (from data-file) is \"$message1\""  17&nbsp;# Note:                            escaped quotes  18&nbsp;  19&nbsp;print_message This is the message-print function in the data-file.  20&nbsp;  21&nbsp;  22&nbsp;exit 0</PRE></TD></TR></TABLE><P>File <TTCLASS="FILENAME">data-file</TT> for <AHREF="internal.html#EX38">Example 11-20</A>, above.  Must be present in same		directory.</P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# This is a data file loaded by a script.   2&nbsp;# Files of this type may contain variables, functions, etc.   3&nbsp;# It may be loaded with a 'source' or '.' command by a shell script.   4&nbsp;   5&nbsp;# Let's initialize some variables.   6&nbsp;   7&nbsp;variable1=22   8&nbsp;variable2=474   9&nbsp;variable3=5  10&nbsp;variable4=97  11&nbsp;  12&nbsp;message1="Hello, how are you?"  13&nbsp;message2="Enough for now. Goodbye."  14&nbsp;  15&nbsp;print_message ()  16&nbsp;{  17&nbsp;# Echoes any message passed to it.  18&nbsp;  19&nbsp;  if [ -z "$1" ]  20&nbsp;  then  21&nbsp;    return 1  22&nbsp;    # Error, if argument missing.  23&nbsp;  fi  24&nbsp;  25&nbsp;  echo  26&nbsp;  27&nbsp;  until [ -z "$1" ]  28&nbsp;  do  29&nbsp;    # Step through arguments passed to function.  30&nbsp;    echo -n "$1"  31&nbsp;    # Echo args one at a time, suppressing line feeds.  32&nbsp;    echo -n " "  33&nbsp;    # Insert spaces between words.  34&nbsp;    shift  35&nbsp;    # Next one.  36&nbsp;  done    37&nbsp;  38&nbsp;  echo  39&nbsp;  40&nbsp;  return 0  41&nbsp;}  </PRE></TD></TR></TABLE><HR></DIV><P>If the <ICLASS="EMPHASIS">sourced</I> file is itself	       an executable script, then it will run, then	       return control to the script that called it.	       A <ICLASS="EMPHASIS">sourced</I> executable script may use a	      <AHREF="functions.html#RETURNREF">return</A> for this	      purpose.</P><P>	      Arguments may be (optionally) passed to the	      <ICLASS="EMPHASIS">sourced</I> file as <AHREF="othertypesv.html#POSPARAMREF1">positional parameters</A>.	       <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;source $filename $arg1 arg2</PRE></TD></TR></TABLE>	    </P><P>It is even possible for a script to	    <ICLASS="EMPHASIS">source</I> itself, though this does not	    seem to have any practical applications.</P><DIVCLASS="EXAMPLE"><HR><ANAME="SELFSOURCE"></A><P><B>Example 11-21. A (useless) script that sources itself</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# self-source.sh: a script sourcing itself "recursively."   3&nbsp;# From "Stupid Script Tricks," Volume II.   4&nbsp;   5&nbsp;MAXPASSCNT=100    # Maximum number of execution passes.   6&nbsp;   7&nbsp;echo -n  "$pass_count  "   8&nbsp;#  At first execution pass, this just echoes two blank spaces,   9&nbsp;#+ since $pass_count still uninitialized.  10&nbsp;  11&nbsp;let "pass_count += 1"  12&nbsp;#  Assumes the uninitialized variable $pass_count  13&nbsp;#+ can be incremented the first time around.  14&nbsp;#  This works with Bash and pdksh, but  15&nbsp;#+ it relies on non-portable (and possibly dangerous) behavior.  16&nbsp;#  Better would be to initialize $pass_count to 0 before incrementing.  17&nbsp;  18&nbsp;while [ "$pass_count" -le $MAXPASSCNT ]  19&nbsp;do  20&nbsp;  . $0   # Script "sources" itself, rather than calling itself.  21&nbsp;         # ./$0 (which would be true recursion) doesn't work here. Why?  22&nbsp;done    23&nbsp;  24&nbsp;#  What occurs here is not actually recursion,  25&nbsp;#+ since the script effectively "expands" itself, i.e.,  26&nbsp;#+ generates a new section of code  27&nbsp;#+ with each pass through the 'while' loop',  28&nbsp;#  with each 'source' in 

⌨️ 快捷键说明

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