Shell编程基础:修订间差异

来自Ubuntu中文
跳到导航跳到搜索
Wl1336412留言 | 贡献
无编辑摘要
 
(未显示超过100个用户的206个中间版本)
第1行: 第1行:
<p class="line862">本文作者:<a href="http://127.0.0.1:8000/Leal">Leal</a> </p>
原作者 Leal;请参阅页面底部的编者列表。
<p class="line867">&nbsp;</p>
<p class="line867">&nbsp;</p>
<p class="line874">授权许可: </p>
<ul>
    <li style="list-style-type: none;">
    <p class="line891"><a href="http://creativecommons.org/licenses/by-sa/2.0/" class="http">创作共用协议Attribution-ShareAlike 2.0</a> </p>
    </li>
    <li style="list-style-type: none;">
    <p class="line891"><a href="http://www.gnu.org/copyleft/fdl.html" class="http">GNU自由文档许可证</a> </p>
    </li>
</ul>
<p class="line862">编辑人员:<a href="http://127.0.0.1:8000/FireHare">FireHare</a> </p>
<p class="line874">校对人员: </p>
<p class="line874">适用版本: </p>
<p class="line874">文章状态: </p>
<p class="line874">参考文献: </p>
<hr />
<p class="line874">&nbsp;</p>
<div>&nbsp;</div>
<p>&nbsp;</p>
<p class="line867">&nbsp;</p>
<h2 id="head-40bf9537717143d434032ef1db0c8b2f08abc617">1. 基本格式</h2>
<p>&nbsp;</p>
<p class="line862">编</p>
<address>#!/bin/sh<br />
<br />
...
<p class="line874">符号#!用来告诉系统执行该脚本的程序,本例使用/bin/sh。编辑结束并保存后,如果要执行该脚本,必须先使其可执行:</p>
</address>
<address>chmod +x filename
<address>&nbsp;
<p class="line874">此后在该脚本所在目录下,输入 ./filename 即可执行该脚本。</p>
<p class="line867">&nbsp;</p>
<h3 id="head-e8fd7a45e8093d614f9f8575cd4840ce82b6b4a6">1.1. 合理使用注释</h3>
<p>&nbsp;</p>
<p class="line874">shell 脚本中以# 开始的行表示注释,直到该行的结束。我们强烈建议你在脚本中进行适当/合理的注释,这样一来,即便你在相当长时间内没有使用该脚本,也能在短时间内就明白 它的作用和工作原理。此外,还有一个很重要的原因是,在注释的帮助下,别人可以快速有效的分享你的脚本,并提出自己的意见和改进。</p>
<p class="line867">&nbsp;</p>
<h3 id="head-81ace5f3f8146bb1a2586a6296051e6568a501a6">1.2. 变量赋值和引用</h3>
<p>&nbsp;</p>
<p class="line874">Shell编程中,使用变量无需事先声明,同时变量名的命名须遵循如下规则:</p>
<ol type="1">
    <li>首个字符必须为字母(a-z,A-Z)</li>
    <li>中间不能有空格,可以使用下滑线(_)</li>
    <li>不能使用标点符号</li>
    <li>不能使用bash里的关键字(可用help命令查看保留关键字)</li>
</ol>
<p class="line874">需要给变量赋值时,可以这么写:</p>
<pre>变量名=值</pre>
<p>&nbsp;</p>
<p class="line874">要取用一个变量的值,只需在变量名前面加一个$:</p>
<address>#!/bin/sh<br />
#对变量赋值:<br />
a=&quot;hello world&quot;<br />
<br />
# 打印变量a的值:<br />
echo &quot;A is:&quot; $a</address>
<address>&nbsp;</address>
<p class="line874">挑个自己喜欢的编辑器,输入上述内容,并保存为文件first,然后执行 chmod +x first 使其可执行,最后输入 ./first 执行该脚本。其输出结果如下:</p>
<address>A is: hello world</address>
<address>&nbsp;</address>
<p class="line874">有时候变量名可能会和其它文字混淆,比如:</p>
<address>num=2<br />
echo &quot;this is the $numnd&quot;</address>
<address>&nbsp;</address>
<p class="line874">上述脚本并不会输出&quot;this is the 2nd&quot;而是&quot;this is the &quot;;这是由于shell会去搜索变量numnd的值,而实际上这个变量此时并没有值。这时,我们可以用花括号来告诉shell要打印的是num变量:</p>
<address>num=2<br />
echo &quot;this is the ${num}nd&quot;</address>
<address>&nbsp;</address>
<p class="line874">其输出结果为:this is the 2nd</p>
<p class="line874">Shell脚本中有许多变量是系统自动设定的,我们将在用到这些变量时再作说明。除了只在脚本内有效的普通shell变量外,还有环境变量,即那些由export关键字处理过的变量。本文不讨论环境变量,因为它们一般只在登录脚本中用到。</p>
<p class="line867">&nbsp;</p>


<h2 id="head-5c0a624fbeab7e309e1113dbdb31b4820e24e9ba">2. Shell里的命令</h2>
授权许可:
<p>&nbsp;</p>
* [http://creativecommons.org/licenses/by-sa/2.0/ 创作共享署名协议]
<p class="line867">&nbsp;</p>
* [http://www.gnu.org/copyleft/fdl.html GNU 自由文档许可证]
<h3 id="head-c11876226cc57fd14f72cc943d2fd15a1fa02d48">2.1. Unix 命令</h3>
 
<p>&nbsp;</p>
注意:本文仍然在持续的修订之中,且错漏之处可能较多。如果能够阅读英语的话,可以考虑试试较为完善的 [http://mywiki.wooledge.org/BashGuide/ Wooledge BashGuide]。这个站点除了教程之外,还有一些类似“bash 百科”的内容。[https://gnu.org/s/bash/manual Bash 官方手册]也是你的好朋友。
<p class="line874">在shell脚本中可以使用任意unix命令,不过实际上最为常用的一般都是那些文件和文字操作相关的命令。下面介绍一些常用命令的语法和功能: </p>
 
<pre>  echo &quot;some text&quot;: 在屏幕上输出信息<br /><br />  ls: 文件列表<br /><br />  wc &ndash;l file wc -w file wc -c file: 分别计算文件的行数(line)、单词数(word)和字符数(character)<br /><br />  cp sourcefile destfile: 文件拷贝<br /><br />  mv oldname newname: 重命名文件或移动文件<br /><br />  rm file: 删除文件<br /><br />  grep 'pattern' file: 在文件内搜索字符串或和正则表达式匹配的字符串<br /><br />  cut -b column file: 将指定范围内的文件内容输出到标准输出设备(屏幕)上。比如:输出每行第5至9个字符 cut -b5-9 file.txt,注意不要和cat命令混淆,这是两个完全不同的命令<br /><br />  cat file.txt: 输出文件内容到标准输出设备(屏幕)上<br /><br />  file somefile: 取得文件somefile的文件类型<br /><br />  read var: 提示用户输入,并将输入内容赋值给变量var<br /><br />  sort file.txt: 对file.txt文件所有行进行排序<br /><br />  uniq: 只输出文件中内容不一致的行,如: sort file.txt | uniq<br /><br />  expr: 进行数学运算,如要进行2+3的运算,命令为: expr 2 &quot;+&quot; 3<br /><br />  find: 搜索文件,如根据文件名搜索:find . -name filename -print<br /><br />  tee: 将数据输出到标准输出设备(屏幕) 和文件,比如:somecommand | tee outfile<br /><br />  basename file: 返回不包含路径的文件名,如: basename /bin/tux 会返回 tux<br /><br />  dirname file: 返回文件所在路径,如:dirname /bin/tux 会返回 /bin<br /><br />  head file: 打印文本文件开头几行<br /><br />  tail file : 打印文本文件末尾几行<br /><br />  sed: 是一个基本的查找替换程序。可以从标准输入(如命令管道)读入文本,并将结果输出到标准输出(屏幕);该命令采用正则表达式进行搜索。不要和 shell中的通配符相混淆。比如将 ubuntu 替换为 Ubuntu :cat text.file | sed 's/ubuntu/Ubuntu/' &gt; newtext.file<br /><br />  awk: 用来提取文本文件中的字段。缺省的字段分割符是空格,可以使用 -F 指定其它分割符。cat file.txt | awk -F, '{print $1 &quot;,&quot; $3 }',这里我们使用 , 作为字段分割符,同时打印第一和第三个字段。如果该文件内容为 Adam Bor, 34, IndiaKerry Miller, 22, USA,则上述命令的输出为:Adam Bor, IndiaKerry Miller, USA<br /></pre>
== 从第一行开始 ==
<p>&nbsp;</p>
我们可以使用任意一种文字编辑器,比如gedit、kedit、emacs、vi等来编写shell脚本,它必须以如下行开始(必须放在文件的第一行):
<p class="line867">&nbsp;</p>
 
<h3 id="head-c27835ddb4efde1cc9c508ebb6fcdce6fa1f90d4">2.2. 概念: 管道, 重定向和 backtick</h3>
<source lang=bash>#!/bin/bash</source>
<p>&nbsp;</p>
 
<hr />
此行称为 [https://en.wikipedia.org/wiki/shebang shebang](就是 sharp (#) + bang (!) 的意思),会指引操作系统使用接下来指定的程序运行此文件。此处 <tt>/bin/bash</tt> 执行我们的文件。
<p class="line874">&nbsp;</p>
 
<p class="line874">尽管这些都不是系统命令,不过它们扮演着相当重要的角色。 </p>
一些人使用 <tt>#!/bin/sh</tt> 来让 <tt>sh</tt> 执行文件,按照习惯这表示任何支持 [http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html POSIX shell 命令语言]的 <tt>sh</tt>程序。为了用上我们所喜欢的 <tt>bash</tt> 拓展语法功能,我们就不这么用了。如果你使用别的脚本,例如 <tt>/bin/tcsh</tt>,照着样子加个 <tt>#!</tt> 就行。
<ul>
 
    <li>管道 (|) 将一个命令的输出作为另外一个命令的输入 </li>
编辑结束并保存后,如果直接要执行该脚本,必须先使其具有可执行属性:
</ul>
 
<p class="line867">&nbsp;</p>
<source lang=bash>chmod +x filename</source>
<pre>grep &quot;hello&quot; file.txt | wc -l<br /></pre>
 
<p>&nbsp;</p>
此后在该脚本所在目录下,输入 <tt>./filename<tt> 即可执行该脚本。
<p class="line874">上述命令会在file.txt中搜索包含有&rdquo;hello&rdquo;的行并计算行数,这里grep命令的输出成了wc命令的输入。 </p>
 
<ul>
== 变量 ==
    <li>重定向:将命令的结果输出到文件,而不是标准输出(屏幕) </li>
 
</ul>
Shell 变量默认全都是字符串。
<p class="line867">&nbsp;</p>
 
<pre>&gt;  写入文件并覆盖旧文件<br />   &gt;&gt; 加到文件的尾部,保留旧文件内容<br /></pre>
=== 变量赋值和引用  ===
<p>&nbsp;</p>
 
<ul>
Shell 编程中,使用变量无需事先声明。变量名的命名遵守正则表达式 <tt>[a-zA-Z_][a-zA-Z0-9_]+</tt>,也就是由大小写字母数字和下划线组成,且不能以数字开头。请注意 shell 环境中的确有以数字和特殊符号开头的变量名,但是那些东西不可以用接下来的方式赋值。
    <li>反短斜线 </li>
 
</ul>
需要给变量赋值时,可以这么写:
<p class="line874">反短斜线可以将一个命令的输出作为其它命令的命令行参数。 </p>
 
<pre>find . -mtime -1 -type f -print<br /></pre>
<source lang=bash>varname=值 [var2=val2 ....]</source>
<p>&nbsp;</p>
 
<p class="line874">上述命令可以查找过去24小时(-mtime &ndash;2则表示过去48小时)内修改过的文件。如果你想将上述命令查找到的所有文件打包,则可以使用如下脚本: </p>
请注意这边等号左右不能有空格。
<pre>#!/bin/sh<br /><br />   # The ticks are backticks (`) not normal quotes ('):<br />   tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print`<br /></pre>
要取用一个变量的值,只需在变量名前面加一个 <tt>$</tt>:
<p>&nbsp;</p>
 
<p class="line867">&nbsp;</p>
<source lang=bash># assign
<h2 id="head-766f58c718d1d6f7a0d691638502fc644c1dd828">3. Shell里的流程控制</h2>
a="hello world"  # 等号两边均不能有空格存在
<p>&nbsp;</p>
# print
<p class="line867">&nbsp;</p>
printf '%s\n' "A is: $a"</source>
<h3 id="head-6b610e022239147cf7054d415840f1f8ba4da410">3.1. if 语句</h3>
 
<p>&nbsp;</p>
挑个自己喜欢的编辑器,输入上述内容,并保存为文件 first,然后执行 chmod +x first 使其可执行,最后输入 ./first 执行该脚本。其输出结果如下:
<p class="line874">&quot;if&quot;表达式如果条件为真,则执行then后的部分:</p>
 
<div lang="en" class="codearea" dir="ltr"><script type="text/javascript">
<source lang="bash">
function isnumbered(obj) {
A is: hello world
  return obj.childNodes.length && obj.firstChild.childNodes.length && obj.firstChild.firstChild.className == 'LineNumber';
</source>
 
有时候变量名可能会和其它文字(匹配最长的符合变量名或特殊变量名要求的内容)混淆,比如:
 
<source lang=bash>num=2
echo "this is the $numnd"  # 输出 this is the      — shell 尝试寻找 $numnd 的值
echo "this is the ${num}nd" # 输出 this is the 2nd  — 修好了!
# 花括号可以隔开变量名,但是放歪了的话…
echo "this is the {$num}nd" # 输出 this is the {2}nd — 切是切开了,但是…</source>
 
=== 变量算术 ===
 
Shell 变量默认都是字符串。这也就是说,你尝试这么做,肯定没用:
 
<source lang=bash>var=1
var=$var+1
echo $var # 输出 1+1</source>
 
我们可以用很多方法达成我们的目标。首先是好孩子的方法——C 风格表达式。
 
<source lang=bash>var=0
# bash 里面可以用 (( )) 执行 C 风格的算术表达式。
# 如果你接下来还会读 if 那一段的话,你还会知道这玩意的返回和 C 的非零真假判断一致。
(( var += 1 )) # 这是一种,现在 var 是 1
(( var++ ))    # 这也是一种自增,2
(( var = var * var )) # 怎么来乘法了!var 现在是 4。
let 'var = var / 3'   # 还是只有 bash 才能用的拓展。除法是整数除法,向 0 舍入,1。
# 来一点不一定要 bash 的方法吧,毕竟 sh 还有很多种,总不能全报错了吧。
# $(( )) 会展开成为这个 C 表达式求值的结果。以前 bash 有个 $[ ] 一样,但是别去用。
echo $((var += 2))    # echo 出 3,var 现在是 3。
var=$((var-1))        # 展开成 var=2,var 现在是……还用说吗,2。</source>
 
以前还有人用 expr 之类的外部程序来,不过这属于杀鸡用牛刀。并且调用外部程序浪费时间性能差。
 
<source lang=bash>var=1
var=$(expr "$var" + 1) # expr 收到三个参数 '1' '+' '1',
 
                      # 按照 expr --help 里面写的方法运行
                      # 然后输出替换掉 $() 这里变成 var=2。
 
var=`expr "$var" + 1`  # 前面一行的老写法,千万千万不要学。</source>
 
==  Shell里的流程控制 ==
 
===  if 语句 ===
 
if 表达式如果条件命令组为真,则执行 then 后的部分。标准形式:
 
<source lang=bash>if
  判断命令,可以有很多个,真假取最后的返回值
then
  如果前述为真做什么
[ # 方括号代表可选,别真打进去了!
elif
  可以再来个判断,如果签名为假继续尝试这里
then
  如果前述为真做什么 ]
else
  如果全都不行做什么
fi # 结束,就是倒写的 if 啦。</source>
 
现实生活中一般判断只有一个命令,所以你看到的一般是:
 
<source lang=bash>if ....; then # 你也可以写成 if 之后换行,这样就不用分号了。
  ....
fi</source>
 
大多数情况下,可以使用测试命令来对条件进行测试,比如可以比较字符串、判断文件是否存在及是否可读等等……在 bash 中一般采用更好用的 <tt>[[ ... ]]</tt> 语法进行条件测试,而通用方法是 <tt>[ ... ]<tt>(相当于 <tt>test ...</tt>)。两者都接纳的常用测试语句有:
 
;<tt>-f "filename"</tt>:判断是否是一个文件
;<tt>-x "/bin/ls"</tt>:判断/bin/ls是否存在并有可执行权限
;<tt>-n "$var"</tt>:判断 $var 变量是否有值
;<tt>"$a" == "$b"</tt>:判断$a和$b是否相等
 
前者可以使用 <tt>help [[</tt> 查询用法,后者使用 <tt>help [</tt> (bash) 或 <tt>man test</tt> 查询。下面的语句用到了这个内容:
 
<source lang=bash>if [ "${SHELL}" == "/bin/bash" ]; then
  echo "your login shell is the bash (bourne again shell)"
else
  echo "your login shell is not bash but ${SHELL}"
fi</source>
 
变量 <tt>$SHELL</tt> 包含有登录shell的名称,我们拿它和 <tt>/bin/bash</tt> 进行比较以判断当前使用的shell是否为bash。你可能会问了,要是 bash 路径不是这个呢?
 
=== && 和 || 操作符 ===
 
熟悉C语言的朋友可能会喜欢下面的表达式:
 
<source lang=bash>[ -f "/etc/shadow" ] && echo "This computer uses shadow passwords"</source>
 
这里的 && 就是一个快捷操作符,如果左边的表达式为真(返回 0——“成功”)则执行右边的语句,你也可以把它看作逻辑运算里的与操作。上述脚本表示如果/etc/shadow文件存在,则打印“This computer uses shadow passwords”。
 
同样shell编程中还可以用或操作 (||),例如:
 
<source lang=bash>#!/bin/bash
 
mailfolder=/var/spool/mail/james
[ -r "$mailfolder" ] || { echo "Can not read $mailfolder"; exit 1; }
echo "$mailfolder has mail from:"
grep "^From " $mailfolder</source>
 
该脚本首先判断mailfolder是否可读,如果可读则打印该文件中以"From"开头的行。如果不可读则或操作生效,打印错误信息后脚本退出。需要注意的是,这里我们必须使用如下两个命令:
 
<source lang=bash>{
  echo "Can not read $mailfolder"; # 打印错误信息
  exit 1; # 退出程序
}</source>
 
我们使用花括号以组合命令的形式将两个命令放到一起作为一个命令使用。即使不用与和或操作符,我们也可以用if表达式完成任何事情,但是使用与或操作符会更便利很多。
 
要注意 Shell 中的 && || 程序流操作符不表现任何优先级区别,完全是先看到谁就先处理谁的关系。
 
=== case 语句 ===
 
case表达式可以用来匹配一个给定的字符串,而不是数字(可别和C语言里的switch...case混淆)。
 
<source lang="bash">
case ... in
  ...) do something here
  ;;
esac
</source>
file命令可以辨别出一个给定文件的文件类型,如:file lf.gz,其输出结果为:
 
<source lang="bash">
lf.gz: gzip compressed data, deflated, original filename,
last modified: Mon Aug 27 23:09:18 2001, os: Unix
</source>
 
我们利用这点写了一个名为smartzip的脚本,该脚本可以自动解压bzip2, gzip和zip 类型的压缩文件:
 
<source lang="bash">
#!/bin/bash
 
ftype="$(file "$1")"
case "$ftype" in
"$1: Zip archive"*)
  unzip "$1" ;;
"$1: gzip compressed"*)
  gunzip "$1" ;;
"$1: bzip2 compressed"*)
  bunzip2 "$1" ;;
*)
  echo "File $1 can not be uncompressed with smartzip";;
esac
</source>
 
你可能注意到上面使用了一个特殊变量 {{code|$1}},该变量包含有传递给该脚本的第一个参数值。也就是说,当我们运行:
 
<source lang="bash">
smartzip articles.zip
</source>
 
{{code|$1}} 就是字符串 articles.zip。
 
=== select 循环语句 ===
 
select 循环语句是bash的一种扩展应用,擅长于交互式场合。
 
用户可以从一组不同的值中进行选择:
 
<source lang="bash">
pocket=()
select var in 跳跳糖 糖 很多糖 企鹅糖; do
  echo "除了 $var 还要什么吗?"
  if ((RANDOM%4 == 0)); then
    echo "呀!时间不够了,快上车!"
    break # break 还是那个 break
  fi
  pocket+=("$var")
done
echo "你最后说的那个 $var 弄丢了……"
IFS='、'
echo "现在口袋里只有:${pocket[*]}。"
IFS=$' \t\n'
</source>
 
下面是一个简单的示例:
 
<source lang="bash">
#!/bin/bash
 
echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do
  break;
done
echo "You have selected $var"
</source>
 
该脚本的运行结果如下:
 
<source lang="bash">
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux
</source>
 
=== while/for 循环===
 
在shell中,可以使用如下循环:
 
<source lang="bash">
while ...; do
  ....
done
</source>
 
只要测试表达式条件为真,则while循环将一直运行。关键字"break"用来跳出循环,而关键字”continue”则可以跳过一个循环的余下部分,直接跳到下一次循环中。
 
for循环会查看一个字符串列表(字符串用空格分隔),并将其赋给一个变量:
 
<source lang="bash">
for var in ....; do
  ....
done
</source>
 
下面的示例会把A B C分别打印到屏幕上:
 
<source lang="bash">
#!/bin/bash
 
for var in A B C ; do
  echo "var is $var"
done
</source>
 
下面是一个实用的脚本showrpm,其功能是打印一些RPM包的统计信息:
 
<source lang="bash">
#!/bin/bash
 
# list a content summary of a number of RPM packages
# USAGE: showrpm rpmfile1 rpmfile2 ...
# EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpm
for rpmpackage in "$@"; do
  if [ -r "$rpmpackage" ];then
      echo "=============== $rpmpackage =============="
      rpm -qi -p $rpmpackage
  else
      echo "ERROR: cannot read file $rpmpackage"
  fi
done
</source>
 
这里出现了第二个特殊变量$@,该变量包含有输入的所有命令行参数值。如果你运行showrpm openssh.rpm w3m.rpm webgrep.rpm,那么 "$@"(有引号) 就包含有 3 个字符串,即openssh.rpm, w3m.rpm和 webgrep.rpm。$*的意思是差不多的。但是只有一个字串。如果不加引号,带空格的参数会被截断。
 
== Shell里的一些特殊符号==
 
=== 引号 ===
 
在向程序传递任何参数之前,程序会扩展通配符和变量。这里所谓的扩展是指程序会把通配符(比如*)替换成适当的文件名,把变量替换成变量值。我们可以使用引号来防止这种扩展,先来看一个例子,假设在当前目录下有两个jpg文件:mail.jpg和tux.jpg。
 
<source lang="bash">
#!/bin/bash
 
echo *.jpg  # => mail.jpg tux.jpg
</source>
 
引号(单引号和双引号)可以防止通配符*的扩展:
 
<source lang="bash">
#!/bin/bash
 
echo "*.jpg"  # => *.jpg
echo '*.jpg'  # => *.jpg
</source>
 
其中单引号更严格一些,它可以防止任何变量扩展;而双引号可以防止通配符扩展但允许变量扩展:
 
<source lang="bash">
#!/bin/bash
 
echo $SHELL  # => /bin/bash
echo "$SHELL" # => /bin/bash
echo '$SHELL' # => $SHELL
</source>
 
此外还有一种防止这种扩展的方法,即使用转义字符——反斜杠{{code|\}}:
 
<source lang="bash">
echo \*.jpg  # => *.jpg
echo \$SHELL  # => $SHELL
</source>
 
== Here Document ==
 
当要将几行文字传递给一个命令时,用here document是一种不错的方法。对每个脚本写一段帮助性的文字是很有用的,此时如果使用here document就不必用echo函数一行行输出。Here document以 &lt;&lt; 开头,后面接上一个字符串,这个字符串还必须出现在here document的末尾。下面是一个例子,在该例子中,我们对多个文件进行重命名,并且使用here document打印帮助:
 
<source lang="bash">
#!/bin/bash
 
# we have less than 3 arguments. Print the help text:
if [ $# -lt 3 ] ;; then
cat << HELP
 
ren -- renames a number of files using sed regular expressions USAGE: ren 'regexp' 'replacement' files...
 
EXAMPLE: rename all *.HTM files in *.html:
  ren 'HTM$' 'html' *.HTM
 
HELP                #这里HELP要顶格写,前面不能有空格或者TAB制表符。如果cat一行写成cat &lt;&lt; -HELP,前边可以带TAB.
  exit 0
fi
OLD="$1"
NEW="$2"
# The shift command removes one argument from the list of
# command line arguments.
shift
shift
# $@ contains now all the files:
for file in "$@"; do
  if [ -f "$file" ]&nbsp;; then
      newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`
      if [ -f "$newfile" ]; then
      echo "ERROR: $newfile exists already"
      else
        echo "renaming $file to $newfile ..."
        mv "$file" "$newfile"
      fi
  fi
done
</source>
示例有点复杂,我们需要多花点时间来说明一番。第一个if表达式判断输入命令行参数是否小于3个 (特殊变量$# 表示包含参数的个数) 。如果输入参数小于3个,则将帮助文字传递给cat命令,然后由cat命令将其打印在屏幕上。打印帮助文字后程序退出。如果输入参数等于或大于3个,我们就将第一个参数赋值给变量OLD,第二个参数赋值给变量NEW。下一步,我们使用shift命令将第一个和第二个参数从参数列表中删除,这样原来的第三个参数就成为参数列表$*的第一个参数。然后我们开始循环,命令行参数列表被一个接一个地被赋值给变量$file。接着我们判断该文件是否存在,如果存在则通过sed命令搜索和替换来产生新的文件名。然后将反短斜线内命令结果赋值给newfile。这样我们就达到了目的:得到了旧文件名和新文件名。然后使用 mv命令进行重命名
 
== Shell里的函数  ==
 
如果你写过比较复杂的脚本,就会发现可能在几个地方使用了相同的代码,这时如果用上函数,会方便很多。函数的大致样子如下:
 
<source lang="bash">
# 别笑,bash 里面函数名的确可以这样……
# (POSIX sh 函数名倒是和变量名要求差不多)
我是一个函数() {
  # 函数里面 $1 $2 对应函数所接受到的第一、第二……个参数。
  这里有很多命令
}
</source>
 
函数没有必要声明。只要在执行之前出现定义就行
 
下面是一个名为xtitlebar的脚本,它可以改变终端窗口的名称。这里使用了一个名为help的函数,该函数在脚本中使用了两次:
 
<source lang=bash>#!/bin/bash
 
help()
{
cat << HELP
xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole
USAGE: xtitlebar [-h] "string_for_titelbar"
OPTIONS: -h help text
EXAMPLE: xtitlebar "cvs"
HELP
exit 0
}
# in case of error or if -h is given we call the function help:
if [[ $1 == '' || $1 == '-h' ]]; then
   help
fi
# send the escape sequence to change the xterm titelbar:
echo -e "\033]0;$1\007"
#</source>  
在脚本中提供帮助是一种很好的编程习惯,可以方便其他用户(和自己)使用和理解脚本。
 
== 命令行参数  ==
 
我们已经见过 {{code|$*}} 和 {{code|$1}}, $2 ... $9 等特殊变量,这些特殊变量包含了用户从命令行输入的参数。迄今为止,我们仅仅了解了一些简单的命令行语法(比如一些强制性的参数和查看帮助的-h选项)。但是在编写更复杂的程序时,您可能会发现您需要更多的自定义的选项。通常的惯例是在所有可选的参数之前加一个减号,后面再加上参数值 (比如文件名)。
 
有好多方法可以实现对输入参数的分析,但是下面的使用case表达式的例子无疑是一个不错的方法。
 
<source lang="bash">
#!/bin/bash
help()
{
  cat &lt;&lt; HELP
  This is a generic command line parser demo.
  USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2
HELP
  exit 0
}
 
while [ -n "$1" ]; do
case "$1" in
  -h) help;shift 1;; # function help is called
  -f) opt_f=1;shift 1;; # variable opt_f is set
  -l) opt_l=$2;shift 2;; # -l takes an argument -&gt; shift by 2
  --) shift;break;; # end of options
  -*) echo "error: no such option $1. -h for help";exit 1;;
  *) break;;
esac
done
echo "opt_f is $opt_f"
echo "opt_l is $opt_l"
echo "first arg is $1"
echo "2nd arg is $2"
 
</source>
 
你可以这样运行该脚本:
 
<source lang="bash">
cmdparser -l hello -f -- -somefile1 somefile2
</source>
 
返回结果如下:
 
<source lang="bash">
opt_f is 1
opt_l is hello
first arg is -somefile1
2nd arg is somefile2
</source>
 
这个脚本是如何工作的呢?脚本首先在所有输入命令行参数中进行循环,将输入参数与case表达式进行比较,如果匹配则设置一个变量并且移除该参数。根据unix系统的惯例,首先输入的应该是包含减号的参数。
 
== Shell脚本示例==
 
=== 一般编程步骤===
 
现在我们来讨论编写一个脚本的一般步骤。任何优秀的脚本都应该具有帮助和输入参数。写一个框架脚本(framework.sh),该脚本包含了大多数脚本需要的框架结构,是一个非常不错的主意。这样一来,当我们开始编写新脚本时,可以先执行如下命令:
 
<source lang="bash">
cp framework.sh myscript
</source>
 
然后再插入自己的函数。
 
让我们来看看如下两个示例。
 
=== 二进制到十进制的转换 ===
 
脚本 b2d 将二进制数 (比如 1101) 转换为相应的十进制数。这也是一个用expr命令进行数学运算的例子:
 
<source lang="bash">
#!/bin/bash
# vim: set sw=4 ts=4 et:
help()
{
  cat << HELP
 
b2d -- convert binary to decimal
USAGE: b2d [-h] binarynum
OPTIONS: -h help text
EXAMPLE: b2d 111010
will return 58
HELP
  exit 0
}
}
function nformat(num,chrs,add) {
  var nlen = Math.max(0,chrs-(''+num).length), res = '';
error()
  while (nlen>0) { res += ' '; nlen-- }
{
  return res+num+add;
  # print an error and exit
  echo "$1"
  exit 1
}
}
function addnumber(did, nstart, nstep) {
  var c = document.getElementById(did), l = c.firstChild, n = 1;
lastchar()
  if (!isnumbered(c))
{
    if (typeof nstart == 'undefined') nstart = 1;
  # return the last character of a string in $rval
    if (typeof nstep  == 'undefined') nstep = 1;
  if [ -z "$1" ]; then
    n = nstart;
      # empty string
    while (l != null) {
      rval=""
       if (l.tagName == 'SPAN') {
       return
        var s = document.createElement('SPAN');
  fi
        s.className = 'LineNumber'
  # wc puts some space behind the output this is why we need sed:
        s.appendChild(document.createTextNode(nformat(n,4,' ')));
  numofchar=`echo -n "$1" | sed 's/ //g' | wc -c `
        n += nstep;
  #sed 's/ //g' 所有空白去掉  sed 's/ /\t/g' 所有空白用t代替
        if (l.childNodes.length)
  # now cut out the last char  抓取第numofchar个字节
          l.insertBefore(s, l.firstChild)
  rval=`echo -n "$1" | cut -b $numofchar`
        else
          l.appendChild(s)
      }
      l = l.nextSibling;
    }
  return false;
}
}
function remnumber(did) {
  var c = document.getElementById(did), l = c.firstChild;
chop()
  if (isnumbered(c))
{
    while (l != null) {
  # remove the last character in string and return it in $rval
       if (l.tagName == 'SPAN' && l.firstChild.className == 'LineNumber') l.removeChild(l.firstChild);
  if [ -z "$1" ]; then
       l = l.nextSibling;
      # empty string
    }
      rval=""
  return false;
       return
  fi
  # wc puts some space behind the output this is why we need sed:
  numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
  if [ "$numofchar" = "1" ]; then
      # only one char in string
      rval=""
       return
  fi
  numofcharminus1=`expr $numofchar "-" 1`
  # now cut all but the last char:
  rval=`echo -n "$1" | cut -b -$numofcharminus1`
  #原来的 rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`运行时出错.
  #原因是cut从1开始计数,应该是cut -b 1-${numofcharminus1}
}
}
function togglenumber(did, nstart, nstep) {
  var c = document.getElementById(did);
while [ -n "$1" ]; do
   if (isnumbered(c)) {
case $1 in
     remnumber(did);
  -h) help;shift 1;; # function help is called
  } else {
  --) shift;break;; # end of options
     addnumber(did,nstart,nstep);
  -*) error "error: no such option $1. -h for help";;
   }
  *) break;;
   return false;
esac
done
 
# The main program
sum=0
weight=1
# one arg must be given:
[ -z "$1" ] &amp;&amp; help
binnum="$1"
binnumorig="$1"
while [ -n "$binnum" ]; do
  lastchar "$binnum"
  if [ "$rval" = "1" ]; then
      sum=`expr "$weight" "+" "$sum"`
      # $expr 10 + 10    20 expr提示是计算操作
  fi
  # remove the last position in $binnum
  chop "$binnum"
  binnum="$rval"
  weight=`expr "$weight" "*" 2`
done
echo "binary $binnumorig is decimal $sum"
#
</source>
 
该脚本使用的算法是利用十进制和二进制数权值 (1,2,4,8,16,..),比如二进制"10"可以这样转换成十进制:
 
<source lang="bash">
0 * 1 + 1 * 2 = 2
</source>
 
为了得到单个的二进制数我们是用了lastchar 函数。该函数使用wc –c计算字符个数,然后使用cut命令取出末尾一个字符。Chop函数的功能则是移除最后一个字符。
 
但是还记得前面怎么说的吗?进制转换哪需要这么麻烦:
 
<source lang="bash">
#!/bin/bash
while read -p 'input a binary...' num; do
   if [[ $num == *[!01]* ]]; then
    echo "含有 0 1 之外的字符"
  fi
  echo "$((0x$num))"      # 在 num 头上糊一个 0x 然后跑数学计算——就完事了!
  printf "%d\n" "0x$num"    # printf 也可以凑热闹啊
done
</source>
 
如果你喜欢自己算的话,其实也可以从左到右来(反正数学计算不要有事没事玩 expr 啦):
 
<source lang="bash">#!/bin/bash
# 人人皆知的 Horner 规则
value=0
echo "写一堆 1 0 完了回车"
while read -n 1 char; do
  case $char in
     (0|1) ;;      # 好
    ('')  break;; # 没了
     (*)   echo "你说啥?"; break;;
   esac
  ((value *= 2))
   ((value += char))
done
echo "$value"</source>
 
=== 文件循环移动 ===
 
你可能有这样的需求并一直都这么做:将所有发出邮件保存到一个文件中。但是过了几个月之后,这个文件可能会变得很大以至于该文件的访问速度变慢;下面的脚本 rotatefile 可以解决这个问题。这个脚本可以重命名邮件保存文件(假设为outmail)为outmail.1,而原来的outmail.1就变成了 outmail.2 等等...
 
<source lang="bash">
#!/bin/bash
# vim: set sw=4 ts=4 et:
ver="0.1"
help()
{
  cat << HELP
  rotatefile -- rotate the file name
  USAGE: rotatefile [-h] filename
  OPTIONS: -h help text
  EXAMPLE: rotatefile out
  This will e.g rename out.2 to out.3, out.1 to out.2, out to out.1
  and create an empty out-file
 
  version $ver
 
HELP
 
  exit 0
}
}
</script>  <script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-f5c371b7eea37b1e7bfdc12cca5acd38bf88b99c_000\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><span class="codenumbers">Toggle line numbers</span>
<address><span class="line"><span class="LineNumber">  1 </span>  <span class="ResWord">if</span> <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">;</span> <span class="ID">then</span></span><br />
<span class="line"><span class="LineNumber">  2 </span>    <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span></span><br />
<span class="line"><span class="LineNumber">  3 </span>  <span class="ResWord">elif</span> <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">;</span> <span class="ID">then</span></span><br />
<span class="line"><span class="LineNumber">  4 </span>    <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span></span><br />
<span class="line"><span class="LineNumber">  5 </span>  <span class="ResWord">else</span></span><br />
<span class="line"><span class="LineNumber">  6 </span>    <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span></span><br />
<span class="line"><span class="LineNumber">  7 </span>  <span class="ID">fi</span></span></address>
</div>
<address>&nbsp;</address>
<p class="line874">大多数情况下,可以使用测试命令来对条件进行测试,比如可以比较字符串、判断文件是否存在及是否可读等等&hellip;&hellip;通常用&quot; [ ] &quot;来表示条件测试,注意这里的空格很重要,要确保方括号前后的空格。</p>
<pre>[ -f &quot;somefile&quot; ] :判断是否是一个文件<br />  [ -x &quot;/bin/ls&quot; ] :判断/bin/ls是否存在并有可执行权限<br />  [ -n &quot;$var&quot; ] :判断$var变量是否有值<br />  [ &quot;$a&quot; = &quot;$b&quot; ] :判断$a和$b是否相等</pre>
<p>&nbsp;</p>
<p class="line874">执行man test可以查看所有测试表达式可以比较和判断的类型。下面是一个简单的if语句:</p>
<div lang="en" class="codearea" dir="ltr"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-a3fb8bf838f3565b62e0b99e3059c942a69f48d4_001\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><span class="codenumbers">Toggle line numbers</span>
<address><span class="line"><span class="LineNumber">  1 </span>  <span class="Comment">#!/bin/sh</span></span><br />
<span class="line"><span class="LineNumber">  2 </span></span><br />
<span class="line"><span class="LineNumber">  3 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="String">&quot;$SHELL&quot;</span> <span class="Operator">=</span> <span class="String">&quot;/bin/bash&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br />
<span class="line"><span class="LineNumber">  4 </span>      <span class="ID">echo</span> <span class="String">&quot;your login shell is the bash (bourne again shell)&quot;</span></span><br />
<span class="line"><span class="LineNumber">  5 </span>  <span class="ResWord">else</span></span><br />
<span class="line"><span class="LineNumber">  6 </span>      <span class="ID">echo</span> <span class="String">&quot;your login shell is not bash but $SHELL&quot;</span></span><br />
<span class="line"><span class="LineNumber">  7 </span>  <span class="ID">fi</span></span></address>
</div>
<p>&nbsp;</p>
<p class="line874">变量$SHELL包含有登录shell的名称,我们拿它和/bin/bash进行比较以判断当前使用的shell是否为bash。</p>
<p class="line867">&nbsp;</p>


<h3 id="head-e662a8dc1bc66d276f98f4775de5adccc657c197">3.2. &amp;&amp; 和|| 操作符</h3>
if [[ $1 == '-h' || $1 == '' ]]; then
<p>&nbsp;</p>
   help
<p class="line874">熟悉C语言的朋友可能会喜欢下面的表达式: </p>
fi
<pre>[ -f &quot;/etc/shadow&quot; ] &amp;&amp; echo &quot;This computer uses shadow passwords&quot;<br /></pre>
 
<p>&nbsp;</p>
filename=$1
<p class="line862">这 里的 &amp;&amp; 就是一个快捷操作符,如果左边的表达式为真则执行右边的语句,你也可以把它看作逻辑运算里的与操作。上述脚本表示如果/etc/shadow文件存在,则 打印&rdquo;This computer uses shadow passwords&rdquo;。同样shell编程中还可以用或操作(||),例如: </p>
 
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
# 我们先找到最大的数字再说。
document.write('<a href="#" onclick="return togglenumber(\'CA-860ef357b644a8342b4058c577e45c6a5b440045_002\', 1, 1);" \
max=0
                class="codenumbers">Toggle line numbers<\/a>');
while [ -f "$filename.$((++max))" ]; do
</script><a class="codenumbers" onclick="return togglenumber('CA-860ef357b644a8342b4058c577e45c6a5b440045_002', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
   : # 什么都不用做,我们已经顺手用 ++max 自增了 max 了。
<pre lang="en" id="CA-860ef357b644a8342b4058c577e45c6a5b440045_002" dir="ltr"><span class="line"><span class="LineNumber">  1 </span>  <span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span>  <span class="ID">mailfolder</span><span class="Operator">=</span><span class="Operator">/</span><span class="ID">var</span><span class="Operator">/</span><span class="ID">spool</span><span class="Operator">/</span><span class="ID">mail</span><span class="Operator">/</span><span class="ID">james</span></span><br /><span class="line"><span class="LineNumber">  4 </span>  <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">r</span> <span class="String">&quot;$mailfolder&quot;</span> <span class="Operator">]</span> <span class="Operator">|</span><span class="Operator">|</span> <span class="Operator">{</span> <span class="ID">echo</span> <span class="String">&quot;Can not read $mailfolder&quot;</span> <span class="Operator">;</span> <span class="ID">exit</span> <span class="Number">1</span><span class="Operator">;</span> <span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  5 </span>      <span class="ID">echo</span> <span class="String">&quot;$mailfolder has mail from:&quot;</span></span><br /><span class="line"><span class="LineNumber">   6 </span>      <span class="ID">grep</span> <span class="String">&quot;^From &quot;</span><span class="Error"> </span><span class="Error">$</span><span class="ID">mailfolder</span></span></pre>
done
</div>
 
<p>&nbsp;</p>
# 然后从最大的一路重命名下来。
<p class="line874">该脚本首先判断mailfolder是否可读,如果可读则打印该文件中的&quot;From&quot; 一行。如果不可读则或操作生效,打印错误信息后脚本退出。需要注意的是,这里我们必须使用如下两个命令: </p>
for ((i=max; i>0; i--)); do
<pre>-打印错误信息<br /><br />  -退出程序<br /></pre>
   # 数字加个 1,好给前一个让位子。
<p>&nbsp;</p>
   mv "$filename.$i" "$filename.$((i+1))"
<p class="line874">我们使用花括号以匿名函数的形式将两个命令放到一起作为一个命令使用;普通函数稍后再作说明。即使不用与和或操作符,我们也可以用if表达式完成任何事情,但是使用与或操作符会更便利很多。 </p>
done
<p class="line867">&nbsp;</p>
   
<h3 id="head-d85f4c842c4992698e9924ceeb01337db3650489">3.3. case 语句</h3>
# 最后我们点名要重命名的:
<p>&nbsp;</p>
if [ -f "$filename" ]; then
<p class="line874">case表达式可以用来匹配一个给定的字符串,而不是数字(可别和C语言里的switch...case混淆)。 </p>
  mv "$filename" "$filename.1"
<pre>case ... in<br />      ...) do something here ;;<br />  esac<br /></pre>
fi
<p>&nbsp;</p>
 
<p class="line874">让我们看一个例子,file命令可以辨别出一个给定文件的文件类型,如:file lf.gz,其输出结果为: </p>
# 重新创建一下。
<pre>lf.gz: gzip compressed data, deflated, original filename,<br />   last modified: Mon Aug 27 23:09:18 2001, os: Unix<br /></pre>
: > "$filename"
<p>&nbsp;</p>
 
<p class="line874">我们利用这点写了一个名为smartzip的脚本,该脚本可以自动解压bzip2, gzip和zip 类型的压缩文件: </p>
</source>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
 
document.write('<a href="#" onclick="return togglenumber(\'CA-c663a0073c2d49110ab4f3f23f7f6ef77a138b02_003\', 1, 1);" \
== 脚本调试==
                class="codenumbers">Toggle line numbers<\/a>');
 
</script><a class="codenumbers" onclick="return togglenumber('CA-c663a0073c2d49110ab4f3f23f7f6ef77a138b02_003', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
最简单的调试方法当然是使用echo命令。你可以在任何怀疑出错的地方用echo打印变量值,这也是大部分shell程序员花费80%的时间用于调试的原因。Shell脚本的好处在于无需重新编译,而插入一个echo命令也不需要多少时间。
<pre lang="en" id="CA-c663a0073c2d49110ab4f3f23f7f6ef77a138b02_003" dir="ltr"><span class="line"><span class="LineNumber">  1 </span>   <span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">   2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span>  <span class="ID">ftype</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">file</span> <span class="String">&quot;$1&quot;</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  4 </span>  <span class="ID">case</span> <span class="String">&quot;$ftype&quot;</span> <span class="ResWord">in</span></span><br /><span class="line"><span class="LineNumber">  5 </span>  <span class="String">&quot;$1: Zip archive&quot;</span><span class="Operator">*</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  6 </span>      <span class="ID">unzip</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  7 </span>  <span class="String">&quot;$1: gzip compressed&quot;</span><span class="Operator">*</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  8 </span>      <span class="ID">gunzip</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  9 </span>  <span class="String">&quot;$1: bzip2 compressed&quot;</span><span class="Operator">*</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber"> 10 </span>      <span class="ID">bunzip2</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  11 </span>  <span class="Operator">*</span><span class="Operator">)</span> <span class="ID">error</span> <span class="String">&quot;File $1 can not be uncompressed with smartzip&quot;</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  12 </span>  <span class="ID">esac</span><br /><strong>ERROR: EOF in multi-line statement</strong><br /></span></pre>
 
</div>
shell也有一个真正的调试模式,如果脚本"strangescript"出错,可以使用如下命令进行调试:
<p>&nbsp;</p>
 
<p class="line874">你可能注意到上面使用了一个特殊变量$1,该变量包含有传递给该脚本的第一个参数值。也就是说,当我们运行: </p>
<source lang="bash">
<pre>smartzip articles.zip<br /></pre>
sh -x strangescript
<p>&nbsp;</p>
</source>
<p class="line874">$1 就是字符串 articles.zip。 </p>
 
<p class="line867">&nbsp;</p>
上述命令会执行该脚本,同时显示所有变量的值。
<h3 id="head-bd7078b3d00a5a6449e60d03d432645852c10a3a">3.4. select 语句</h3>
 
<p>&nbsp;</p>
shell还有一个不执行脚本只检查语法的模式,命令如下:
<p class="line874">select表达式是bash的一种扩展应用,擅长于交互式场合。用户可以从一组不同的值中进行选择:</p>
 
<p class="line867">&nbsp;</p>
<source lang="bash">
<div lang="en" class="codearea" dir="ltr"><script type="text/javascript">
sh -n your_script
document.write('<a href="#" onclick="return togglenumber(\'CA-1372e104ca0ef28128f5a5bc7daa780e167ad6f9_004\', 1, 1);" \
</source>
                class="codenumbers">Toggle line numbers<\/a>');
 
</script><a href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#" onclick="return togglenumber('CA-1372e104ca0ef28128f5a5bc7daa780e167ad6f9_004', 1, 1);" class="codenumbers">Toggle line numbers</a>
这个命令会返回所有语法错误。
<address><span class="line"><span class="LineNumber">  1 </span><span class="ID">select</span> <span class="ID">var</span> <span class="ResWord">in</span> <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span> <span class="Operator">;</span> <span class="ID">do</span></span><br />
 
<span class="line"><span class="LineNumber">  2 </span><span class="Error"> </span><span class="ResWord">break</span></span><br />
我们希望你现在已经可以开始编写自己的shell脚本了,尽情享受这份乐趣吧! :)
<span class="line"><span class="LineNumber">  3 </span><span class="ID">done</span></span><br />
 
<span class="line"><span class="LineNumber">  4 </span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span> <span class="ID">now</span><span class="Error"> </span><span class="Error">$</span><span class="ID">var</span> <span class="ID">can</span> <span class="ID">be</span> <span class="ID">used</span> <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span></span></address>
</div>
<p>&nbsp;</p>
<p class="line874">下面是一个简单的示例:</p>
<div lang="en" class="codearea" dir="ltr"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-c92b7b6a34e56af6238cf6e11462e8411a656b79_005\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#" onclick="return togglenumber('CA-c92b7b6a34e56af6238cf6e11462e8411a656b79_005', 1, 1);" class="codenumbers">Toggle line numbers</a>
<address><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br />
<span class="line"><span class="LineNumber">  2 </span></span><br />
<span class="line"><span class="LineNumber">  3 </span><span class="ID">echo</span> <span class="String">&quot;What is your favourite OS?&quot;</span></span><br />
<span class="line"><span class="LineNumber">  4 </span><span class="ID">select</span> <span class="ID">var</span> <span class="ResWord">in</span> <span class="String">&quot;Linux&quot;</span> <span class="String">&quot;Gnu Hurd&quot;</span> <span class="String">&quot;Free BSD&quot;</span> <span class="String">&quot;Other&quot;</span><span class="Operator">;</span> <span class="ID">do</span></span><br />
<span class="line"><span class="LineNumber">  5 </span><span class="Error"> </span><span class="Error"> </span><span class="Error"> </span><span class="Error"> </span><span class="ResWord">break</span></span><br />
<span class="line"><span class="LineNumber">  6 </span><span class="ID">done</span></span><br />
<span class="line"><span class="LineNumber">  7 </span><span class="ID">echo</span> <span class="String">&quot;You have selected $var&quot;</span></span></address>
</div>
<address>&nbsp;</address>
<p class="line874">该脚本的运行结果如下:</p>
<address>What is your favourite OS?<br />
1) Linux<br />
2) Gnu Hurd<br />
3) Free BSD<br />
4) Other<br />
#? 1<br />
You have selected Linux</address>
<address>&nbsp;</address>
<p class="line867">&nbsp;</p>


<h3 id="head-a9cadb7fe406c8a167b3c2bfed01bcc134937cda">3.5. while/for 循环</h3>
[[Category:程序开发]]
<p>&nbsp;</p>
<hr />
<p class="line874">&nbsp;</p>
<p class="line874">在shell中,可以使用如下循环: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-c0248677e3766e700161c1cefa1b61f2c2c1c26f_006\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-c0248677e3766e700161c1cefa1b61f2c2c1c26f_006', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-c0248677e3766e700161c1cefa1b61f2c2c1c26f_006" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="ResWord">while</span> <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  2 </span>  <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ID">done</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">只要测试表达式条件为真,则while循环将一直运行。关键字&quot;break&quot;用来跳出循环,而关键字&rdquo;continue&rdquo;则可以跳过一个循环的余下部分,直接跳到下一次循环中。 </p>
<p class="line874">for循环会查看一个字符串列表(字符串用空格分隔),并将其赋给一个变量: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-f7ff0cc0d595ae94a0160140e3cb2fd752455c11_007\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-f7ff0cc0d595ae94a0160140e3cb2fd752455c11_007', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-f7ff0cc0d595ae94a0160140e3cb2fd752455c11_007" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="ResWord">for</span> <span class="ID">var</span> <span class="ResWord">in</span> <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  2 </span>  <span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ID">done</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">下面的示例会把A B C分别打印到屏幕上: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-1cb1f1e6097b29798c83492d0561c51dcaedc677_008\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-1cb1f1e6097b29798c83492d0561c51dcaedc677_008', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-1cb1f1e6097b29798c83492d0561c51dcaedc677_008" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ResWord">for</span> <span class="ID">var</span> <span class="ResWord">in</span> <span class="ID">A</span> <span class="ID">B</span> <span class="ID">C</span> <span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  4 </span>  <span class="ID">echo</span> <span class="String">&quot;var is $var&quot;</span></span><br /><span class="line"><span class="LineNumber">  5 </span><span class="ID">done</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">下面是一个实用的脚本showrpm,其功能是打印一些RPM包的统计信息: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-3dba5c48c0c1bb55da514604393db8e315aa812f_009\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-3dba5c48c0c1bb55da514604393db8e315aa812f_009', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-3dba5c48c0c1bb55da514604393db8e315aa812f_009" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="Comment"># list a content summary of a number of RPM packages</span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="Comment"># USAGE: showrpm rpmfile1 rpmfile2 ...</span></span><br /><span class="line"><span class="LineNumber">  5 </span><span class="Comment"># EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpm</span></span><br /><span class="line"><span class="LineNumber">  6 </span><span class="ResWord">for</span> <span class="ID">rpmpackage</span> <span class="ResWord">in</span><span class="Error"> </span><span class="Error">$</span><span class="Operator">*</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  7 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">r</span> <span class="String">&quot;$rpmpackage&quot;</span> <span class="Operator">]</span><span class="Operator">;</span><span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  8 </span>      <span class="ID">echo</span> <span class="String">&quot;=============== $rpmpackage ==============&quot;</span></span><br /><span class="line"><span class="LineNumber">  9 </span>      <span class="ID">rpm</span> <span class="Operator">-</span><span class="ID">qi</span> <span class="Operator">-</span><span class="ID">p</span><span class="Error"> </span><span class="Error">$</span><span class="ID">rpmpackage</span></span><br /><span class="line"><span class="LineNumber">  10 </span>  <span class="ResWord">else</span></span><br /><span class="line"><span class="LineNumber">  11 </span>      <span class="ID">echo</span> <span class="String">&quot;ERROR: cannot read file $rpmpackage&quot;</span></span><br /><span class="line"><span class="LineNumber">  12 </span>  <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  13 </span><span class="ID">done</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">这 里出现了第二个特殊变量$*,该变量包含有输入的所有命令行参数值。如果你运行showrpm openssh.rpm w3m.rpm webgrep.rpm,那么 $* 就包含有 3 个字符串,即openssh.rpm, w3m.rpm和 webgrep.rpm。 </p>
<p class="line867">&nbsp;</p>
<h2 id="head-6a37b8ac17c33faa70e898fcb6cc248a2bb2a128">4. Shell里的一些特殊符号</h2>
<p>&nbsp;</p>
<hr />
<p class="line874">&nbsp;</p>
<p class="line867">&nbsp;</p>
<h3 id="head-724702f87755bfd26419fa1d5c916a762d3b74bb">4.1. 引号</h3>
<p>&nbsp;</p>
<hr />
<p class="line874">&nbsp;</p>
<p class="line874">在向程序传递任何参数之前,程序会扩展通配符和变量。这里所谓的扩展是指程序会把通配符(比如*)替换成适当的文件名,把变量替换成变量值。我们可以使用引号来防止这种扩展,先来看一个例子,假设在当前目录下有两个jpg文件:mail.jpg和tux.jpg。 </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-cca50ec62fd5a61b6ff64c3060efdd8a04b56607_010\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-cca50ec62fd5a61b6ff64c3060efdd8a04b56607_010', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-cca50ec62fd5a61b6ff64c3060efdd8a04b56607_010" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ID">echo</span> <span class="Operator">*</span><span class="Operator">.</span><span class="ID">jpg</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">运行结果为: </p>
<pre>mail.jpg tux.jpg<br /></pre>
<p>&nbsp;</p>
<p class="line874">引号(单引号和双引号)可以防止通配符*的扩展: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-861e22b4d7d455ed8c88718e1d1c88def6b92a45_011\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-861e22b4d7d455ed8c88718e1d1c88def6b92a45_011', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-861e22b4d7d455ed8c88718e1d1c88def6b92a45_011" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ID">echo</span> <span class="String">&quot;*.jpg&quot;</span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="ID">echo</span> <span class="String">'*.jpg'</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">其运行结果为: </p>
<pre>*.jpg<br />  *.jpg<br /></pre>
<p>&nbsp;</p>
<p class="line874">其中单引号更严格一些,它可以防止任何变量扩展;而双引号可以防止通配符扩展但允许变量扩展: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-d1585cc917e2f453edf18f3e887231b88ada9708_012\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-d1585cc917e2f453edf18f3e887231b88ada9708_012', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-d1585cc917e2f453edf18f3e887231b88ada9708_012" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ID">echo</span><span class="Error"> </span><span class="Error">$</span><span class="ID">SHELL</span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="ID">echo</span> <span class="String">&quot;$SHELL&quot;</span></span><br /><span class="line"><span class="LineNumber">  5 </span><span class="ID">echo</span> <span class="String">'$SHELL'</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">运行结果为: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-45b48036e40d65c70df271f2ea697532de3a4ba6_013\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-45b48036e40d65c70df271f2ea697532de3a4ba6_013', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-45b48036e40d65c70df271f2ea697532de3a4ba6_013" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Operator">/</span><span class="ID">bin</span><span class="Operator">/</span><span class="ID">bash</span></span><br /><span class="line"><span class="LineNumber">  2 </span><span class="Operator">/</span><span class="ID">bin</span><span class="Operator">/</span><span class="ID">bash</span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="Error">$</span><span class="ID">SHELL</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">此外还有一种防止这种扩展的方法,即使用转义字符&mdash;&mdash;反斜杆: </p>
<pre>echo *.jpg<br />  echo $SHELL<br /></pre>
<p>&nbsp;</p>
<p class="line874">输出结果为: </p>
<pre>*.jpg<br />  $SHELL<br /></pre>
<p>&nbsp;</p>
<p class="line867">&nbsp;</p>
<h3 id="head-1f704b93b14943ab8d5f1637a12f254130e2c8ed">4.2. Here documents</h3>
<p>&nbsp;</p>
<p class="line862">当 要将几行文字传递给一个命令时,here documents一种不错的方法。对每个脚本写一段帮助性的文字是很有用的,此时如果使用here documents就不必用echo函数一行行输出。Here document以 &lt;&lt; 开头,后面接上一个字符串,这个字符串还必须出现在here document的末尾。下面是一个例子,在该例子中,我们对多个文件进行重命名,并且使用here documents打印帮助: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-cb6508d380a72da28fa9a5b846a25d55eea1e838_014\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-cb6508d380a72da28fa9a5b846a25d55eea1e838_014', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-cb6508d380a72da28fa9a5b846a25d55eea1e838_014" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="Comment"># we have less than 3 arguments. Print the help text:</span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="ResWord">if</span> <span class="Operator">[</span><span class="Error"> </span><span class="Error">$</span><span class="Comment"># -lt 3 ] ; then</span></span><br /><span class="line"><span class="LineNumber">  5 </span><span class="ID">cat</span> <span class="Operator">&lt;</span> <span class="ID">ren</span> <span class="Operator">-</span><span class="Operator">-</span> <span class="ID">renames</span> <span class="ID">a</span> <span class="ID">number</span> <span class="ID">of</span> <span class="ID">files</span> <span class="ID">using</span> <span class="ID">sed</span> <span class="ID">regular</span> <span class="ID">expressions</span></span><br /><span class="line"><span class="LineNumber">  6 </span></span><br /><span class="line"><span class="LineNumber">  7 </span><span class="ID">USAGE</span><span class="Operator">:</span> <span class="ID">ren</span> <span class="String">'regexp'</span> <span class="String">'replacement'</span> <span class="ID">files</span><span class="Operator">.</span><span class="Operator">.</span><span class="Operator">.</span></span><br /><span class="line"><span class="LineNumber">  8 </span></span><br /><span class="line"><span class="LineNumber">  9 </span><span class="ID">EXAMPLE</span><span class="Operator">:</span> <span class="ID">rename</span> <span class="ID">all</span> <span class="Operator">*</span><span class="Operator">.</span><span class="ID">HTM</span> <span class="ID">files</span> <span class="ResWord">in</span> <span class="Operator">*</span><span class="Operator">.</span><span class="ID">html</span><span class="Operator">:</span></span><br /><span class="line"><span class="LineNumber">  10 </span>  <span class="ID">ren</span> <span class="String">'HTM$'</span> <span class="String">'html'</span> <span class="Operator">*</span><span class="Operator">.</span><span class="ID">HTM</span></span><br /><span class="line"><span class="LineNumber">  11 </span></span><br /><span class="line"><span class="LineNumber">  12 </span><span class="ID">HELP</span></span><br /><span class="line"><span class="LineNumber">  13 </span>  <span class="ID">exit</span> <span class="Number">0</span></span><br /><span class="line"><span class="LineNumber">  14 </span><span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  15 </span></span><br /><span class="line"><span class="LineNumber">  16 </span><span class="ID">OLD</span><span class="Operator">=</span><span class="String">&quot;$1&quot;</span></span><br /><span class="line"><span class="LineNumber">  17 </span><span class="ID">NEW</span><span class="Operator">=</span><span class="String">&quot;$2&quot;</span></span><br /><span class="line"><span class="LineNumber">  18 </span><span class="Comment"># The shift command removes one argument from the list of</span></span><br /><span class="line"><span class="LineNumber">  19 </span><span class="Comment"># command line arguments.</span></span><br /><span class="line"><span class="LineNumber">  20 </span><span class="ID">shift</span></span><br /><span class="line"><span class="LineNumber">  21 </span><span class="ID">shift</span></span><br /><span class="line"><span class="LineNumber">  22 </span><span class="Comment"># $* contains now all the files:</span></span><br /><span class="line"><span class="LineNumber">  23 </span><span class="ResWord">for</span> <span class="ID">file</span> <span class="ResWord">in</span><span class="Error"> </span><span class="Error">$</span><span class="Operator">*</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  24 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">f</span> <span class="String">&quot;$file&quot;</span> <span class="Operator">]</span> <span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  25 </span>      <span class="ID">newfile</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">echo</span> <span class="String">&quot;$file&quot;</span> <span class="Operator">|</span> <span class="ID">sed</span> <span class="String">&quot;s/${OLD}/${NEW}/g&quot;</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  26 </span>      <span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">f</span> <span class="String">&quot;$newfile&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  27 </span><span class="Error"> </span><span class="Error"> </span><span class="Error"> </span><span class="Error"> </span>  <span class="ID">echo</span> <span class="String">&quot;ERROR: $newfile exists already&quot;</span></span><br /><span class="line"><span class="LineNumber">  28 </span>      <span class="ResWord">else</span></span><br /><span class="line"><span class="LineNumber">  29 </span>        <span class="ID">echo</span> <span class="String">&quot;renaming $file to $newfile ...&quot;</span></span><br /><span class="line"><span class="LineNumber">  30 </span>        <span class="ID">mv</span> <span class="String">&quot;$file&quot;</span> <span class="String">&quot;$newfile&quot;</span></span><br /><span class="line"><span class="LineNumber">  31 </span>      <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  32 </span>  <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  33 </span><span class="ID">done</span><br /><strong>ERROR: EOF in multi-line statement</strong><br /></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">这 个示例有点复杂,我们需要多花点时间来说明一番。第一个if表达式判断输入命令行参数是否小于3个 (特殊变量$# 表示包含参数的个数) 。如果输入参数小于3个,则将帮助文字传递给cat命令,然后由cat命令将其打印在屏幕上。打印帮助文字后程序退出。如果输入参数等于或大于3个,我们 就将第一个参数赋值给变量OLD,第二个参数赋值给变量NEW。下一步,我们使用shift命令将第一个和第二个参数从参数列表中删除,这样原来的第三个 参数就成为参数列表$*的第一个参数。然后我们开始循环,命令行参数列表被一个接一个地被赋值给变量$file。接着我们判断该文件是否存在,如果存在则 通过sed命令搜索和替换来产生新的文件名。然后将反短斜线内命令结果赋值给newfile。这样我们就达到了目的:得到了旧文件名和新文件名。然后使用 mv命令进行重命名。 </p>
<p class="line867">&nbsp;</p>
<h2 id="head-0f2fd35195cd3f6090de7c97837696d49290d677">5. Shell里的函数</h2>
<p>&nbsp;</p>
<p class="line874">如果你写过比较复杂的脚本,就会发现可能在几个地方使用了相同的代码,这时如果用上函数,会方便很多。函数的大致样子如下: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-8321b263dc991021d79d7ce9ed777c5992cc3b17_015\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-8321b263dc991021d79d7ce9ed777c5992cc3b17_015', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-8321b263dc991021d79d7ce9ed777c5992cc3b17_015" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="ID">functionname</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  2 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="Comment"># inside the body $1 is the first argument given to the function</span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="Comment"># $2 the second ...</span></span><br /><span class="line"><span class="LineNumber">  5 </span><span class="ID">body</span></span><br /><span class="line"><span class="LineNumber">  6 </span><span class="Operator">}</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">你需要在每个脚本的开始对函数进行声明。 </p>
<p class="line874">下面是一个名为xtitlebar的脚本,它可以改变终端窗口的名称。这里使用了一个名为help的函数,该函数在脚本中使用了两次: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-44e64264e26782b13781561b1645e84a2a64125b_016\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-44e64264e26782b13781561b1645e84a2a64125b_016', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-44e64264e26782b13781561b1645e84a2a64125b_016" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span><span class="Comment"># vim: set sw=4 ts=4 et:</span></span><br /><span class="line"><span class="LineNumber">  3 </span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="ID">help</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  5 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  6 </span>  <span class="ID">cat</span> <span class="Operator">&lt;</span> <span class="ID">xtitlebar</span> <span class="Operator">-</span><span class="Operator">-</span> <span class="ID">change</span> <span class="ID">the</span> <span class="ID">name</span> <span class="ID">of</span> <span class="ID">an</span> <span class="ID">xterm</span><span class="Operator">,</span> <span class="ID">gnome</span><span class="Operator">-</span><span class="ID">terminal</span> <span class="ResWord">or</span> <span class="ID">kde</span> <span class="ID">konsole</span></span><br /><span class="line"><span class="LineNumber">  7 </span></span><br /><span class="line"><span class="LineNumber">  8 </span><span class="ID">USAGE</span><span class="Operator">:</span> <span class="ID">xtitlebar</span> <span class="Operator">[</span><span class="Operator">-</span><span class="ID">h</span><span class="Operator">]</span> <span class="String">&quot;string_for_titelbar&quot;</span></span><br /><span class="line"><span class="LineNumber">  9 </span></span><br /><span class="line"><span class="LineNumber">  10 </span><span class="ID">OPTIONS</span><span class="Operator">:</span> <span class="Operator">-</span><span class="ID">h</span> <span class="ID">help</span> <span class="ID">text</span></span><br /><span class="line"><span class="LineNumber">  11 </span></span><br /><span class="line"><span class="LineNumber">  12 </span><span class="ID">EXAMPLE</span><span class="Operator">:</span> <span class="ID">xtitlebar</span> <span class="String">&quot;cvs&quot;</span></span><br /><span class="line"><span class="LineNumber">  13 </span></span><br /><span class="line"><span class="LineNumber">  14 </span><span class="ID">HELP</span></span><br /><span class="line"><span class="LineNumber">  15 </span>  <span class="ID">exit</span> <span class="Number">0</span></span><br /><span class="line"><span class="LineNumber">  16 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  17 </span></span><br /><span class="line"><span class="LineNumber">  18 </span><span class="Comment"># in case of error or if -h is given we call the function help:</span></span><br /><span class="line"><span class="LineNumber">  19 </span><span class="Operator">[</span> <span class="Operator">-</span><span class="ID">z</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span> <span class="Operator">&amp;</span><span class="Operator">&amp;</span> <span class="ID">help</span></span><br /><span class="line"><span class="LineNumber">  20 </span><span class="Operator">[</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">=</span> <span class="String">&quot;-h&quot;</span> <span class="Operator">]</span> <span class="Operator">&amp;</span><span class="Operator">&amp;</span> <span class="ID">help</span></span><br /><span class="line"><span class="LineNumber">  21 </span></span><br /><span class="line"><span class="LineNumber">  22 </span><span class="Comment"># send the escape sequence to change the xterm titelbar:</span></span><br /><span class="line"><span class="LineNumber">  23 </span><span class="ID">echo</span> <span class="Operator">-</span><span class="ID">e</span> <span class="String">&quot;33]0;$107&quot;</span></span><br /><span class="line"><span class="LineNumber">  24 </span><span class="Comment">#</span></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">在脚本中提供帮助是一种很好的编程习惯,可以方便其他用户(和自己)使用和理解脚本。 </p>
<p class="line867">&nbsp;</p>
<h2 id="head-78551a773fa22f0d7d4e4cb09629d275c2d48220">6. 命令行参数</h2>
<p>&nbsp;</p>
<p class="line874">我 们已经见过$* 和 $1, $2 ... $9 等特殊变量,这些特殊变量包含了用户从命令行输入的参数。迄今为止,我们仅仅了解了一些简单的命令行语法(比如一些强制性的参数和查看帮助的-h选项)。 但是在编写更复杂的程序时,您可能会发现您需要更多的自定义的选项。通常的惯例是在所有可选的参数之前加一个减号,后面再加上参数值 (比如文件名)。 </p>
<p class="line874">有好多方法可以实现对输入参数的分析,但是下面的使用case表达式的例子无疑是一个不错的方法。 </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-b5a643119a63f5eea1744e170bb7cbd6d65b8df8_017\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-b5a643119a63f5eea1744e170bb7cbd6d65b8df8_017', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-b5a643119a63f5eea1744e170bb7cbd6d65b8df8_017" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ID">help</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  5 </span>  <span class="ID">cat</span> <span class="Operator">&lt;</span> <span class="ID">This</span> <span class="ResWord">is</span> <span class="ID">a</span> <span class="ID">generic</span> <span class="ID">command</span> <span class="ID">line</span> <span class="ID">parser</span> <span class="ID">demo</span><span class="Operator">.</span></span><br /><span class="line"><span class="LineNumber">  6 </span>  <span class="ID">USAGE</span> <span class="ID">EXAMPLE</span><span class="Operator">:</span> <span class="ID">cmdparser</span> <span class="Operator">-</span><span class="ID">l</span> <span class="ID">hello</span> <span class="Operator">-</span><span class="ID">f</span> <span class="Operator">-</span><span class="Operator">-</span> <span class="Operator">-</span><span class="ID">somefile1</span> <span class="ID">somefile2</span></span><br /><span class="line"><span class="LineNumber">  7 </span>  <span class="ID">HELP</span></span><br /><span class="line"><span class="LineNumber">  8 </span>  <span class="ID">exit</span> <span class="Number">0</span></span><br /><span class="line"><span class="LineNumber">  9 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  10 </span></span><br /><span class="line"><span class="LineNumber">  11 </span><span class="ResWord">while</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  12 </span><span class="ID">case</span><span class="Error"> </span><span class="Error">$</span><span class="Number">1</span> <span class="ResWord">in</span></span><br /><span class="line"><span class="LineNumber">  13 </span>  <span class="Operator">-</span><span class="ID">h</span><span class="Operator">)</span> <span class="ID">help</span><span class="Operator">;</span><span class="ID">shift</span> <span class="Number">1</span><span class="Operator">;</span><span class="Operator">;</span> <span class="Comment"># function help is called</span></span><br /><span class="line"><span class="LineNumber">  14 </span>  <span class="Operator">-</span><span class="ID">f</span><span class="Operator">)</span> <span class="ID">opt_f</span><span class="Operator">=</span><span class="Number">1</span><span class="Operator">;</span><span class="ID">shift</span> <span class="Number">1</span><span class="Operator">;</span><span class="Operator">;</span> <span class="Comment"># variable opt_f is set</span></span><br /><span class="line"><span class="LineNumber">  15 </span>  <span class="Operator">-</span><span class="ID">l</span><span class="Operator">)</span> <span class="ID">opt_l</span><span class="Operator">=</span><span class="Error">$</span><span class="Number">2</span><span class="Operator">;</span><span class="ID">shift</span> <span class="Number">2</span><span class="Operator">;</span><span class="Operator">;</span> <span class="Comment"># -l takes an argument -&gt; shift by 2</span></span><br /><span class="line"><span class="LineNumber">  16 </span>  <span class="Operator">-</span><span class="Operator">-</span><span class="Operator">)</span> <span class="ID">shift</span><span class="Operator">;</span><span class="ResWord">break</span><span class="Operator">;</span><span class="Operator">;</span> <span class="Comment"># end of options</span></span><br /><span class="line"><span class="LineNumber">  17 </span>  <span class="Operator">-</span><span class="Operator">*</span><span class="Operator">)</span> <span class="ID">echo</span> <span class="String">&quot;error: no such option $1. -h for help&quot;</span><span class="Operator">;</span><span class="ID">exit</span> <span class="Number">1</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  18 </span>  <span class="Operator">*</span><span class="Operator">)</span> <span class="ResWord">break</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  19 </span><span class="ID">esac</span></span><br /><span class="line"><span class="LineNumber">  20 </span><span class="ID">done</span></span><br /><span class="line"><span class="LineNumber">  21 </span></span><br /><span class="line"><span class="LineNumber">  22 </span><span class="ID">echo</span> <span class="String">&quot;opt_f is $opt_f&quot;</span></span><br /><span class="line"><span class="LineNumber">  23 </span><span class="ID">echo</span> <span class="String">&quot;opt_l is $opt_l&quot;</span></span><br /><span class="line"><span class="LineNumber">  24 </span><span class="ID">echo</span> <span class="String">&quot;first arg is $1&quot;</span></span><br /><span class="line"><span class="LineNumber">  25 </span><span class="ID">echo</span> <span class="String">&quot;2nd arg is $2&quot;</span><br /><strong>ERROR: EOF in multi-line statement</strong><br /></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">你可以这样运行该脚本: </p>
<pre>cmdparser -l hello -f -- -somefile1 somefile2<br /></pre>
<p>&nbsp;</p>
<p class="line874">返回结果如下: </p>
<pre>opt_f is 1<br />  opt_l is hello<br />  first arg is -somefile1<br />  2nd arg is somefile2<br /></pre>
<p>&nbsp;</p>
<p class="line874">这个脚本是如何工作的呢?脚本首先在所有输入命令行参数中进行循环,将输入参数与case表达式进行比较,如果匹配则设置一个变量并且移除该参数。根据unix系统的惯例,首先输入的应该是包含减号的参数。 </p>
<p class="line867">&nbsp;</p>
<h2 id="head-7f5dea156e61d0b3b59bb542eb03e598b8f780e9">7. Shell脚本示例</h2>
<p>&nbsp;</p>
<hr />
<p class="line874">&nbsp;</p>
<p class="line867">&nbsp;</p>
<h3 id="head-682486eda880b6f6b103fb8ac80a03fca007152c">7.1. 一般编程步骤</h3>
<p>&nbsp;</p>
<p class="line874">现在我们来讨论编写一个脚本的一般步骤。任何优秀的脚本都应该具有帮助和输入参数。写一个框架脚本(framework.sh),该脚本包含了大多数脚本需要的框架结构,是一个非常不错的主意。这样一来,当我们开始编写新脚本时,可以先执行如下命令: </p>
<pre>cp framework.sh myscript<br /></pre>
<p>&nbsp;</p>
<p class="line874">然后再插入自己的函数。 </p>
<p class="line874">让我们来看看如下两个示例。 </p>
<p class="line867">&nbsp;</p>
<h3 id="head-236d3314f32da0ef477a5dfefff157acd85f6064">7.2. 二进制到十进制的转换</h3>
<p>&nbsp;</p>
<hr />
<p class="line874">&nbsp;</p>
<p class="line874">脚本 b2d 将二进制数 (比如 1101) 转换为相应的十进制数。这也是一个用expr命令进行数学运算的例子: </p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-207d191769de27203cfe00538f94e294591bbd59_018\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-207d191769de27203cfe00538f94e294591bbd59_018', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-207d191769de27203cfe00538f94e294591bbd59_018" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span><span class="Comment"># vim: set sw=4 ts=4 et:</span></span><br /><span class="line"><span class="LineNumber">  3 </span><span class="ID">help</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  5 </span>  <span class="ID">cat</span> <span class="Operator">&lt;</span> <span class="ID">b2h</span> <span class="Operator">-</span><span class="Operator">-</span> <span class="ID">convert</span> <span class="ID">binary</span> <span class="ID">to</span> <span class="ID">decimal</span></span><br /><span class="line"><span class="LineNumber">  6 </span></span><br /><span class="line"><span class="LineNumber">  7 </span><span class="ID">USAGE</span><span class="Operator">:</span> <span class="ID">b2h</span> <span class="Operator">[</span><span class="Operator">-</span><span class="ID">h</span><span class="Operator">]</span> <span class="ID">binarynum</span></span><br /><span class="line"><span class="LineNumber">  8 </span></span><br /><span class="line"><span class="LineNumber">  9 </span><span class="ID">OPTIONS</span><span class="Operator">:</span> <span class="Operator">-</span><span class="ID">h</span> <span class="ID">help</span> <span class="ID">text</span></span><br /><span class="line"><span class="LineNumber">  10 </span></span><br /><span class="line"><span class="LineNumber">  11 </span><span class="ID">EXAMPLE</span><span class="Operator">:</span> <span class="ID">b2h</span> <span class="Number">111010</span></span><br /><span class="line"><span class="LineNumber">  12 </span><span class="ID">will</span> <span class="ResWord">return</span> <span class="Number">58</span></span><br /><span class="line"><span class="LineNumber">  13 </span><span class="ID">HELP</span></span><br /><span class="line"><span class="LineNumber">  14 </span>  <span class="ID">exit</span> <span class="Number">0</span></span><br /><span class="line"><span class="LineNumber">  15 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  16 </span></span><br /><span class="line"><span class="LineNumber">  17 </span><span class="ID">error</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  18 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  19 </span>  <span class="Comment"># print an error and exit</span></span><br /><span class="line"><span class="LineNumber">  20 </span>  <span class="ID">echo</span> <span class="String">&quot;$1&quot;</span></span><br /><span class="line"><span class="LineNumber">  21 </span>  <span class="ID">exit</span> <span class="Number">1</span></span><br /><span class="line"><span class="LineNumber">  22 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  23 </span></span><br /><span class="line"><span class="LineNumber">  24 </span><span class="ID">lastchar</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  25 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  26 </span>  <span class="Comment"># return the last character of a string in $rval</span></span><br /><span class="line"><span class="LineNumber">  27 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">z</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  28 </span>      <span class="Comment"># empty string</span></span><br /><span class="line"><span class="LineNumber">  29 </span>      <span class="ID">rval</span><span class="Operator">=</span><span class="String">&quot;&quot;</span></span><br /><span class="line"><span class="LineNumber">  30 </span>      <span class="ResWord">return</span></span><br /><span class="line"><span class="LineNumber">  31 </span>  <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  32 </span>  <span class="Comment"># wc puts some space behind the output this is why we need sed:</span></span><br /><span class="line"><span class="LineNumber">  33 </span>  <span class="ID">numofchar</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">echo</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">|</span> <span class="ID">wc</span> <span class="Operator">-</span><span class="ID">c</span> <span class="Operator">|</span> <span class="ID">sed</span> <span class="String">'s/ //g'</span> <span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  34 </span>  <span class="Comment"># now cut out the last char</span></span><br /><span class="line"><span class="LineNumber">  35 </span>  <span class="ID">rval</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">echo</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">|</span> <span class="ID">cut</span> <span class="Operator">-</span><span class="ID">b</span><span class="Error"> </span><span class="Error">$</span><span class="ID">numofchar</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  36 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  37 </span></span><br /><span class="line"><span class="LineNumber">  38 </span><span class="ID">chop</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  39 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  40 </span>  <span class="Comment"># remove the last character in string and return it in $rval</span></span><br /><span class="line"><span class="LineNumber">  41 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">z</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  42 </span>      <span class="Comment"># empty string</span></span><br /><span class="line"><span class="LineNumber">  43 </span>      <span class="ID">rval</span><span class="Operator">=</span><span class="String">&quot;&quot;</span></span><br /><span class="line"><span class="LineNumber">  44 </span>      <span class="ResWord">return</span></span><br /><span class="line"><span class="LineNumber">  45 </span>  <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  46 </span>  <span class="Comment"># wc puts some space behind the output this is why we need sed:</span></span><br /><span class="line"><span class="LineNumber">  47 </span>  <span class="ID">numofchar</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">echo</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">|</span> <span class="ID">wc</span> <span class="Operator">-</span><span class="ID">c</span> <span class="Operator">|</span> <span class="ID">sed</span> <span class="String">'s/ //g'</span> <span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  48 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="String">&quot;$numofchar&quot;</span> <span class="Operator">=</span> <span class="String">&quot;1&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  49 </span>      <span class="Comment"># only one char in string</span></span><br /><span class="line"><span class="LineNumber">  50 </span>      <span class="ID">rval</span><span class="Operator">=</span><span class="String">&quot;&quot;</span></span><br /><span class="line"><span class="LineNumber">  51 </span>      <span class="ResWord">return</span></span><br /><span class="line"><span class="LineNumber">  52 </span>  <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  53 </span>  <span class="ID">numofcharminus1</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">expr</span><span class="Error"> </span><span class="Error">$</span><span class="ID">numofchar</span> <span class="String">&quot;-&quot;</span> <span class="Number">1</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  54 </span>  <span class="Comment"># now cut all but the last char:</span></span><br /><span class="line"><span class="LineNumber">  55 </span>  <span class="ID">rval</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">echo</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">|</span> <span class="ID">cut</span> <span class="Operator">-</span><span class="ID">b</span> <span class="Number">0</span><span class="Operator">-</span><span class="Error">$</span><span class="Operator">{</span><span class="ID">numofcharminus1</span><span class="Operator">}</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  56 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  57 </span></span><br /><span class="line"><span class="LineNumber">  58 </span><span class="ResWord">while</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  59 </span><span class="ID">case</span><span class="Error"> </span><span class="Error">$</span><span class="Number">1</span> <span class="ResWord">in</span></span><br /><span class="line"><span class="LineNumber">  60 </span>  <span class="Operator">-</span><span class="ID">h</span><span class="Operator">)</span> <span class="ID">help</span><span class="Operator">;</span><span class="ID">shift</span> <span class="Number">1</span><span class="Operator">;</span><span class="Operator">;</span> <span class="Comment"># function help is called</span></span><br /><span class="line"><span class="LineNumber">  61 </span>  <span class="Operator">-</span><span class="Operator">-</span><span class="Operator">)</span> <span class="ID">shift</span><span class="Operator">;</span><span class="ResWord">break</span><span class="Operator">;</span><span class="Operator">;</span> <span class="Comment"># end of options</span></span><br /><span class="line"><span class="LineNumber">  62 </span>  <span class="Operator">-</span><span class="Operator">*</span><span class="Operator">)</span> <span class="ID">error</span> <span class="String">&quot;error: no such option $1. -h for help&quot;</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  63 </span>  <span class="Operator">*</span><span class="Operator">)</span> <span class="ResWord">break</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  64 </span><span class="ID">esac</span></span><br /><span class="line"><span class="LineNumber">  65 </span><span class="ID">done</span></span><br /><span class="line"><span class="LineNumber">  66 </span></span><br /><span class="line"><span class="LineNumber">  67 </span><span class="Comment"># The main program</span></span><br /><span class="line"><span class="LineNumber">  68 </span><span class="ID">sum</span><span class="Operator">=</span><span class="Number">0</span></span><br /><span class="line"><span class="LineNumber">  69 </span><span class="ID">weight</span><span class="Operator">=</span><span class="Number">1</span></span><br /><span class="line"><span class="LineNumber">  70 </span><span class="Comment"># one arg must be given:</span></span><br /><span class="line"><span class="LineNumber">  71 </span><span class="Operator">[</span> <span class="Operator">-</span><span class="ID">z</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span> <span class="Operator">&amp;</span><span class="Operator">&amp;</span> <span class="ID">help</span></span><br /><span class="line"><span class="LineNumber">  72 </span><span class="ID">binnum</span><span class="Operator">=</span><span class="String">&quot;$1&quot;</span></span><br /><span class="line"><span class="LineNumber">  73 </span><span class="ID">binnumorig</span><span class="Operator">=</span><span class="String">&quot;$1&quot;</span></span><br /><span class="line"><span class="LineNumber">  74 </span></span><br /><span class="line"><span class="LineNumber">  75 </span><span class="ResWord">while</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$binnum&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  76 </span>  <span class="ID">lastchar</span> <span class="String">&quot;$binnum&quot;</span></span><br /><span class="line"><span class="LineNumber">  77 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="String">&quot;$rval&quot;</span> <span class="Operator">=</span> <span class="String">&quot;1&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  78 </span>      <span class="ID">sum</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">expr</span> <span class="String">&quot;$weight&quot;</span> <span class="String">&quot;+&quot;</span> <span class="String">&quot;$sum&quot;</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  79 </span>  <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  80 </span>  <span class="Comment"># remove the last position in $binnum</span></span><br /><span class="line"><span class="LineNumber">  81 </span>  <span class="ID">chop</span> <span class="String">&quot;$binnum&quot;</span></span><br /><span class="line"><span class="LineNumber">  82 </span>  <span class="ID">binnum</span><span class="Operator">=</span><span class="String">&quot;$rval&quot;</span></span><br /><span class="line"><span class="LineNumber">  83 </span>  <span class="ID">weight</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">expr</span> <span class="String">&quot;$weight&quot;</span> <span class="String">&quot;*&quot;</span> <span class="Number">2</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  84 </span><span class="ID">done</span></span><br /><span class="line"><span class="LineNumber">  85 </span></span><br /><span class="line"><span class="LineNumber">  86 </span><span class="ID">echo</span> <span class="String">&quot;binary $binnumorig is decimal $sum&quot;</span></span><br /><span class="line"><span class="LineNumber">  87 </span><span class="Comment">#</span><br /><strong>ERROR: EOF in multi-line statement</strong><br /></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">该脚本使用的算法是利用十进制和二进制数权值 (1,2,4,8,16,..),比如二进制&quot;10&quot;可以这样转换成十进制: </p>
<pre>0 * 1 + 1 * 2 = 2<br /></pre>
<p>&nbsp;</p>
<p class="line874">为了得到单个的二进制数我们是用了lastchar 函数。该函数使用wc &ndash;c计算字符个数,然后使用cut命令取出末尾一个字符。Chop函数的功能则是移除最后一个字符。 </p>
<p class="line867">&nbsp;</p>
<h3 id="head-a0b677c50b996a252d3426753e6a04263b39f518">7.3. 文件循环拷贝</h3>
<p>&nbsp;</p>
<p class="line874">你 可能有这样的需求并一直都这么做:将所有发出邮件保存到一个文件中。但是过了几个月之后,这个文件可能会变得很大以至于该文件的访问速度变慢;下面的脚本 rotatefile 可以解决这个问题。这个脚本可以重命名邮件保存文件(假设为outmail)为outmail.1,而原来的outmail.1就变成了 outmail.2 等等... </p>
<p class="line867">&nbsp;</p>
<div lang="en" dir="ltr" class="codearea"><script type="text/javascript">
document.write('<a href="#" onclick="return togglenumber(\'CA-20be6ed29fcf5783fddc7f33ca5a1734626f729f_019\', 1, 1);" \
                class="codenumbers">Toggle line numbers<\/a>');
</script><a class="codenumbers" onclick="return togglenumber('CA-20be6ed29fcf5783fddc7f33ca5a1734626f729f_019', 1, 1);" href="http://127.0.0.1:8000/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80#">Toggle line numbers</a>
<pre lang="en" id="CA-20be6ed29fcf5783fddc7f33ca5a1734626f729f_019" dir="ltr"><span class="line"><span class="LineNumber">  1 </span><span class="Comment">#!/bin/sh</span></span><br /><span class="line"><span class="LineNumber">  2 </span><span class="Comment"># vim: set sw=4 ts=4 et:</span></span><br /><span class="line"><span class="LineNumber">  3 </span></span><br /><span class="line"><span class="LineNumber">  4 </span><span class="ID">ver</span><span class="Operator">=</span><span class="String">&quot;0.1&quot;</span></span><br /><span class="line"><span class="LineNumber">  5 </span><span class="ID">help</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  6 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  7 </span>  <span class="ID">cat</span> <span class="Operator">&lt;</span> <span class="ID">rotatefile</span> <span class="Operator">-</span><span class="Operator">-</span> <span class="ID">rotate</span> <span class="ID">the</span> <span class="ID">file</span> <span class="ID">name</span></span><br /><span class="line"><span class="LineNumber">  8 </span>  <span class="ID">USAGE</span><span class="Operator">:</span> <span class="ID">rotatefile</span> <span class="Operator">[</span><span class="Operator">-</span><span class="ID">h</span><span class="Operator">]</span> <span class="ID">filename</span></span><br /><span class="line"><span class="LineNumber">  9 </span>  <span class="ID">OPTIONS</span><span class="Operator">:</span> <span class="Operator">-</span><span class="ID">h</span> <span class="ID">help</span> <span class="ID">text</span></span><br /><span class="line"><span class="LineNumber">  10 </span>  <span class="ID">EXAMPLE</span><span class="Operator">:</span> <span class="ID">rotatefile</span> <span class="ID">out</span></span><br /><span class="line"><span class="LineNumber">  11 </span></span><br /><span class="line"><span class="LineNumber">  12 </span>  <span class="ID">This</span> <span class="ID">will</span> <span class="ID">e</span><span class="Operator">.</span><span class="ID">g</span> <span class="ID">rename</span> <span class="ID">out</span><span class="Number">.2</span> <span class="ID">to</span> <span class="ID">out</span><span class="Number">.3</span><span class="Operator">,</span> <span class="ID">out</span><span class="Number">.1</span> <span class="ID">to</span> <span class="ID">out</span><span class="Number">.2</span><span class="Operator">,</span> <span class="ID">out</span> <span class="ID">to</span> <span class="ID">out</span><span class="Number">.1</span><span class="Operator">[</span><span class="ID">BR</span><span class="Operator">]</span></span><br /><span class="line"><span class="LineNumber">  13 </span>  <span class="ResWord">and</span> <span class="ID">create</span> <span class="ID">an</span> <span class="ID">empty</span> <span class="ID">out</span><span class="Operator">-</span><span class="ID">file</span></span><br /><span class="line"><span class="LineNumber">  14 </span></span><br /><span class="line"><span class="LineNumber">  15 </span>  <span class="ID">The</span> <span class="ID">max</span> <span class="ID">number</span> <span class="ResWord">is</span> <span class="Number">10</span></span><br /><span class="line"><span class="LineNumber">  16 </span></span><br /><span class="line"><span class="LineNumber">  17 </span>  <span class="ID">version</span><span class="Error"> </span><span class="Error">$</span><span class="ID">ver</span></span><br /><span class="line"><span class="LineNumber">  18 </span>  <span class="ID">HELP</span></span><br /><span class="line"><span class="LineNumber">  19 </span></span><br /><span class="line"><span class="LineNumber">  20 </span>  <span class="ID">exit</span> <span class="Number">0</span></span><br /><span class="line"><span class="LineNumber">  21 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  22 </span></span><br /><span class="line"><span class="LineNumber">  23 </span><span class="ID">error</span><span class="Operator">(</span><span class="Operator">)</span></span><br /><span class="line"><span class="LineNumber">  24 </span><span class="Operator">{</span></span><br /><span class="line"><span class="LineNumber">  25 </span>  <span class="ID">echo</span> <span class="String">&quot;$1&quot;</span></span><br /><span class="line"><span class="LineNumber">  26 </span>  <span class="ID">exit</span> <span class="Number">1</span></span><br /><span class="line"><span class="LineNumber">  27 </span><span class="Operator">}</span></span><br /><span class="line"><span class="LineNumber">  28 </span></span><br /><span class="line"><span class="LineNumber">  29 </span><span class="ResWord">while</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">n</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  30 </span>  <span class="ID">case</span><span class="Error"> </span><span class="Error">$</span><span class="Number">1</span> <span class="ResWord">in</span></span><br /><span class="line"><span class="LineNumber">  31 </span>      <span class="Operator">-</span><span class="ID">h</span><span class="Operator">)</span> <span class="ID">help</span><span class="Operator">;</span><span class="ID">shift</span> <span class="Number">1</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  32 </span>      <span class="Operator">-</span><span class="Operator">-</span><span class="Operator">)</span> <span class="ResWord">break</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  33 </span>      <span class="Operator">-</span><span class="Operator">*</span><span class="Operator">)</span> <span class="ID">echo</span> <span class="String">&quot;error: no such option $1. -h for help&quot;</span><span class="Operator">;</span><span class="ID">exit</span> <span class="Number">1</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  34 </span>      <span class="Operator">*</span><span class="Operator">)</span> <span class="ResWord">break</span><span class="Operator">;</span><span class="Operator">;</span></span><br /><span class="line"><span class="LineNumber">  35 </span>  <span class="ID">esac</span></span><br /><span class="line"><span class="LineNumber">  36 </span><span class="ID">done</span></span><br /><span class="line"><span class="LineNumber">  37 </span></span><br /><span class="line"><span class="LineNumber">  38 </span><span class="Comment"># input check:</span></span><br /><span class="line"><span class="LineNumber">  39 </span><span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">z</span> <span class="String">&quot;$1&quot;</span> <span class="Operator">]</span> <span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  40 </span>  <span class="ID">error</span> <span class="String">&quot;ERROR: you must specify a file, use -h for help&quot;</span></span><br /><span class="line"><span class="LineNumber">  41 </span><span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  42 </span></span><br /><span class="line"><span class="LineNumber">  43 </span><span class="ID">filen</span><span class="Operator">=</span><span class="String">&quot;$1&quot;</span></span><br /><span class="line"><span class="LineNumber">  44 </span><span class="Comment"># rename any .1 , .2 etc file:</span></span><br /><span class="line"><span class="LineNumber">  45 </span><span class="ResWord">for</span> <span class="ID">n</span> <span class="ResWord">in</span> <span class="Number">9</span> <span class="Number">8</span> <span class="Number">7</span> <span class="Number">6</span> <span class="Number">5</span> <span class="Number">4</span> <span class="Number">3</span> <span class="Number">2</span> <span class="Number">1</span><span class="Operator">;</span> <span class="ID">do</span></span><br /><span class="line"><span class="LineNumber">  46 </span>  <span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">f</span> <span class="String">&quot;$filen.$n&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  47 </span>      <span class="ID">p</span><span class="Operator">=</span><span class="Operator">`</span><span class="ID">expr</span><span class="Error"> </span><span class="Error">$</span><span class="ID">n</span> <span class="Operator">+</span> <span class="Number">1</span><span class="Operator">`</span></span><br /><span class="line"><span class="LineNumber">  48 </span>      <span class="ID">echo</span> <span class="String">&quot;mv $filen.$n $filen.$p&quot;</span></span><br /><span class="line"><span class="LineNumber">  49 </span>      <span class="ID">mv</span><span class="Error"> </span><span class="Error">$</span><span class="ID">filen</span><span class="Operator">.</span><span class="Error">$</span><span class="ID">n</span><span class="Error"> </span><span class="Error">$</span><span class="ID">filen</span><span class="Operator">.</span><span class="Error">$</span><span class="ID">p</span></span><br /><span class="line"><span class="LineNumber">  50 </span>  <span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  51 </span><span class="ID">done</span></span><br /><span class="line"><span class="LineNumber">  52 </span></span><br /><span class="line"><span class="LineNumber">  53 </span><span class="Comment"># rename the original file:</span></span><br /><span class="line"><span class="LineNumber">  54 </span><span class="ResWord">if</span> <span class="Operator">[</span> <span class="Operator">-</span><span class="ID">f</span> <span class="String">&quot;$filen&quot;</span> <span class="Operator">]</span><span class="Operator">;</span> <span class="ID">then</span></span><br /><span class="line"><span class="LineNumber">  55 </span>  <span class="ID">echo</span> <span class="String">&quot;mv $filen $filen.1&quot;</span></span><br /><span class="line"><span class="LineNumber">  56 </span>  <span class="ID">mv</span><span class="Error"> </span><span class="Error">$</span><span class="ID">filen</span><span class="Error"> </span><span class="Error">$</span><span class="ID">filen</span><span class="Number">.1</span></span><br /><span class="line"><span class="LineNumber">  57 </span><span class="ID">fi</span></span><br /><span class="line"><span class="LineNumber">  58 </span></span><br /><span class="line"><span class="LineNumber">  59 </span><span class="ID">echo</span> <span class="ID">touch</span><span class="Error"> </span><span class="Error">$</span><span class="ID">filen</span></span><br /><span class="line"><span class="LineNumber">  60 </span><span class="ID">touch</span><span class="Error"> </span><span class="Error">$</span><span class="ID">filen</span><br /><strong>ERROR: EOF in multi-line statement</strong><br /></span></pre>
</div>
<p>&nbsp;</p>
<p class="line874">这 个脚本是如何工作的呢?在检测到用户提供了一个文件名之后,首先进行一个9到1的循环;文件名.9重命名为文件名.10,文件名.8重命名为文件名. 9&hellip;&hellip;等等。循环结束之后,把原始文件命名为文件名.1,同时创建一个和原始文件同名的空文件(touch $filen)。 </p>
<p class="line867">&nbsp;</p>
<h2 id="head-3678df5da4466e97a699b4294a835a8095b088fc">8. 脚本调试</h2>
<p>&nbsp;</p>
<p class="line874">最简单的调试方法当然是使用echo命令。你可以在任何怀疑出错的地方用echo打印变量值,这也是大部分shell程序员花费80%的时间用于调试的原因。Shell脚本的好处在于无需重新编译,而插入一个echo命令也不需要多少时间。 </p>
<p class="line874">shell也有一个真正的调试模式,如果脚本&quot;strangescript&quot;出错,可以使用如下命令进行调试: </p>
<pre>sh -x strangescript<br /></pre>
<p>&nbsp;</p>
<p class="line874">上述命令会执行该脚本,同时显示所有变量的值。 </p>
<p class="line874">shell还有一个不执行脚本只检查语法的模式,命令如下: </p>
<pre>sh -n your_script<br /></pre>
<p>&nbsp;</p>
<p class="line874">这个命令会返回所有语法错误。 </p>
<p class="line862">我们希望你现在已经可以开始编写自己的shell脚本了,尽情享受这份乐趣吧! <img width="15" height="15" title=":)" src="http://127.0.0.1:8000/wiki/ubuntu-cn/img/smile.png" alt=":)" /> </p>
<hr />
<p class="line874"><a href="http://127.0.0.1:8000/%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E7%89%88%E6%9C%AC%E7%B1%BB">支持所有版本类</a> </p>
<p lang="zh" dir="ltr" class="info" id="pageinfo">Shell编程基础  (2007-03-16 07:17:53由<span title="??? @ localhost[127.0.0.1]">localhost</span>编辑)</p>

2016年6月14日 (二) 16:49的最新版本

原作者 Leal;请参阅页面底部的编者列表。

授权许可:

注意:本文仍然在持续的修订之中,且错漏之处可能较多。如果能够阅读英语的话,可以考虑试试较为完善的 Wooledge BashGuide。这个站点除了教程之外,还有一些类似“bash 百科”的内容。Bash 官方手册也是你的好朋友。

从第一行开始

我们可以使用任意一种文字编辑器,比如gedit、kedit、emacs、vi等来编写shell脚本,它必须以如下行开始(必须放在文件的第一行):

<source lang=bash>#!/bin/bash</source>

此行称为 shebang(就是 sharp (#) + bang (!) 的意思),会指引操作系统使用接下来指定的程序运行此文件。此处 /bin/bash 执行我们的文件。

一些人使用 #!/bin/sh 来让 sh 执行文件,按照习惯这表示任何支持 POSIX shell 命令语言sh程序。为了用上我们所喜欢的 bash 拓展语法功能,我们就不这么用了。如果你使用别的脚本,例如 /bin/tcsh,照着样子加个 #! 就行。

编辑结束并保存后,如果直接要执行该脚本,必须先使其具有可执行属性:

<source lang=bash>chmod +x filename</source>

此后在该脚本所在目录下,输入 ./filename 即可执行该脚本。

变量

Shell 变量默认全都是字符串。

变量赋值和引用

Shell 编程中,使用变量无需事先声明。变量名的命名遵守正则表达式 [a-zA-Z_][a-zA-Z0-9_]+,也就是由大小写字母数字和下划线组成,且不能以数字开头。请注意 shell 环境中的确有以数字和特殊符号开头的变量名,但是那些东西不可以用接下来的方式赋值。

需要给变量赋值时,可以这么写:

<source lang=bash>varname=值 [var2=val2 ....]</source>

请注意这边等号左右不能有空格。 要取用一个变量的值,只需在变量名前面加一个 $

<source lang=bash># assign a="hello world" # 等号两边均不能有空格存在

  1. print

printf '%s\n' "A is: $a"</source>

挑个自己喜欢的编辑器,输入上述内容,并保存为文件 first,然后执行 chmod +x first 使其可执行,最后输入 ./first 执行该脚本。其输出结果如下:

<source lang="bash"> A is: hello world </source>

有时候变量名可能会和其它文字(匹配最长的符合变量名或特殊变量名要求的内容)混淆,比如:

<source lang=bash>num=2 echo "this is the $numnd" # 输出 this is the — shell 尝试寻找 $numnd 的值 echo "this is the ${num}nd" # 输出 this is the 2nd — 修好了!

  1. 花括号可以隔开变量名,但是放歪了的话…

echo "this is the {$num}nd" # 输出 this is the {2}nd — 切是切开了,但是…</source>

变量算术

Shell 变量默认都是字符串。这也就是说,你尝试这么做,肯定没用:

<source lang=bash>var=1 var=$var+1 echo $var # 输出 1+1</source>

我们可以用很多方法达成我们的目标。首先是好孩子的方法——C 风格表达式。

<source lang=bash>var=0

  1. bash 里面可以用 (( )) 执行 C 风格的算术表达式。
  2. 如果你接下来还会读 if 那一段的话,你还会知道这玩意的返回和 C 的非零真假判断一致。

(( var += 1 )) # 这是一种,现在 var 是 1 (( var++ )) # 这也是一种自增,2 (( var = var * var )) # 怎么来乘法了!var 现在是 4。 let 'var = var / 3' # 还是只有 bash 才能用的拓展。除法是整数除法,向 0 舍入,1。

  1. 来一点不一定要 bash 的方法吧,毕竟 sh 还有很多种,总不能全报错了吧。
  2. $(( )) 会展开成为这个 C 表达式求值的结果。以前 bash 有个 $[ ] 一样,但是别去用。

echo $((var += 2)) # echo 出 3,var 现在是 3。 var=$((var-1)) # 展开成 var=2,var 现在是……还用说吗,2。</source>

以前还有人用 expr 之类的外部程序来,不过这属于杀鸡用牛刀。并且调用外部程序浪费时间性能差。

<source lang=bash>var=1 var=$(expr "$var" + 1) # expr 收到三个参数 '1' '+' '1',

                     # 按照 expr --help 里面写的方法运行
                     # 然后输出替换掉 $() 这里变成 var=2。

var=`expr "$var" + 1` # 前面一行的老写法,千万千万不要学。</source>

Shell里的流程控制

if 语句

if 表达式如果条件命令组为真,则执行 then 后的部分。标准形式:

<source lang=bash>if

 判断命令,可以有很多个,真假取最后的返回值

then

 如果前述为真做什么

[ # 方括号代表可选,别真打进去了! elif

 可以再来个判断,如果签名为假继续尝试这里

then

 如果前述为真做什么 ]

else

 如果全都不行做什么

fi # 结束,就是倒写的 if 啦。</source>

现实生活中一般判断只有一个命令,所以你看到的一般是:

<source lang=bash>if ....; then # 你也可以写成 if 之后换行,这样就不用分号了。

 ....

fi</source>

大多数情况下,可以使用测试命令来对条件进行测试,比如可以比较字符串、判断文件是否存在及是否可读等等……在 bash 中一般采用更好用的 ... 语法进行条件测试,而通用方法是 [ ... ](相当于 test ...)。两者都接纳的常用测试语句有:

-f "filename"
判断是否是一个文件
-x "/bin/ls"
判断/bin/ls是否存在并有可执行权限
-n "$var"
判断 $var 变量是否有值
"$a" == "$b"
判断$a和$b是否相等

前者可以使用 help [[ 查询用法,后者使用 help [ (bash) 或 man test 查询。下面的语句用到了这个内容:

<source lang=bash>if [ "${SHELL}" == "/bin/bash" ]; then

 echo "your login shell is the bash (bourne again shell)"

else

 echo "your login shell is not bash but ${SHELL}"

fi</source>

变量 $SHELL 包含有登录shell的名称,我们拿它和 /bin/bash 进行比较以判断当前使用的shell是否为bash。你可能会问了,要是 bash 路径不是这个呢?

&& 和 || 操作符

熟悉C语言的朋友可能会喜欢下面的表达式:

<source lang=bash>[ -f "/etc/shadow" ] && echo "This computer uses shadow passwords"</source>

这里的 && 就是一个快捷操作符,如果左边的表达式为真(返回 0——“成功”)则执行右边的语句,你也可以把它看作逻辑运算里的与操作。上述脚本表示如果/etc/shadow文件存在,则打印“This computer uses shadow passwords”。

同样shell编程中还可以用或操作 (||),例如:

<source lang=bash>#!/bin/bash

mailfolder=/var/spool/mail/james [ -r "$mailfolder" ] || { echo "Can not read $mailfolder"; exit 1; } echo "$mailfolder has mail from:" grep "^From " $mailfolder</source>

该脚本首先判断mailfolder是否可读,如果可读则打印该文件中以"From"开头的行。如果不可读则或操作生效,打印错误信息后脚本退出。需要注意的是,这里我们必须使用如下两个命令:

<source lang=bash>{

 echo "Can not read $mailfolder"; # 打印错误信息
 exit 1; # 退出程序

}</source>

我们使用花括号以组合命令的形式将两个命令放到一起作为一个命令使用。即使不用与和或操作符,我们也可以用if表达式完成任何事情,但是使用与或操作符会更便利很多。

要注意 Shell 中的 && || 程序流操作符不表现任何优先级区别,完全是先看到谁就先处理谁的关系。

case 语句

case表达式可以用来匹配一个给定的字符串,而不是数字(可别和C语言里的switch...case混淆)。

<source lang="bash"> case ... in

  ...) do something here 
  ;;

esac </source> file命令可以辨别出一个给定文件的文件类型,如:file lf.gz,其输出结果为:

<source lang="bash"> lf.gz: gzip compressed data, deflated, original filename, last modified: Mon Aug 27 23:09:18 2001, os: Unix </source>

我们利用这点写了一个名为smartzip的脚本,该脚本可以自动解压bzip2, gzip和zip 类型的压缩文件:

<source lang="bash">

  1. !/bin/bash

ftype="$(file "$1")" case "$ftype" in "$1: Zip archive"*)

  unzip "$1" ;;

"$1: gzip compressed"*)

  gunzip "$1" ;;

"$1: bzip2 compressed"*)

  bunzip2 "$1" ;;
  • )
  echo "File $1 can not be uncompressed with smartzip";;

