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

📄 assortedtips.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 3 页
字号:
><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;SUCCESS=0   4&nbsp;E_BADINPUT=65   5&nbsp;   6&nbsp;test "$1" -ne 0 -o "$1" -eq 0 2&#62;/dev/null   7&nbsp;# An integer is either equal to 0 or not equal to 0.   8&nbsp;# 2&#62;/dev/null suppresses error message.   9&nbsp;  10&nbsp;if [ $? -ne "$SUCCESS" ]  11&nbsp;then  12&nbsp;  echo "Usage: `basename $0` integer-input"  13&nbsp;  exit $E_BADINPUT  14&nbsp;fi  15&nbsp;  16&nbsp;let "sum = $1 + 25"             # Would give error if $1 not integer.  17&nbsp;echo "Sum = $sum"  18&nbsp;  19&nbsp;# Any variable, not just a command line parameter, can be tested this way.  20&nbsp;  21&nbsp;exit 0</PRE></TD></TR></TABLE>          </P></LI><LI><P><ANAME="RVT"></A>The 0 - 255 range for function return	    values is a severe limitation. Global variables and	    other workarounds are often problematic. An alternative	    method for a function to communicate a value back to	    the main body of the script is to have the function	    write to <TTCLASS="FILENAME">stdout</TT> (usually with	    <AHREF="internal.html#ECHOREF">echo</A>) the <SPANCLASS="QUOTE">"return	    value,"</SPAN> and assign this to a variable. This is	    actually a variant of <AHREF="commandsub.html#COMMANDSUBREF">command	    substitution.</A></P><DIVCLASS="EXAMPLE"><HR><ANAME="MULTIPLICATION"></A><P><B>Example 33-15. Return value trickery</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# multiplication.sh   3&nbsp;   4&nbsp;multiply ()                     # Multiplies params passed.   5&nbsp;{                               # Will accept a variable number of args.   6&nbsp;   7&nbsp;  local product=1   8&nbsp;   9&nbsp;  until [ -z "$1" ]             # Until uses up arguments passed...  10&nbsp;  do  11&nbsp;    let "product *= $1"  12&nbsp;    shift  13&nbsp;  done  14&nbsp;  15&nbsp;  echo $product                 #  Will not echo to stdout,  16&nbsp;}                               #+ since this will be assigned to a variable.  17&nbsp;  18&nbsp;mult1=15383; mult2=25211  19&nbsp;val1=`multiply $mult1 $mult2`  20&nbsp;echo "$mult1 X $mult2 = $val1"  21&nbsp;                                # 387820813  22&nbsp;  23&nbsp;mult1=25; mult2=5; mult3=20  24&nbsp;val2=`multiply $mult1 $mult2 $mult3`  25&nbsp;echo "$mult1 X $mult2 X $mult3 = $val2"  26&nbsp;                                # 2500  27&nbsp;  28&nbsp;mult1=188; mult2=37; mult3=25; mult4=47  29&nbsp;val3=`multiply $mult1 $mult2 $mult3 $mult4`  30&nbsp;echo "$mult1 X $mult2 X $mult3 X $mult4 = $val3"  31&nbsp;                                # 8173300  32&nbsp;  33&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>The same technique also works for alphanumeric	    strings. This means that a function can <SPANCLASS="QUOTE">"return"</SPAN>	    a non-numeric value.</P><P>	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;capitalize_ichar ()          #  Capitalizes initial character   2&nbsp;{                            #+ of argument string(s) passed.   3&nbsp;   4&nbsp;  string0="$@"               # Accepts multiple arguments.   5&nbsp;   6&nbsp;  firstchar=${string0:0:1}   # First character.   7&nbsp;  string1=${string0:1}       # Rest of string(s).   8&nbsp;   9&nbsp;  FirstChar=`echo "$firstchar" | tr a-z A-Z`  10&nbsp;                             # Capitalize first character.  11&nbsp;  12&nbsp;  echo "$FirstChar$string1"  # Output to stdout.  13&nbsp;  14&nbsp;}    15&nbsp;  16&nbsp;newstring=`capitalize_ichar "every sentence should start with a capital letter."`  17&nbsp;echo "$newstring"          # Every sentence should start with a capital letter.</PRE></TD></TR></TABLE> 	  </P><P>It is even possible for a function to <SPANCLASS="QUOTE">"return"</SPAN>	    multiple values with this method.</P><DIVCLASS="EXAMPLE"><HR><ANAME="SUMPRODUCT"></A><P><B>Example 33-16. Even more return value trickery</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# sum-product.sh   3&nbsp;# A function may "return" more than one value.   4&nbsp;   5&nbsp;sum_and_product ()   # Calculates both sum and product of passed args.   6&nbsp;{   7&nbsp;  echo $(( $1 + $2 )) $(( $1 * $2 ))   8&nbsp;# Echoes to stdout each calculated value, separated by space.   9&nbsp;}  10&nbsp;  11&nbsp;echo  12&nbsp;echo "Enter first number "  13&nbsp;read first  14&nbsp;  15&nbsp;echo  16&nbsp;echo "Enter second number "  17&nbsp;read second  18&nbsp;echo  19&nbsp;  20&nbsp;retval=`sum_and_product $first $second`      # Assigns output of function.  21&nbsp;sum=`echo "$retval" | awk '{print $1}'`      # Assigns first field.  22&nbsp;product=`echo "$retval" | awk '{print $2}'`  # Assigns second field.  23&nbsp;  24&nbsp;echo "$first + $second = $sum"  25&nbsp;echo "$first * $second = $product"  26&nbsp;echo  27&nbsp;  28&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV></LI><LI><P><ANAME="PASSARRAY"></A></P><P>Next in our bag of tricks are techniques for passing	    an <AHREF="arrays.html#ARRAYREF">array</A> to a	    <AHREF="functions.html#FUNCTIONREF">function</A>, then	    <SPANCLASS="QUOTE">"returning"</SPAN> an array back to the main body of	    the script.</P><P>Passing an array involves loading the space-separated	    elements of the array into a variable with <AHREF="commandsub.html#COMMANDSUBREF">command substitution</A>. <ANAME="RETARRAY"></A>Getting an array back as the <SPANCLASS="QUOTE">"return	    value"</SPAN> from a function uses the previously mentioned	    strategem of <AHREF="internal.html#ECHOREF">echoing</A> the	    array in the function, then invoking command substitution	    and the <BCLASS="COMMAND">( ... )</B> operator to assign it to	    an array.</P><DIVCLASS="EXAMPLE"><HR><ANAME="ARRFUNC"></A><P><B>Example 33-17. Passing and returning arrays</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# array-function.sh: Passing an array to a function and...   3&nbsp;#                   "returning" an array from a function   4&nbsp;   5&nbsp;   6&nbsp;Pass_Array ()   7&nbsp;{   8&nbsp;  local passed_array   # Local variable.   9&nbsp;  passed_array=( `echo "$1"` )  10&nbsp;  echo "${passed_array[@]}"  11&nbsp;  #  List all the elements of the new array  12&nbsp;  #+ declared and set within the function.  13&nbsp;}  14&nbsp;  15&nbsp;  16&nbsp;original_array=( element1 element2 element3 element4 element5 )  17&nbsp;  18&nbsp;echo  19&nbsp;echo "original_array = ${original_array[@]}"  20&nbsp;#                      List all elements of original array.  21&nbsp;  22&nbsp;  23&nbsp;# This is the trick that permits passing an array to a function.  24&nbsp;# **********************************  25&nbsp;argument=`echo ${original_array[@]}`  26&nbsp;# **********************************  27&nbsp;#  Pack a variable  28&nbsp;#+ with all the space-separated elements of the original array.  29&nbsp;#  30&nbsp;# Note that attempting to just pass the array itself will not work.  31&nbsp;  32&nbsp;  33&nbsp;# This is the trick that allows grabbing an array as a "return value".  34&nbsp;# *****************************************  35&nbsp;returned_array=( `Pass_Array "$argument"` )  36&nbsp;# *****************************************  37&nbsp;# Assign 'echoed' output of function to array variable.  38&nbsp;  39&nbsp;echo "returned_array = ${returned_array[@]}"  40&nbsp;  41&nbsp;echo "============================================================="  42&nbsp;  43&nbsp;#  Now, try it again,  44&nbsp;#+ attempting to access (list) the array from outside the function.  45&nbsp;Pass_Array "$argument"  46&nbsp;  47&nbsp;# The function itself lists the array, but...  48&nbsp;#+ accessing the array from outside the function is forbidden.  49&nbsp;echo "Passed array (within function) = ${passed_array[@]}"  50&nbsp;# NULL VALUE since this is a variable local to the function.  51&nbsp;  52&nbsp;echo  53&nbsp;  54&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>For a more elaborate example of passing arrays to	    functions, see <AHREF="contributed-scripts.html#LIFESLOW">Example A-10</A>.</P></LI><LI><P><ANAME="CSTYLE"></A></P><P>Using the <AHREF="dblparens.html">double parentheses	    construct</A>, it is possible to use C-style syntax	    for setting and incrementing/decrementing variables	    and in <AHREF="loops.html#FORLOOPREF1">for</A> and <AHREF="loops.html#WHILELOOPREF">while</A> loops.	See <AHREF="loops.html#FORLOOPC">Example 10-12</A> and <AHREF="loops.html#WHLOOPC">Example 10-17</A>.</P></LI><LI><P><ANAME="SETPUM"></A></P><P>Setting the <AHREF="variables2.html#PATHREF">path</A> and <AHREF="system.html#UMASKREF">umask</A> at the beginning of a script makes	    it more <SPANCLASS="QUOTE">"portable"</SPAN> -- more likely to run on a	    <SPANCLASS="QUOTE">"foreign"</SPAN> machine whose user may have bollixed up the	    <TTCLASS="VARNAME">$PATH</TT> and <BCLASS="COMMAND">umask</B>.	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;PATH=/bin:/usr/bin:/usr/local/bin ; export PATH   3&nbsp;umask 022   # Files that the script creates will have 755 permission.   4&nbsp;   5&nbsp;# Thanks to Ian D. Allen, for this tip.</PRE></TD></TR></TABLE></P></LI><LI><P><ANAME="FILTEROUTP"></A></P><P>A useful scripting technique is to	    <SPANCLASS="emphasis"><ICLASS="EMPHASIS">repeatedly</I></SPAN> feed the output of a filter	    (by piping) back to the <SPANCLASS="emphasis"><ICLASS="EMPHASIS">same filter</I></SPAN>, but	    with a different set of arguments and/or options. Especially	    suitable for this are <AHREF="textproc.html#TRREF">tr</A> and	    <AHREF="textproc.html#GREPREF">grep</A>.</P><P>	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# From "wstrings.sh" example.   2&nbsp;   3&nbsp;wlist=`strings "$1" | tr A-Z a-z | tr '[:space:]' Z | \   4&nbsp;tr -cs '[:alpha:]' Z | tr -s '\173-\377' Z | tr Z ' '`</PRE></TD></TR></TABLE>	  </P><DIVCLASS="EXAMPLE"><HR><ANAME="AGRAM"></A><P><B>Example 33-18. Fun with anagrams</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# agram.sh: Playing games with anagrams.   3&nbsp;   4&nbsp;# Find anagrams of...   5&nbsp;LETTERSET=etaoinshrdlu   6&nbsp;FILTER='.......'       # How many letters minimum?   7&nbsp;#       1234567   8&nbsp;   9&nbsp;anagram "$LETTERSET" | # Find all anagrams of the letterset...  10&nbsp;grep "$FILTER" |       # With at least 7 letters,  11&nbsp;grep '^is' |           # starting with 'is'  12&nbsp;grep -v 's$' |         # no plurals  13&nbsp;grep -v 'ed$'          # no past tense verbs  14&nbsp;# Possible to add many combinations of conditions and filters.  15&nbsp;  16&nbsp;#  Uses "anagram" utility  17&nbsp;#+ that is part of the author's "yawl" word list package.  18&nbsp;#  http://ibiblio.org/pub/Linux/libs/yawl-0.3.2.tar.gz  19&nbsp;#  http://personal.riverusers.com/~thegrendel/yawl-0.3.2.tar.gz  20&nbsp;  21&nbsp;exit 0                 # End of code.  22&nbsp;  23&nbsp;  24&nbsp;bash$ sh agram.sh  25&nbsp;islander  26&nbsp;isolate  27&nbsp;isolead  28&nbsp;isotheral  29&nbsp;  30&nbsp;  31&nbsp;  32&nbsp;#  Exercises:  33&nbsp;#  ---------  34&nbsp;#  Modify this script to take the LETTERSET as a command-line parameter.  35&nbsp;#  Parameterize the filters in lines 11 - 13 (as with $FILTER),  36&nbsp;#+ so that they can be specified by passing arguments to a function.  37&nbsp;  38&nbsp;#  For a slightly different approach to anagramming,  39&nbsp;#+ see the agram2.sh script.</PRE></TD></TR></TABLE><HR></DIV><P>See also <AHREF="procref1.html#CONSTAT">Example 27-3</A>, <AHREF="textproc.html#CRYPTOQUOTE">Example 15-24</A>, and <AHREF="contributed-scripts.html#SOUNDEX">Example A-9</A>.</P></LI><LI><P><ANAME="COMMBLAHD"></A></P><P>Use <SPANCLASS="QUOTE">"<AHREF="here-docs.html#ANONHEREDOC0">anonymous here	    documents</A>"</SPAN> to comment out blocks of code,	    to save having to individually comment out each line with	    a <SPANCLASS="TOKEN">#</SPAN>.  See <AHREF="here-docs.html#COMMENTBLOCK">Example 18-11</A>.</P></LI><LI><P><ANAME="WHATISREF3"></A></P><P>Running a script on a machine that relies on a command	    that might not be installed is dangerous. Use <AHREF="filearchiv.html#WHATISREF">whatis</A> to avoid potential problems	    with this.</P><P>	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;CMD=command1                 # First choice.   2&nbsp;PlanB=command2               # Fallback option.   3&nbsp;   4&nbsp;command_test=$(whatis "$CMD" | grep 'nothing appropriate')   5&nbsp;#  If 'command1' not found on system , 'whatis' will return   6&nbsp;#+ "command1: nothing appropriate."   7&nbsp;#   8&nbsp;#  A safer alternative is:

⌨️ 快捷键说明

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