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

📄 assortedtips.html

📁 BASH Shell 编程 经典教程 《高级SHELL脚本编程》中文版
💻 HTML
📖 第 1 页 / 共 3 页
字号:
CLASS="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;# 整数要不就是0, 要不就是非0值. (译者注: 感觉像废话 . . .)  8&nbsp;# 2&#62;/dev/null禁止输出错误信息.   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"             # 如果$1不是整数, 就会产生错误.  17&nbsp;echo "Sum = $sum" 18&nbsp; 19&nbsp;# 任何变量都可以使用这种方法来测试, 而不仅仅适用于命令行参数.  20&nbsp; 21&nbsp;exit 0</PRE></FONT></TD></TR></TABLE>          </P></LI><LI><P><ANAME="RVT"></A>函数的返回值严格限制在0 - 255之间. 	    使用全局变量或者其他方法来代替函数返回值, 通常都很容易产生问题. 	    从函数中, 返回一个值到脚本主体的另一个办法是, 		将这个"返回值"写入到<TTCLASS="FILENAME">stdout</TT>(通常都使用<AHREF="internal.html#ECHOREF">echo</A>命令), 		然后将其赋值给一个变量. 		这种做法其实就是<AHREF="commandsub.html#COMMANDSUBREF">命令替换</A>的一个变种. </P><DIVCLASS="EXAMPLE"><HR><ANAME="MULTIPLICATION"></A><P><B>例子 33-15. 返回值小技巧</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#!/bin/bash  2&nbsp;# multiplication.sh  3&nbsp;  4&nbsp;multiply ()                     # 将乘数作为参数传递进来.   5&nbsp;{                               # 可以接受多个参数.   6&nbsp;  7&nbsp;  local product=1  8&nbsp;  9&nbsp;  until [ -z "$1" ]             # 直到处理完所有的参数... 10&nbsp;  do 11&nbsp;    let "product *= $1" 12&nbsp;    shift 13&nbsp;  done 14&nbsp; 15&nbsp;  echo $product                 #  不会echo到stdout,  16&nbsp;}                               #+ 因为要把它赋值给一个变量.  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></FONT></TD></TR></TABLE><HR></DIV><P>相同的技术也可以用在字符串上. 	    这意味着函数可以<SPANCLASS="QUOTE">"返回"</SPAN>非数字的值. </P><P>	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;capitalize_ichar ()          #  将传递进来的字符串的  2&nbsp;{                            #+ 首字母转换为大写.   3&nbsp;  4&nbsp;  string0="$@"               # 能够接受多个参数.   5&nbsp;  6&nbsp;  firstchar=${string0:0:1}   # 首字母.   7&nbsp;  string1=${string0:1}       # 余下的字符.   8&nbsp;  9&nbsp;  FirstChar=`echo "$firstchar" | tr a-z A-Z` 10&nbsp;                             # 将首字母转换为大写.  11&nbsp; 12&nbsp;  echo "$FirstChar$string1"  # 输出到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></FONT></TD></TR></TABLE> 	  </P><P>使用这种办法甚至能够<SPANCLASS="QUOTE">"返回"</SPAN>多个值. </P><DIVCLASS="EXAMPLE"><HR><ANAME="SUMPRODUCT"></A><P><B>例子 33-16. 返回多个值的技巧</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#!/bin/bash  2&nbsp;# sum-product.sh  3&nbsp;# 可以"返回"超过一个值的函数.   4&nbsp;  5&nbsp;sum_and_product ()   # 计算所有传递进来的参数的总和, 与总乘积.   6&nbsp;{  7&nbsp;  echo $(( $1 + $2 )) $(( $1 * $2 ))  8&nbsp;# 将每个计算出来的结果输出到stdout, 并以空格分隔.   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`      # 将函数的输出赋值给变量.  21&nbsp;sum=`echo "$retval" | awk '{print $1}'`      # 赋值第一个域.  22&nbsp;product=`echo "$retval" | awk '{print $2}'`  # 赋值第二个域.  23&nbsp; 24&nbsp;echo "$first + $second = $sum" 25&nbsp;echo "$first * $second = $product" 26&nbsp;echo 27&nbsp; 28&nbsp;exit 0</PRE></FONT></TD></TR></TABLE><HR></DIV></LI><LI><P>下一个技巧, 是将<AHREF="arrays.html#ARRAYREF">数组</A>传递给<AHREF="functions.html#FUNCTIONREF">函数</A>的技术, 				然后<SPANCLASS="QUOTE">"返回"</SPAN>一个数组给脚本的主体. 	    </P><P>使用<AHREF="commandsub.html#COMMANDSUBREF">命令替换</A>将数组中的所有元素(元素之间用空格分隔)赋值给一个变量, 			这样就可以将数组传递到函数中了. 			我们之前提到过一种返回值的策略, 就是将要从函数中返回的内容, 			用<EM>echo</EM>命令输出出来, 			然后使用命令替换或者<BCLASS="COMMAND">( ... )</B>操作符, 			将函数的输出(也就是我们想要得返回值)保存到一个变量中. 			如果我们想让函数<SPANCLASS="QUOTE">"返回"</SPAN>数组, 当然也可以使用这种策略. 	    </P><DIVCLASS="EXAMPLE"><HR><ANAME="ARRFUNC"></A><P><B>例子 33-17. 传递数组到函数, 从函数中返回数组</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#!/bin/bash  2&nbsp;# array-function.sh: 将数组传递到函数中与...  3&nbsp;#                   从函数中"返回"一个数组  4&nbsp;  5&nbsp;  6&nbsp;Pass_Array ()  7&nbsp;{  8&nbsp;  local passed_array   # 局部变量.   9&nbsp;  passed_array=( `echo "$1"` ) 10&nbsp;  echo "${passed_array[@]}" 11&nbsp;  #  列出这个新数组中的所有元素,  12&nbsp;  #+ 这个新数组是在函数内声明的, 也是在函数内赋值的.  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;#                      列出原始数组的所有元素.  21&nbsp; 22&nbsp; 23&nbsp;# 下面是关于如何将数组传递给函数的技巧.  24&nbsp;# ********************************** 25&nbsp;argument=`echo ${original_array[@]}` 26&nbsp;# ********************************** 27&nbsp;#  将原始数组中所有的元素都用空格进行分隔,  28&nbsp;#+ 然后合并成一个字符串, 最后赋值给一个变量.  29&nbsp;# 30&nbsp;# 注意, 如果只把数组传递给函数, 那是不行的.  31&nbsp; 32&nbsp; 33&nbsp;# 下面是让数组作为"返回值"的技巧.  34&nbsp;# ***************************************** 35&nbsp;returned_array=( `Pass_Array "$argument"` ) 36&nbsp;# ***************************************** 37&nbsp;# 将函数中'echo'出来的输出赋值给数组变量.  38&nbsp; 39&nbsp;echo "returned_array = ${returned_array[@]}" 40&nbsp; 41&nbsp;echo "=============================================================" 42&nbsp; 43&nbsp;#  现在, 再试一次,  44&nbsp;#+ 尝试一下, 在函数外面访问(列出)数组.  45&nbsp;Pass_Array "$argument" 46&nbsp; 47&nbsp;# 函数自身可以列出数组, 但是... 48&nbsp;#+ 从函数外部访问数组是被禁止的.  49&nbsp;echo "Passed array (within function) = ${passed_array[@]}" 50&nbsp;# NULL值, 因为这个变量是函数内部的局部变量.  51&nbsp; 52&nbsp;echo 53&nbsp; 54&nbsp;exit 0</PRE></FONT></TD></TR></TABLE><HR></DIV><P>如果想更加了解如何将数组传递到函数中, 	    请参考<AHREF="contributed-scripts.html#LIFESLOW">例子 A-10</A>, 这是一个精心制作的例子. </P></LI><LI><P>利用双括号结构, 就可以让我们使用C风格的语法, 				在<AHREF="loops1.html#FORLOOPREF1">for</A>循环和<AHREF="loops1.html#WHILELOOPREF">while</A>循环中, 设置或者增加变量. 	    请参考<AHREF="loops1.html#FORLOOPC">例子 10-12</A>和<AHREF="loops1.html#WHLOOPC">例子 10-17</A>. </P></LI><LI><P>如果在脚本的开头设置<AHREF="internalvariables.html#PATHREF">path</A>和<AHREF="system.html#UMASKREF">umask</A>的话, 就可以增加脚本的<SPANCLASS="QUOTE">"可移植性"</SPAN> 		  -- 即使在那些被用户将<CODECLASS="VARNAME">$PATH</CODE>和<BCLASS="COMMAND">umask</B>弄糟了的机器上, 也可以运行. 	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#!/bin/bash  2&nbsp;PATH=/bin:/usr/bin:/usr/local/bin ; export PATH  3&nbsp;umask 022   # 脚本创建的文件所具有的权限是755.   4&nbsp;  5&nbsp;# 感谢Ian D. Allen提出这个技巧. </PRE></FONT></TD></TR></TABLE></P></LI><LI><P>一项很有用的技术是, 		  <EM>重复地</EM>将一个过滤器的输出(通过管道)传递给这个相同的过滤器, 	    但是这两次使用不同的参数和选项. 	    尤其是<AHREF="textproc.html#TRREF">tr</A>和<AHREF="textproc.html#GREPREF">grep</A>, 非常适合于这种情况. </P><P>	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;# 摘自例子"wstrings.sh".   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></FONT></TD></TR></TABLE>	  </P><DIVCLASS="EXAMPLE"><HR><ANAME="AGRAM"></A><P><B>例子 33-18. anagram游戏</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><FONTCOLOR="#000000"><PRECLASS="PROGRAMLISTING">  1&nbsp;#!/bin/bash  2&nbsp;# agram.sh: 使用anagram来玩游戏.   3&nbsp;  4&nbsp;# 寻找anagram...  5&nbsp;LETTERSET=etaoinshrdlu  6&nbsp;FILTER='.......'       # 最少有多少个字母?   7&nbsp;#       1234567  8&nbsp;  9&nbsp;anagram "$LETTERSET" | # 找出这个字符串中所有的anagram... 10&nbsp;grep "$FILTER" |       # 至少需要7个字符,  11&nbsp;grep '^is' |           # 以'is'开头 12&nbsp;grep -v 's$' |         # 不是复数(指英文单词的复数) 13&nbsp;grep -v 'ed$'          # 不是过去时(也指英文单词) 14&nbsp;# 可以添加许多种组合条件和过滤器.  15&nbsp; 16&nbsp;#  使用"anagram"工具,  17&nbsp;#+ 这是作者的"yawl"文字表软件包中的一部分.  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                 # 代码结束.  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;#  练习:

⌨️ 快捷键说明

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