esac </source>

你可能注意到上面使用了一个特殊变量 $1,该变量包含有传递给该脚本的第一个参数值。也就是说,当我们运行:

<source lang="bash"> smartzip articles.zip </source>

$1 就是字符串 articles.zip。

select 循环语句

select 循环语句是bash的一种扩展应用,擅长于交互式场合。

用户可以从一组不同的值中进行选择:

<source lang="bash"> pocket=() select var in 跳跳糖 糖 很多糖 企鹅糖; do

 echo "除了 $var 还要什么吗?"
 if ((RANDOM%4 == 0)); then
   echo "呀!时间不够了,快上车!"
   break # break 还是那个 break
 fi
 pocket+=("$var")

done echo "你最后说的那个 $var 弄丢了……" IFS='、' echo "现在口袋里只有:${pocket[*]}。" IFS=$' \t\n' </source>

下面是一个简单的示例:

<source lang="bash">

  1. !/bin/bash

echo "What is your favourite OS?" select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do

 break;

done echo "You have selected $var" </source>

该脚本的运行结果如下:

<source lang="bash"> What is your favourite OS? 1) Linux 2) Gnu Hurd 3) Free BSD 4) Other

  1. ? 1

You have selected Linux </source>

while/for 循环

在shell中,可以使用如下循环:

<source lang="bash"> while ...; do

  ....

done </source>

只要测试表达式条件为真,则while循环将一直运行。关键字"break"用来跳出循环,而关键字”continue”则可以跳过一个循环的余下部分,直接跳到下一次循环中。

for循环会查看一个字符串列表(字符串用空格分隔),并将其赋给一个变量:

<source lang="bash"> for var in ....; do

  ....

done </source>

下面的示例会把A B C分别打印到屏幕上:

<source lang="bash">

  1. !/bin/bash

for var in A B C ; do

  echo "var is $var"

done </source>

下面是一个实用的脚本showrpm,其功能是打印一些RPM包的统计信息:

<source lang="bash">

  1. !/bin/bash
  1. list a content summary of a number of RPM packages
  2. USAGE: showrpm rpmfile1 rpmfile2 ...
  3. EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpm

for rpmpackage in "$@"; do

  if [ -r "$rpmpackage" ];then
     echo "=============== $rpmpackage =============="
     rpm -qi -p $rpmpackage
  else
     echo "ERROR: cannot read file $rpmpackage"
  fi

done </source>

这里出现了第二个特殊变量$@,该变量包含有输入的所有命令行参数值。如果你运行showrpm openssh.rpm w3m.rpm webgrep.rpm,那么 "$@"(有引号) 就包含有 3 个字符串,即openssh.rpm, w3m.rpm和 webgrep.rpm。$*的意思是差不多的。但是只有一个字串。如果不加引号,带空格的参数会被截断。

Shell里的一些特殊符号

引号

在向程序传递任何参数之前,程序会扩展通配符和变量。这里所谓的扩展是指程序会把通配符(比如*)替换成适当的文件名,把变量替换成变量值。我们可以使用引号来防止这种扩展,先来看一个例子,假设在当前目录下有两个jpg文件:mail.jpg和tux.jpg。

<source lang="bash">

  1. !/bin/bash

echo *.jpg # => mail.jpg tux.jpg </source>

引号(单引号和双引号)可以防止通配符*的扩展:

<source lang="bash">

  1. !/bin/bash

echo "*.jpg" # => *.jpg echo '*.jpg' # => *.jpg </source>

其中单引号更严格一些,它可以防止任何变量扩展;而双引号可以防止通配符扩展但允许变量扩展:

<source lang="bash">

  1. !/bin/bash

echo $SHELL # => /bin/bash echo "$SHELL" # => /bin/bash echo '$SHELL' # => $SHELL </source>

此外还有一种防止这种扩展的方法,即使用转义字符——反斜杠\

<source lang="bash"> echo \*.jpg # => *.jpg echo \$SHELL # => $SHELL </source>

Here Document

当要将几行文字传递给一个命令时,用here document是一种不错的方法。对每个脚本写一段帮助性的文字是很有用的,此时如果使用here document就不必用echo函数一行行输出。Here document以 << 开头,后面接上一个字符串,这个字符串还必须出现在here document的末尾。下面是一个例子,在该例子中,我们对多个文件进行重命名,并且使用here document打印帮助:

<source lang="bash">

  1. !/bin/bash
  1. we have less than 3 arguments. Print the help text:

if [ $# -lt 3 ] ;; then cat << HELP

ren -- renames a number of files using sed regular expressions USAGE: ren 'regexp' 'replacement' files...

EXAMPLE: rename all *.HTM files in *.html:

  ren 'HTM$' 'html' *.HTM

HELP #这里HELP要顶格写,前面不能有空格或者TAB制表符。如果cat一行写成cat << -HELP,前边可以带TAB.

  exit 0

fi OLD="$1" NEW="$2"

  1. The shift command removes one argument from the list of
  2. command line arguments.

shift shift

  1. $@ contains now all the files:

for file in "$@"; do

  if [ -f "$file" ] ; then
     newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`
     if [ -f "$newfile" ]; then

     echo "ERROR: $newfile exists already"

     else
        echo "renaming $file to $newfile ..."
        mv "$file" "$newfile"
     fi
  fi

done </source> 示例有点复杂,我们需要多花点时间来说明一番。第一个if表达式判断输入命令行参数是否小于3个 (特殊变量$# 表示包含参数的个数) 。如果输入参数小于3个,则将帮助文字传递给cat命令,然后由cat命令将其打印在屏幕上。打印帮助文字后程序退出。如果输入参数等于或大于3个,我们就将第一个参数赋值给变量OLD,第二个参数赋值给变量NEW。下一步,我们使用shift命令将第一个和第二个参数从参数列表中删除,这样原来的第三个参数就成为参数列表$*的第一个参数。然后我们开始循环,命令行参数列表被一个接一个地被赋值给变量$file。接着我们判断该文件是否存在,如果存在则通过sed命令搜索和替换来产生新的文件名。然后将反短斜线内命令结果赋值给newfile。这样我们就达到了目的:得到了旧文件名和新文件名。然后使用 mv命令进行重命名

Shell里的函数

如果你写过比较复杂的脚本,就会发现可能在几个地方使用了相同的代码,这时如果用上函数,会方便很多。函数的大致样子如下:

<source lang="bash">

  1. 别笑,bash 里面函数名的确可以这样……
  2. (POSIX sh 函数名倒是和变量名要求差不多)

我是一个函数() {

 # 函数里面 $1 $2 对应函数所接受到的第一、第二……个参数。
 这里有很多命令

} </source>

函数没有必要声明。只要在执行之前出现定义就行

下面是一个名为xtitlebar的脚本,它可以改变终端窗口的名称。这里使用了一个名为help的函数,该函数在脚本中使用了两次:

<source lang=bash>#!/bin/bash

help() { cat << HELP xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole USAGE: xtitlebar [-h] "string_for_titelbar" OPTIONS: -h help text EXAMPLE: xtitlebar "cvs" HELP exit 0 }

  1. in case of error or if -h is given we call the function help:

if | $1 == '-h' ; then

 help

fi

  1. send the escape sequence to change the xterm titelbar:

echo -e "\033]0;$1\007"

  1. </source>

在脚本中提供帮助是一种很好的编程习惯,可以方便其他用户(和自己)使用和理解脚本。

命令行参数

我们已经见过 $*$1, $2 ... $9 等特殊变量,这些特殊变量包含了用户从命令行输入的参数。迄今为止,我们仅仅了解了一些简单的命令行语法(比如一些强制性的参数和查看帮助的-h选项)。但是在编写更复杂的程序时,您可能会发现您需要更多的自定义的选项。通常的惯例是在所有可选的参数之前加一个减号,后面再加上参数值 (比如文件名)。

有好多方法可以实现对输入参数的分析,但是下面的使用case表达式的例子无疑是一个不错的方法。

<source lang="bash">

  1. !/bin/bash

help() {

  cat << HELP
  This is a generic command line parser demo.
  USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2

HELP

  exit 0

}

while [ -n "$1" ]; do case "$1" in

  -h) help;shift 1;; # function help is called
  -f) opt_f=1;shift 1;; # variable opt_f is set
  -l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2
  --) shift;break;; # end of options
  -*) echo "error: no such option $1. -h for help";exit 1;;
  *) break;;

esac done

echo "opt_f is $opt_f" echo "opt_l is $opt_l" echo "first arg is $1" echo "2nd arg is $2"

</source>

你可以这样运行该脚本:

<source lang="bash"> cmdparser -l hello -f -- -somefile1 somefile2 </source>

返回结果如下:

<source lang="bash"> opt_f is 1 opt_l is hello first arg is -somefile1 2nd arg is somefile2 </source>

这个脚本是如何工作的呢?脚本首先在所有输入命令行参数中进行循环,将输入参数与case表达式进行比较,如果匹配则设置一个变量并且移除该参数。根据unix系统的惯例,首先输入的应该是包含减号的参数。

Shell脚本示例

一般编程步骤

现在我们来讨论编写一个脚本的一般步骤。任何优秀的脚本都应该具有帮助和输入参数。写一个框架脚本(framework.sh),该脚本包含了大多数脚本需要的框架结构,是一个非常不错的主意。这样一来,当我们开始编写新脚本时,可以先执行如下命令:

<source lang="bash"> cp framework.sh myscript </source>

然后再插入自己的函数。

让我们来看看如下两个示例。

二进制到十进制的转换

脚本 b2d 将二进制数 (比如 1101) 转换为相应的十进制数。这也是一个用expr命令进行数学运算的例子:

<source lang="bash">

  1. !/bin/bash
  2. vim: set sw=4 ts=4 et:

help() {

  cat << HELP
  

b2d -- convert binary to decimal

USAGE: b2d [-h] binarynum

OPTIONS: -h help text

EXAMPLE: b2d 111010 will return 58 HELP

  exit 0

}

error() {

  # print an error and exit
  echo "$1"
  exit 1

}

lastchar() {

  # return the last character of a string in $rval
  if [ -z "$1" ]; then
     # empty string
     rval=""
     return
  fi
  # wc puts some space behind the output this is why we need sed:
  numofchar=`echo -n "$1" | sed 's/ //g' | wc -c ` 
  #sed 's/ //g'  所有空白去掉  sed 's/ /\t/g' 所有空白用t代替
  # now cut out the last char  抓取第numofchar个字节
  rval=`echo -n "$1" | cut -b $numofchar`

}

chop() {

  # remove the last character in string and return it in $rval
  if [ -z "$1" ]; then
     # empty string
     rval=""
     return
  fi
  # wc puts some space behind the output this is why we need sed:
  numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
  if [ "$numofchar" = "1" ]; then
     # only one char in string
     rval=""
     return
  fi
  numofcharminus1=`expr $numofchar "-" 1`
  # now cut all but the last char:
  rval=`echo -n "$1" | cut -b -$numofcharminus1` 
  #原来的 rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`运行时出错.
  #原因是cut从1开始计数,应该是cut -b 1-${numofcharminus1}

}

while [ -n "$1" ]; do case $1 in

  -h) help;shift 1;; # function help is called
  --) shift;break;; # end of options
  -*) error "error: no such option $1. -h for help";;
  *) break;;

esac done

  1. The main program

sum=0 weight=1

  1. one arg must be given:

[ -z "$1" ] && help binnum="$1" binnumorig="$1"

while [ -n "$binnum" ]; do

  lastchar "$binnum"
  if [ "$rval" = "1" ]; then
     sum=`expr "$weight" "+" "$sum"` 
     # $expr 10 + 10    20 expr提示是计算操作
  fi
  # remove the last position in $binnum
  chop "$binnum"
  binnum="$rval"
  weight=`expr "$weight" "*" 2`

done

echo "binary $binnumorig is decimal $sum"

</source>

该脚本使用的算法是利用十进制和二进制数权值 (1,2,4,8,16,..),比如二进制"10"可以这样转换成十进制:

<source lang="bash"> 0 * 1 + 1 * 2 = 2 </source>

为了得到单个的二进制数我们是用了lastchar 函数。该函数使用wc –c计算字符个数,然后使用cut命令取出末尾一个字符。Chop函数的功能则是移除最后一个字符。

但是还记得前面怎么说的吗?进制转换哪需要这么麻烦:

<source lang="bash">

  1. !/bin/bash

while read -p 'input a binary...' num; do

 if [[ $num == *[!01]* ]]; then
   echo "含有 0 1 之外的字符"
 fi
 echo "$((0x$num))"      # 在 num 头上糊一个 0x 然后跑数学计算——就完事了!
 printf "%d\n" "0x$num"    # printf 也可以凑热闹啊

done </source>

如果你喜欢自己算的话,其实也可以从左到右来(反正数学计算不要有事没事玩 expr 啦):

<source lang="bash">#!/bin/bash

  1. 人人皆知的 Horner 规则

value=0 echo "写一堆 1 0 完了回车" while read -n 1 char; do

 case $char in
   (0|1) ;;      # 好
   ()  break;; # 没了
   (*)   echo "你说啥?"; break;;
 esac
 ((value *= 2))
 ((value += char))

done echo "$value"</source>

文件循环移动

你可能有这样的需求并一直都这么做:将所有发出邮件保存到一个文件中。但是过了几个月之后,这个文件可能会变得很大以至于该文件的访问速度变慢;下面的脚本 rotatefile 可以解决这个问题。这个脚本可以重命名邮件保存文件(假设为outmail)为outmail.1,而原来的outmail.1就变成了 outmail.2 等等...

<source lang="bash">

  1. !/bin/bash
  2. vim: set sw=4 ts=4 et:

ver="0.1" help() {

  cat << HELP
  rotatefile -- rotate the file name
  USAGE: rotatefile [-h] filename
  OPTIONS: -h help text
  EXAMPLE: rotatefile out

  This will e.g rename out.2 to out.3, out.1 to out.2, out to out.1
  and create an empty out-file

  version $ver

HELP

  exit 0

}

if | $1 == ; then

 help

fi

filename=$1

  1. 我们先找到最大的数字再说。

max=0 while [ -f "$filename.$((++max))" ]; do

 : # 什么都不用做,我们已经顺手用 ++max 自增了 max 了。

done

  1. 然后从最大的一路重命名下来。

for ((i=max; i>0; i--)); do

 # 数字加个 1,好给前一个让位子。
 mv "$filename.$i" "$filename.$((i+1))"

done

  1. 最后我们点名要重命名的:

if [ -f "$filename" ]; then

  mv "$filename" "$filename.1"

fi

  1. 重新创建一下。
> "$filename"

</source>。

脚本调试

最简单的调试方法当然是使用echo命令。你可以在任何怀疑出错的地方用echo打印变量值,这也是大部分shell程序员花费80%的时间用于调试的原因。Shell脚本的好处在于无需重新编译,而插入一个echo命令也不需要多少时间。

shell也有一个真正的调试模式,如果脚本"strangescript"出错,可以使用如下命令进行调试:

<source lang="bash"> sh -x strangescript </source>

上述命令会执行该脚本,同时显示所有变量的值。

shell还有一个不执行脚本只检查语法的模式,命令如下:

<source lang="bash"> sh -n your_script </source>

这个命令会返回所有语法错误。

我们希望你现在已经可以开始编写自己的shell脚本了,尽情享受这份乐趣吧! :)