📄 internal.html
字号:
34 awk "$awkscript" "$filename" 35 36 # Thanks, Stephane Chazelas. 37 38 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 while getopts ":abcde:fg" Option 2 # Initial declaration. 3 # a, b, c, d, e, f, and g are the options (flags) expected. 4 # The : after option 'e' shows it will have an argument passed with it. 5 do 6 case $Option in 7 a ) # Do something with variable 'a'. 8 b ) # Do something with variable 'b'. 9 ... 10 e) # Do something with 'e', and also with $OPTARG, 11 # which is the associated argument passed with option 'e'. 12 ... 13 g ) # Do something with variable 'g'. 14 esac 15 done 16 shift $(($OPTIND - 1)) 17 # Move argument pointer to next. 18 19 # All this is not nearly as complicated as it looks <grin>. 20 </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 #!/bin/bash 2 # Exercising getopts and OPTIND 3 # Script modified 10/09/03 at the suggestion of Bill Gradwohl. 4 5 6 # Here we observe how 'getopts' processes command line arguments to script. 7 # The arguments are parsed as "options" (flags) and associated arguments. 8 9 # Try invoking this script with 10 # 'scriptname -mn' 11 # 'scriptname -oq qOption' (qOption can be some arbitrary string.) 12 # 'scriptname -qXXX -r' 13 # 14 # 'scriptname -qr' - Unexpected result, takes "r" as the argument to option "q" 15 # 'scriptname -q -r' - Unexpected result, same as above 16 # 'scriptname -mnop -mnop' - Unexpected result 17 # (OPTIND is unreliable at stating where an option came from). 18 # 19 # If an option expects an argument ("flag:"), then it will grab 20 #+ whatever is next on the command line. 21 22 NO_ARGS=0 23 E_OPTERROR=65 24 25 if [ $# -eq "$NO_ARGS" ] # Script invoked with no command-line args? 26 then 27 echo "Usage: `basename $0` options (-mnopqrs)" 28 exit $E_OPTERROR # Exit and explain usage, if no argument(s) given. 29 fi 30 # Usage: scriptname -options 31 # Note: dash (-) necessary 32 33 34 while getopts ":mnopq:rs" Option 35 do 36 case $Option in 37 m ) echo "Scenario #1: option -m- [OPTIND=${OPTIND}]";; 38 n | o ) echo "Scenario #2: option -$Option- [OPTIND=${OPTIND}]";; 39 p ) echo "Scenario #3: option -p- [OPTIND=${OPTIND}]";; 40 q ) echo "Scenario #4: option -q-\ 41 with argument \"$OPTARG\" [OPTIND=${OPTIND}]";; 42 # Note that option 'q' must have an associated argument, 43 #+ otherwise it falls through to the default. 44 r | s ) echo "Scenario #5: option -$Option-";; 45 * ) echo "Unimplemented option chosen.";; # DEFAULT 46 esac 47 done 48 49 shift $(($OPTIND - 1)) 50 # Decrements the argument pointer so it points to next argument. 51 # $1 now references the first non option item supplied on the command line 52 #+ if one exists. 53 54 exit 0 55 56 # As Bill Gradwohl states, 57 # "The getopts mechanism allows one to specify: scriptname -mnop -mnop 58 #+ but there is no reliable way to differentiate what came from where 59 #+ 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 #!/bin/bash 2 3 . data-file # Load a data file. 4 # Same effect as "source data-file", but more portable. 5 6 # The file "data-file" must be present in current working directory, 7 #+ since it is referred to by its 'basename'. 8 9 # Now, reference some data from that file. 10 11 echo "variable1 (from data-file) = $variable1" 12 echo "variable3 (from data-file) = $variable3" 13 14 let "sum = $variable2 + $variable4" 15 echo "Sum of variable2 + variable4 (from data-file) = $sum" 16 echo "message1 (from data-file) is \"$message1\"" 17 # Note: escaped quotes 18 19 print_message This is the message-print function in the data-file. 20 21 22 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 # This is a data file loaded by a script. 2 # Files of this type may contain variables, functions, etc. 3 # It may be loaded with a 'source' or '.' command by a shell script. 4 5 # Let's initialize some variables. 6 7 variable1=22 8 variable2=474 9 variable3=5 10 variable4=97 11 12 message1="Hello, how are you?" 13 message2="Enough for now. Goodbye." 14 15 print_message () 16 { 17 # Echoes any message passed to it. 18 19 if [ -z "$1" ] 20 then 21 return 1 22 # Error, if argument missing. 23 fi 24 25 echo 26 27 until [ -z "$1" ] 28 do 29 # Step through arguments passed to function. 30 echo -n "$1" 31 # Echo args one at a time, suppressing line feeds. 32 echo -n " " 33 # Insert spaces between words. 34 shift 35 # Next one. 36 done 37 38 echo 39 40 return 0 41 } </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 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 #!/bin/bash 2 # self-source.sh: a script sourcing itself "recursively." 3 # From "Stupid Script Tricks," Volume II. 4 5 MAXPASSCNT=100 # Maximum number of execution passes. 6 7 echo -n "$pass_count " 8 # At first execution pass, this just echoes two blank spaces, 9 #+ since $pass_count still uninitialized. 10 11 let "pass_count += 1" 12 # Assumes the uninitialized variable $pass_count 13 #+ can be incremented the first time around. 14 # This works with Bash and pdksh, but 15 #+ it relies on non-portable (and possibly dangerous) behavior. 16 # Better would be to initialize $pass_count to 0 before incrementing. 17 18 while [ "$pass_count" -le $MAXPASSCNT ] 19 do 20 . $0 # Script "sources" itself, rather than calling itself. 21 # ./$0 (which would be true recursion) doesn't work here. Why? 22 done 23 24 # What occurs here is not actually recursion, 25 #+ since the script effectively "expands" itself, i.e., 26 #+ generates a new section of code 27 #+ with each pass through the 'while' loop', 28 # with each 'source' in
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -