收藏 分享(赏)

第二章 Shell 脚本编程.ppt

上传人:fmgc7290 文档编号:6002134 上传时间:2019-03-23 格式:PPT 页数:129 大小:486.50KB
下载 相关 举报
第二章 Shell 脚本编程.ppt_第1页
第1页 / 共129页
第二章 Shell 脚本编程.ppt_第2页
第2页 / 共129页
第二章 Shell 脚本编程.ppt_第3页
第3页 / 共129页
第二章 Shell 脚本编程.ppt_第4页
第4页 / 共129页
第二章 Shell 脚本编程.ppt_第5页
第5页 / 共129页
点击查看更多>>
资源描述

1、第二章 Shell 脚本编程,本章参考教材,Unix技术大全系统管理员卷机械工业出版社 Linux与Unix Shell编程指南机械工业出版社 Advanced Bash Scripting Guide, by Mendel Cooper, 电子书籍 其他网上资源,基本概念,Unix/Linux系统中供用户使用的界面,为用户提供了输入命令和参数并可得到命令执行结果的环境。,Unix/Linux中的Shell,Bourne Shell或Posix Shell Korn Shell Bourne Again Shell Z Shell,C Shell TCShell,Windows中的Shell,

2、传统:DOS批处理文件(*.bat) WSH(Windows Script Host) VBScript(*.vbs) Jscript(*.js) C:windowssampleswsh,ASP(Active Server Pages) *.asp VBScript或Jscript脚本语言 在浏览器中运行脚本,基本概念,Shell的特点 命令行解释 使用保留字 使用Shell元字符(通配符) 可处理程序命令 使用输入输出重定向和管道 维护变量 进行Shell环境控制 支持Shell编程,常见Shell命令,文件安全与权限 后台执行命令 Shell输入与输出 文本过滤grep家族 正则表达式 登

3、陆环境,文件安全与权限,-rw-r-r- 1 wlzhang unknown 14 Jan 16 2003 pg.txt -rw-r-r- 1 wlzhang unknown 20 Jan 10 2002 test.txt 文件权限位 文件硬链接数目 文件属主 属主所在的默认组 文件长度 文件更新时间 文件名,文件安全与权限,文件权限位 -rw-r-r 文件属主权限 同组用户权限 其他用户权限 文件类型: d, l, s, b, c, p, -,文件安全与权限,改变权限位符号模式 chmod u+x file1 u, g, o, a +, -, = x, r, w, s, t, l 例子 ch

4、mod u+x o-w myfile,文件安全与权限,改变权限位绝对模式 chmod R 664 /usr/local/home/*,文件安全与权限,目录的权限 r: 可以列出该目录中的文件 w: 可在该目录中创建或删除文件 x: 可搜索或进入该目录 例如:同组用户对某一目录的权限位为-x, 可否执行该目录下设置执行位的脚本?,文件安全与权限,目录的权限 目录的权限覆盖该目录中文件的权限 drwx r- r- dir1 该目录下文件f1权限为 -rwxrwxrwx f1 则同组用户无法编辑该文件或访问该目录(Bourne Shell),文件安全与权限,suid/guid 设置suid/guid

5、 chmod 4755 f2 第一个为4:设置suid2: 设置guid6: 同时设置suid和guid,文件安全与权限,chown和chgrp:改变文件的属主和属组 chown一般形式 chown -R -h owner file 例子: chown pauline project chgrp admin project 注:改变文件的所有权时,相应的suid、guid被清除,文件安全与权限,查看umask值:umask命令,文件安全与权限,软链接和硬链接 ln -s sourcefile destfile 可以用ln命令为文件建立其他的名字,find和xargs,find pathname

6、 options -print -exec -ok find . maxdepth 1 name “t*” print find -name “A-Z*” print -name -perm -type: b, d, c, p, l, f -user -group -mtime n +n -follow -newer file1 ! newer file2 -size +nc nc nc,find和xargs,find . -name “leap“ -prune -o -name “t*“ print find . name “a-za-z0-90-9.txt” print find . pe

7、rm 755 print find /etc user uucp print find / -mtime 5 print find /var/adm mtime +3 print find . -newer chp7_10.sh ! -newer hello.sh -print touch t 09170000 idlefind . newer idle -print,find和xargs,find /etc type d print find . size +10 print find / -name “CON.FILE” depth print find . type f exec ls

8、l ; find . type f name “cw*” ok ls l ; find . name “*.log” mtime +5 ok rm ;,find和xargs,find命令中-exec选项,容易导致: 参数列太长 进程过多,性能下降 find命令与xargs命令结合 分批处理find命令传出的参数 xargs命令只有一个进程,find和xargs,find / name “core” print | xargs /tmp/core.log find /apps/audit perm 0777 | xargs chmod go-w find / -type f print | xa

9、rgs grep “device” find . name * -type f print | xargs grep “DBO”,后台执行命令,设置crontab文件,用它来提交作业(cron) 用at命令提交作业(at) 在后台提交作业(&) 用nohup命令提交作业(nohup),后台执行命令cron和crontab,cron:系统调度进程,自动调度用户的作业 crontab:允许用户提交、编辑或删除相应的作业 用户能否拥有crontab文件,通过 cron.deny cron.allow来管理,后台执行命令cron和crontab,crontab文件六个域 分:159 时:023 日:1

10、31 月:112 星期:06 要运行的命令 域之间用空格分割,每个域可有-、,、*,后台执行命令cron和crontab,crontab文件例子: 30 21 * * * /apps/bin/cleanup.sh 45 4 1,10,22 * * /apps/bin/backup.sh 10 1 * * 6,0 /bin/find name “core” exec rm ; 0,30 18-23 * * * /aaps/bin/dbcheck.sh 注:运行的命令或脚本绝对路径的形式,并在脚本中设置相应的环境变量,crontab命令,crontab -u user e l r 用编辑器创建文件

11、cwcron,每1小时提醒时间(如何写?) crontab cwcron将此作业提交给cron进程 crontab l / crontab e / crontab r 进行备份,at命令,向cron守护进程提交作业,稍后运行 为提交的作业保留当前环境变量,包括路径,作业的输出发送电子邮件(或重定向) at -f script -m l r time date 命令行方式或者at命令提示符,at命令,$ at 21:30 at find / -name “passwd” print at 系统返回Job ID:job 1 从邮件中获得结果信息,at命令,接受的日期/时间格式: H、HH.MM、H

12、H:MM、H:M、am、pm at 6.45am May 12 at 11.10pm at now + 1 hour at 9am tomorrow at 15:00 May 24 at now + 10 minutes,at命令,atq命令或at l命令 $ at l 2 2003-09-02 23:00 a 3 2003-09-22 13:20 a 4 2003-09-03 09:00 a 1 2003-09-03 12:00 a atq c, atq n,at命令,清除作业 先执行at l命令,获得作业标识 再使用at r清除该作业,&命令,将费时的作业放至后台运行,系统返回进程号 完成

13、时,按任一键出现完成提示 将输出重定向 查看进程ps,nohup命令,使后台进程在用户退出登录时继续运行 作业的输入输出重定向到nohup.out中 nohup command & 可通过提交脚本一次提交多个命令,Shell输入与输出,标准输入 标准输出 标准错误输出 输入输出的重定向,Shell输入与输出,echo命令 显示文本或变量 echo hello world echo “hello world” echo hello world var=“hello world”echo $varecho “$var”echo $var,echo “007” echo e “007” echo $

14、007 转义n, r, t, v, b, a0xx(八进制)echo5_2.shecho “$variable01“ echo “ echo “Hello“, he said.“,Shell输入与输出,转义 variable= echo “$variable“ variable=23skidoo echo “$variable“,variable=echo “$variable“ variable=echo “$variable“ 的转义作用 ,Shell输入与输出,echo命令 echo “something ” myfile echo “something ” myfile echo “

15、now is date”,Shell输入与输出,read命令 从键盘或文件的某一行文本中读入,并赋予一个变量 read nameHello how are you read name surnameJohn Doe read name surnameJohn Lemon Doe,参看例子脚本 test.sh,Shell输入与输出,cat命令 显示文件内容、创建文件、显示控制字符 cat myfile cat v myfile (-v显示控制字符,M),用cat命令创建新文件 cat myfile,Shell输入与输出,管道命令(|):把一个命令的输出传递给另一个命令作为输入ls | grep

16、myfile who | awk print $1 “t” $2 df k | awk print $1 | grep v “Filesystem” df k | awk print $1 | grep v “Filesystem” | sed s/C:cygwin/g,Shell输入与输出,tee命令 将输出的副本送到标准输出,另一个副本拷贝到相应文件中 tee a files(-a:追加到文件中) ls l | tee ls.out echo “something” | tee /dev/console,Shell输入与输出,标准输入、输出和错误 标准输入:文件描述符0,默认键盘 标准输出

17、:文件描述符1,默认屏幕 标准错误:文件描述符2,默认屏幕 输入输出的重定向,Shell输入与输出,command filename command filename command 1filename command 1filename command 2filename command 2filename command &filename = command filename 2&1 ( != 2&1 filename),2&1 i &j &j 0 filename (见file1.sh) &:文件描述符的复制,j复制到i,Shell输入与输出,cat myfile /dev/null

18、grep “sky” absentfile 2grep.err cat existfile absentfile 1rec.out 2rec.err cleanup cleanup.out 2&1(将标准输出和标准错误重定向到文件中),文本过滤正则表达式,元字符:正则表达式中描述模式匹配操作的特殊字符 只匹配行首字符 $ 只匹配行尾字符 * 任意多个字符 匹配其中单个或字符的范围 对特殊元字符进行转义 . 单个字符,文本过滤正则表达式,patternn 匹配模式出现n次 patternn, 含义同上,但次数最少为n patternn,m 含义同上,但出现次数在n与m之间 ? 模式出现0次或1次

19、 * 模式出现任意多次 + 模式出现1次或更多次,文本过滤正则表达式,.xxx d sh$ $ $ . .2 *.pas t.*.sh$ t*.sh$,0123456789 0-9 a-zA-Z0-9- 0-9 abc 1 中都是单个字符匹配,文本过滤正则表达式,重复表示符号前面的模式重复出现的次数 *、+、? 23*4 对于1548 Kerry 534 正则表达式1.*4 匹配整行,而不是154,文本过滤正则表达式,(a-z)(a-z)21 :匹配anna,qwwq等 A2B:匹配AAB A4,B: A2,4B: :匹配单词结束 B:不在单词开始或结束,文本过滤正则表达式,正则表达式的连接

20、正则表达式的“或”操作(|) 执行优先次序 重复*,+,? 连接 或:| 可用括号改变顺序,文本过滤常用正则表达式,l the gr(a|e)y (To:|From:) (Seaman|Ramsay ) 0-92-0-92-0-94 a-za-z* .0-90-9,文本过滤grep命令,grep option regexp files grep “hello” * grep c “hello” hello.sh (显示出现次数) grep l “hello” * (显示匹配文件名) grep n “hello” hello.sh (显示匹配的行及行号) grep v “hello” hello

21、.sh (显示不匹配的行) grep i “hello” hello.sh (大小写不敏感) grep s “hello” hello.sh (屏蔽出错信息),文本过滤grep命令,grep、正则表达式,与系统命令 grep test grep l2, test ls l | grep d ls l | grep dxxx ps ax | grep “named” ps ax | grep “named” | grep v “grep”,文本过滤egrep命令,egrep:expression or extended grep -f 选项使用文件作为匹配参数 cat hello.parahel

22、loworld egrep f hello.para hello.sh,文本过滤egrep命令,who | egrep (user1|user2|user3) who | egrep v (user1|user2) egrep (yellow|red) flower(s)? *,文本过滤awk命令,awk -F field-separator commands input-file(s) 在文本文件或字符串中按一定规则浏览和抽取信息 命令、程序、语言 用awk语言编写脚本 awk f awk-script-file input-file(s),文本过滤awk命令,awk BEGIN BEGIN

23、语句 处理数据END 完成处理filename,文本过滤awk命令,例子:grade.txt M.Tansley 05/99 48311 Green 8 40 44 J.Lulu 06/99 48317 green 9 24 26 P.Bunny 02/99 48 Yellow 12 35 28 J.Troll 07/99 4842 Brown-3 12 26 26 L.Tansley 05/99 4712 Brown-2 12 30 28,文本过滤awk命令,awk print $0 grade.txt awk print $1,$4 grade.txt awk BEGIN print “N

24、amen-”print $1END print “end-of-report”grade.txt,文本过滤awk命令,awk if($4/Brown/) print $0 grade.txt awk $0 /Brown/ grade.txt awk if($3/48/) print $0 grade.txt awk $3=“48” print $0 grade.txt awk $0 ! /Brown/ grade.txt awk if($6 $7 print $1 “ Try better at the next comp” grade.txt,文本过滤awk命令,awk /Ggreen/ g

25、rade.txt awk /.a/ grade.txtawk $1 /.a/ grade.txt awk /(Yellow|Brown)/ grade.txt,文本过滤awk命令,awk内置变量 ARGC 命令行参数个数 ARGV 命令行参数 ENVIRON 系统环境变量 FILENAME 浏览的文件名 FNR 浏览文件的记录数 FS 域分隔符 NF 浏览记录的域个数 NR 已读的记录数 OFS 输出域分隔符 ORS 输出记录分隔符 RS 记录分隔符,文本过滤awk命令,awk print NF,NR,$0 END print FILENAME grade.txt awk ENDprint N

26、R grade.txt awk if (NR0 & $4 /Brown/)print $0 grade.txt echo pwd | awk F/ print $NF,文本过滤awk命令,awk name=$1;belts=$4;if (belts/Yellow/) print name “ is belt ” belts grade.txt awk if ($1 = “M.Tansley”) $6=$6-1;print $1,$6,$7 grade.txt awk if($1 = “J.Troll”) ($1=“J.L.Troll”);print $1 grade.txt awk BEGIN

27、print “NametDifference”if($6 $7) $8=$7-$6;print $1,$8 grade.txt awk tot+=$6ENDprint “Students total points:” tot grade.txt,文本过滤awk命令,ls -l | grep .sh$| awk print $9 “tt“ $5; tot+=$5ENDprint “total KB:“tot awk gsub(/4842/,/4899/) print $0 grade.txt awk $1=“J.Troll” print length($1) “ “ $1 grade.txt a

28、wk BEGINprint match(“ANCD”,/C/),文本过滤awk命令,awk BEGINprint split(123#456#78,myarray,”#”) awk $1 = “L.Tansley” print substr($1,1,5) grade.txt echo “Stand-by” | awk print length($0),文本过滤awk命令,echo “65” | awk printf “%cn”, $0 awk printf “%-15s%sn”,$1,$3 grade.txt awk脚本及其执行(见age.awk),文本过滤awk命令,awk数组 for (

29、subscript in array) print arraysubscript,sed用法,非交互式文本流编辑器。读取一遍数据至缓冲区,不与初始文件打交道。 sed options sed-command input-file sed options f sed-script-file input-file sed-script-file options input-file ( out-file),sed用法,sed选项: -n:不打印 -f: 执行脚本 -h:帮助信息 -v:版本信息 -e:使用sed命令编辑,sed中定位文本 行号 正则表达式,sed用法,例子文件:quote.txt

30、sed 2p quote.txt sed n 2p quote.txt sed n 1,3p quote.txt sed -n /e/p quote.txtsed -n /The/p quote.txtsed -n 4,/The/p quote.txt,sed用法,sed -n /$/p quote.txtsed -n 1,$p quote.txt sed n /.*ing/p quote.txt sed -e /music/= quote.txt sed -n /music/= quote.txt sed -n -e /music/= -e /music/p quote.txt,sed用法,

31、附加文本: a addressa text text . text 插入文本 i 修改文本行 c,可接受地址范围,sed -e /company/ a Then suddenly it happend. It is really a disaster. quote.txtsed脚本(见append.sed, insert.sed, update.sed, mix.sed),sed用法,删除文本 sed 1d quote.txtsed 1,3d quote.txt sed $d quote.txt sed /Neave/d quote.txt,sed用法,替换文本 address,address

32、 s/pattern-to-find/replace-pattern/ g, p, w, n sed s/night/NIGHT/ quote.txt sed s/$/ quote.txt sed -n s/$/p quote.txt sed s/The/Wow!/g quote.txt sed -n s/The/Wow!/gp quote.txtsed s/The/Wow!/gw sed.out quote.txt,sed用法,sed -n s/nurse/“Hello“ &/p quote.txt sed 1,2 w file2 quote.txt sed /Neave/w file3 q

33、uote.txt 读文本sed /company/ r sedex.txt quote.txtsed /.a.*/q quote.txt sed -n 1,$l func.txt,sed用法,常用例子:echo “Mr Willis“ | sed s/Mr/& Bruce/g echo “account.doc“ | sed s/./g echo “accounts“ | sed s/$/.doc/gx=“Department+payrollBuilding G“echo $xecho $x | sed s/+/ of /g | sed s/ Located at /g,tr命令,用于字符转换

34、或抽取控制字符 echo “hellooo, World” | tr s “a-zA-Z” echo “hellooo world” | tr s “a-z” “A-Z” tr s “015” “n” input_filetr s “r” “n” input_file tr s “015032” “012*” input_file echo 0000 | tr “0*4” “*”,Shell脚本,#!/bin/bash #name: cleanup #This is a general cleanup script echo “Starting cleanup .wait.” rm /usr/

35、local/apps/log/*.log tail 40 /var/adm/messages /tmp/messages rm /var/adm/messages mv /tmp/messages /var/adm/messages echo “finished cleanup”,Shell脚本,#!/bin/sh #!/bin/bash #!/usr/bin/perl #!/usr/bin/tcl #!/bin/sed f #!/usr/awk -f,登录方式下的shell启动,bash的激活模式,交互式标准输入输出连到终端上 login:读初始化文件 非login:/.bashrc 受限:

36、禁止一些操作(改变目录、修改$SHELL和$PATH变量、运行exec、运行包含/的命令,及使用重定向等) 非交互式用来运行shell脚本 if -n $BASH_ENV ;then “BASH_ENV”; fi,bash的激活模式选项,-c string -i -r-restricted -login -posix -noprofile,-norc -rcfile file -verbose -help -version,控制bash的行为,set 可在命令行、初始化文件、脚本中使用 set a (set allexport) set +a .,shopt命令 shopt s cdable_

37、vars shopt u cdable_vars二者都有很多可设置的选项,参看man bash,初始化文件,/etc/profile $HOME/.Bash_profile $HOME/.Bashrc$HOME/.Bash_login$HOME/.profile 设置文件创建的umask和$PATH$TERM、$MANPATH、$PS1、$PS2,Shell环境变量,$PATH, $MANPATH, $LD_LIBRARY_PATH, $CD_PATH $EDITOR, $VISIUAL $MAIL, $MAILCHECK $HISTSIZE, $HISTFILE $TERM, $PAGER

38、.,alias,别名:交互式shell中缩短长命令的方法 alias rm=“rm i” alias chomd=“chmod” unlias rm rm,关于变量,内部变量 built-in:(vs. shell command) 见internalvars.txt 例子(void.sh, seconds.sh, specialvar.sh),关于变量,declare变量的声明 declare -r var1 declare -i number (见delcare.sh) declare -a indices declare -f functions declare -x var3 (见de

39、clare_x.sh) 对数字类型的操作:expr, let(见let.sh, expr.sh) y=expr $y + 1 , let y=y+1 , y=$($y+1)三者等价 $RANDOM:返回随机数 (.):进行数学运算(见arith.sh),数组,一维数组 area11=23 area13=37 area51=UFOs,或 declare a area$area11见(array.sh),Shell本地变量,在本次Shell生命期里使用的变量 变量的赋值,参见variable.sh 清除变量:unset 显示变量:set 测试变量 echo “The sky is $COLOR:-

40、grey today” echo $File:=my echo $File:+another,参数替换(parameter substitution),DEFAULT_FILENAME=generic.data filename=$1:-$DEFAULT_FILENAME # If not otherwise specified, the following command block operates #+ on the file “generic.data“. # # Commands follow.,参数替换(parameter substitution),$parameter?err_

41、msg $parameter:?err_msg (见checkvar.sh),参数替换(parameter substitution),$var#Pattern, $var#Pattern strip_leading_zero () val=$1#0 return $val 见param_subst.sh,关于变量string,string的长度 $#string expr length $string expr “$string“ : .* 见stringlen.sh, stringmatch.sh, stringindex.sh, stringextract.sh, stringremov

42、al.sh,stringreplace.sh,Shell本地变量,变量的导出export:将变量导出到子进程 (见father.sh和child.sh) local:局部变量,参数位置变量,$pg findfile #!/bin/bash #findfile find / -name $1 print $./findfile profile,参数位置变量,$pg who_is #!/bin/bash #who_is grep $1 passwd | awk F: print $4 $./who_is fangw 例子。 $#, $*,$的例子(见allparams.sh),脚本参数,$0$9

43、$#, $*, $ shift命令 getopts命令 见shift.sh, tr_case.sh,脚本参数,getopts用法: 设定标准选项,在脚本或函数参数中查看所有以-开头的参数(即选项串)是否匹配标准选项。如果匹配,将匹配的选项赋给变量 getopts 标准选项 变量 例如:getopts ahfvc VAR 见backup.sh,shell数字常量,默认10进制 8进制:032 16进制:0x32 2-64进制:base#number,退出/返回状态,$?:返回上一条语句或脚本执行的状态 0:成功 1255:不成功 exit命令 exit exit nnn,Shell编程,条件测试

44、 控制流结构(循环、分支等) shell函数 调试脚本,条件测试,test或:测试命令执行状态、文件状态、比较表达式 if cmp a b & /dev/null # Suppress output. then echo “Files a and b are identical.“ else echo “Files a and b differ.“ fi,条件测试,if grep -q Bash file then echo “File contains at least one occurrence of Bash.“ fi $ -w vartest.sh $test w vartest.s

45、h,条件测试,测试文件状态 -d:目录 -s:文件非空 -f:正规文件 -w:可写 -L:符号链接 -u:文件有suid位 -r:可读 -x:可执行 例子,条件测试,比较表达式 -eq = 字符串: -ne != -gt -n:非空串 -lt =,条件测试,逻辑操作 -a, & -o, | ! 例子gzip.sh,控制流结构,if.then.else.fi 见ifmkdir.sh if.then.elif.then.fi 见ifelif.sh,控制流结构,case “$variable“ in “$condition1“ ) command. ; “$condition2“ ) command

46、. ; *)command.;esac,参见case.sh, case2.shcaseparam.shcasevalid.sh,控制流结构,循环(while, for, until loops) for循环for arg in list do command(s). done (参见forlist.sh、forparams.sh、forcp.sh),控制流结构,for循环 for ( expr1; expr2; expr3) do command(s). done 见for_c.sh,控制流结构,while循环 while condition do command. done 参见while1

47、.sh、whileread.sh等,控制流结构,until循环 until condition-is-true do command. done 见until.sh,控制流结构,循环控制:break, continue break:推出循环或case语句(break-levels.sh) continue:跳过本次循环步,shell函数,function function_name command. return (exit_status) function_name () command. 参见functionfile.sh,functions.sh与direc_check.sh 在命令行执行函数,顺序先于同名命令,

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 网络科技 > 开发文档

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报