CH11-Shell脚本编程(2).pdf
第11讲 Shell脚本编程(2)James HoSept.2012复习 变量 变量的定义与赋值 变量的引用 shell预定义的变量($1,$?,$#,.)关于引号 称为强引号,“”称为弱引号 1.引号的作用是限定字符串,特别是需要正常使用特殊字符(shell元字符)时 2.双引号中的某些特殊字符会被shell解释(例如$)3.单引号中的任何字符都不会被shell解释关于引号 示例 要点1:尽量使用“$var”的形式引用变量的值echo The value of$UID is$UID.echo The value of$UID is$UID.echo The value of$UID is$UID.echo The value of$UID is$UID.fred=There are 4 spaces here:aa.echo$fredecho$fred结构化shell 比较与条件 分支控制 循环控制if expressionthencommand listelif expressionthencommand listelsecommand listfi流程控制之if-elif-else-fi 语法:作用:表达式为true时,执行相应的command list.if expression;thencommand listelif expression;thencommand listelsecommand listfi条件与比较 表达式测试 方法1:test expression 方法2:expression 测试结果返回结果可以是true,或者false 测试用表达式 整数测试 文件测试 字符串测试条件与比较 整数测试表达式 测试结果正确返回true,否则返回false 要点:比较的对象是变量的值表达式表达式意义意义int1-ge int2大于等于(,great or equal)int1-gt int2大于(,great than)int1-le int2小于等于(,less or equal)int1-lt int2小于(,less than)条件与比较 字符串测试表达式:判断字符串的性质 提示:相等比较只使用一个等号!表达式表达式意义意义str字符串非空str1=str2两字符串相等/相同str1!=str2两字符串不相等-n str字符串的长度非0-z str字符串的长度为0条件与比较 文件测试表达式:测试文件属性 格式:-option file 测试结果正确返回true,否则返回false 提示1:如果文件不存在,也返回false 提示2:测试结果与用户权限相关选项选项意义意义选项选项意义意义-f普通文件(file)-r只读文件(read)-d目录文件(directory)-w可写文件(write)-L链接文件(link)-x可执行文件(execute)-s文件长度非0-b块文件(block)-e文件存在(exist)-t终端文件(terminal)条件和比较 测试表达式的组合表达式表达式意义意义!expressionexpression结果的非exp1-a exp2and,exp1和exp2都为真exp1 o exp2or,exp1或者exp2为真(expression)将测试表达式分组exp1&exp2exp1和exp2都为真exp1|exp2exp1或者exp2为真条件和比较 示例:name=$1word1=$2word2=$3if grep$word1$name&grep$word2$namethenecho$word1 and$word2 are both in$name.fi-x“$1”a!d“$1”流程控制之if-elif-else-fi 示例 if_demo1 if_demo2 if_demo3流程控制之if-elif-else-fi 示例:类似的ls-lif !-e$1;thenecho file$1 does not exist.exit 1fiif -d$1;thenecho-n$1 is a directory that you may if !-x$1;thenecho-n not fiecho“access.elif -f$1;thenecho$1 is a regular file.elseecho$1 is a special type of file.fiif -O$1;thenecho you own the file.elseecho you do not own the file.fiif -r$1;thenecho you have read permission on the file.fiif -w$1;thenecho you have write permission on the file.fiif -x$1-a!-d$1;thenecho you have execute permission on the file.fi分支控制之-case 语法:case test-string inpattern1)command-list1;pattern2)command-list2;esac 作用:将test-string和所有的pattern逐一比较,匹配则执行相应的command-list,直到比较介绍 要点:pattern符合shell命令行规范分支控制之-case 示例case_demo1case_demo2循环控制之for 语法:for var in arg-listdocommand listdone 作用:将arg-list中的值逐个赋个var,然后执行command list.特例:但变量列表为空时,使用命令行的所有参数(即等效于使用参数$)循环控制之for 示例for_ex1for_ex2for_ex3循环控制之while 语法:while expressiondocommand listdone 作用:只要expression为真,就重复执行command list.循环控制之until 语法:until expressiondocommand listdone 作用:只要expression为假,就重复执行command list.循环控制之break与continue 作用:配合循环控制(for,while,until),用于终止循环体的执行 break:终止循环,跳出循环体;continue:终止当前循环,开始下一循环;总结 测试.文件测试 字符串测试 整数测试 结构控制:if-then-elif-then-else-fi case-esac for do-done while/until-do-done shell命令也可以作为测试条件作业 15章:6,7,8,17,请在自己的机器上验证你的程序!