shell复用代码片段

1、测试脚本是否被正确的数目参数调用

   1 E_WRONG_ARGS=65
   2 script_parameters="-a -h -m -z"
   3 #                  -a = all, -h = help, etc.
   4 
   5 if [ $# -ne $Number_of_expected_args ]
   6 then
   7   echo "Usage: `basename $0` $script_parameters"
   8   # `basename $0`是指脚本名称(译者:这个内容在后面章节会讲).
   9   exit $E_WRONG_ARGS
  10 fi

2、如果脚本包含了额外的#!行,bash将会把它当作一个注释.

   1 #!/bin/bash
   2 
   3 echo "Part 1 of script."
   4 a=1
   5 
   6 #!/bin/bash
   7 # 这样不会运行一个新的脚本.
   8 
   9 echo "Part 2 of script."
  10 echo $a  # Value of $a stays at 1.

利用上面所述的特性能找到一些有趣的窍门.

   1 #!/bin/rm
   2 # 删除自身的脚本.
   3 
   4 # 当你运行这个脚本时,除了这个脚本消失了之外,你不会发现更多其他的东西。
   5 
   6 WHATEVER=65
   7 
   8 echo "This line will never print (betcha!)."
   9 
  10 exit $WHATEVER  # 不要紧,脚本绝不会运行到这儿.

也可以写一个以#!/bin/more,开头的文件,并执行它。执行结果会发现这是一个自我显示的文件。

3、拷贝文件

   1 cat {file1,file2,file3} > combined_file
   2 # 连接file1,file2,和file3的内容并写到文件combined_file里去.
   3 
   4 
   5 cp file22.{txt,backup}
   6 # 拷贝"file22.txt"内容为"file22.backup"



 

posted @ 2013-11-11 17:23  为自由奋斗  阅读(643)  评论(0)    收藏  举报