shell脚本编程学习.docx





《shell脚本编程学习.docx》由会员分享,可在线阅读,更多相关《shell脚本编程学习.docx(7页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、Shell脚本编程学习入门是本文要介绍的内容,我们可以使用任意一种文字编辑器,比如gedit、kedit、emacs、vi等来编写shell脚本,它必须以如下行开始(必须放在文件的第一行):#!/bin/sh.注意:最好使用“!/bin/bash”而不是“!/bin/sh”,如果使用tc shell改为tcsh,其他类似。符号#!用来告诉系统执行该sell脚本的程序,本例使用/bin/sh。编辑结束并保存后,如果要执行该shell脚本,必须先使其可执行:chmod +x filename此后在该shell脚本所在目录下,输入 ./filename 即可执行该shell脚本。Shell里的一些特
2、殊符号a shell离得函数如果你写过比较复杂的shell脚本,就会发现可能在几个地方使用了相同的代码,这时如果用上函数,会方便很多。函数的大致样子如下:functionname()# inside the body $1 is the first argument given to the function# $2 the second .body你需要在每个脚本的开始对函数进行声明。下面是一个名为xtitlebar的shell脚本,它可以改变终端窗口的名称。这里使用了一个名为help的函数,该函数在shell脚本中使用了两次:#!/bin/sh# vim: set sw=4 ts=4 et
3、:help()cat HELPxtitlebar - change the name of an xterm, gnome-terminal or kde konsoleUSAGE: xtitlebar -h string_for_titelbarOPTIONS: -h help textEXAMPLE: xtitlebar cvsHELPexit 0# in case of error or if -h is given we call the function help: -z $1 & help $1 = -h & help# send the escape sequence to ch
4、ange the xterm titelbar:echo -e 330;$107# 在shell脚本中提供帮助是一种很好的编程习惯,可以方便其他用户(和自己)使用和理解脚本。命令行参数我们已经见过$* 和 $1, $2 . $9 等特殊变量,这些特殊变量包含了用户从命令行输入的参数。迄今为止,我们仅仅了解了一些简单的命令行语法(比如一些强制性的参数和查看帮助的-h选项)。但是在编写更复杂的程序时,您可能会发现您需要更多的自定义的选项。通常的惯例是在所有可选的参数之前加一个减号,后面再加上参数值 (比如文件名)。有好多方法可以实现对输入参数的分析,但是下面的使用case表达式的例子无疑是一个不错
5、的方法。#!/bin/sh help() cat shift by 2 -) shift;break; # end of options -*) echo error: no such option $1. -h for help;exit 1; *) break;esacdone echo opt_f is $opt_fecho opt_l is $opt_lecho first arg is $1echo 2nd arg is $2你可以这样运行该脚本:cmdparser -l hello -f - -somefile1 somefile2返回结果如下:opt_f is 1opt_l is
6、 hellofirst arg is -somefile12nd arg is somefile2这个shell脚本是如何工作的呢?脚本首先在所有输入命令行参数中进行循环,将输入参数与case表达式进行比较,如果匹配则设置一个变量并且移除该参数。根据unix系统的惯例,首先输入的应该是包含减号的参数。shell脚本示例一般编程步骤现在我们来讨论编写一个脚本的一般步骤。任何优秀的脚本都应该具有帮助和输入参数。写一个框架脚本(framework.sh),该shell脚本包含了大多数脚本需要的框架结构,是一个非常不错的主意。这样一来,当我们开始编写新脚本时,可以先执行如下命令:cp framewor
7、k.sh myscript然后再插入自己的函数。让我们来看看如下两个示例。二进制到十进制的转换脚本 b2d 将二进制数 (比如 1101) 转换为相应的十进制数。这也是一个用expr命令进行数学运算的例子:#!/bin/sh# 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 111010will return 58HELP exit 0 error() # print an error
8、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 # now cut out the last char rval=echo -n $1 | cut -b $numofchar
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- shell 脚本 编程 学习

限制150内