1)test命令测试文件、变量的属性,表达式的值,或命令执行返回值。test –d /usr à [ -d /usr ]test –f .bashrc à [ -f .bashrc ]test $count –gt 0 à [ $count –gt 0 ]2)if语句 if (expression) then command-list else command-listfi 3)case语句 case $var in pattern1) command-list ;; pattern2) command-list ;; … esac4)逻辑运算符 && 和 ||# test –f myfile.c && echo “file found”if test –f myfile.c then echo “file found”fi# test –f myfile.c | | echo “file not found”if test ! –f myfile.c then echo “file not found”fi
1.7 循环控制
1)for语句 for var in word-list do command-listdone for count in 1 2 3 do echo $I donefor var do 2)while语句 while (expression) do command-list done #greeting=’hello world’i = 1while test $i –le 100 ; do case $i in *0) echo “**********”>file$i ;; *) echo $i > file$i ;; esac i = ` expr $i + 1 `done例:append命令的实现:case $# in 1) cat >> $1 ;;2) cat < $1>> $2 ;;*) echo ‘usage: append [from] to ’;;esac#chmod +x myappend#myappend file1 file2
1.8函数
functionname( ) { command-list}usage(){ echo “usage:…..$1”}usage “from … to “注意:函数的使用就象可执行程序一样,但必须先定义,后使用。
1.9 here文档
here文档指在shell脚本中指定输入源,而不是来自文件或标准输入,其中的“<<”是here文档保留字。# mail cindy << !@$happy birthdayI love you!@$
1.10 shell内部命令:不产生子进程
1) eval:在shell程序中,利用变量的值来构建命令A=lsB= ‘ | wc -w’eval $A$B 2) exec:转去执行exec后命令,不建立新进程,也不返回到当前的执行过程,相当于go to 语句。#cat execdemoexec dateecho hello 3) read:从标准输入设备(键盘)读入一行,并把读入的字依次赋给各变量,所有剩余的字赋给最后一个变量。#cat parrot echo “you say:c” read what echo “I repeat:$what” 4) shift:使命令行参数向左移动一位,并使记录参数总数的变量$#减1 #cat shiftdemowhile test $# != 0do echo $1 $2 $3 shiftdone #shiftdemo a b ca b cb cc 5)wait:等待当前进程所有子进程结束,若wait后跟参数n,则等待进程n结束。 #cat waitdemoecho “This is a new file”(sleep 5; date)&wait echo “the file terminate”执行结果: This is a new file April 20 10:08:26 BJT 2002-04-20 The file terminate 6) trap:中断处理命令trap 命令表 中断信号表#cat trapfiletrap echo ‘ This is INT 2’ 2 trap echo ‘ This is INT 3’ 3 for I in /bin /bin/usrdo echo $Idone 下面程序实现scan:扫描当前目录下的每一个子目录,并执行用户提交的命令:d=`pwd`for i in *do if test –d $d/$i then cd $d/$i while echo “$i:” trap exit 2 read x do trap : 2 ; eval $x; done fi done7)点命令 . 在bsh利用 . 命令执行一个命令时,不创建子进程。(csh中用source)8)空命令:不做任何事情
1.11 shell程序实例
下面程序dircmp测试当前目录与指定目录是否含有相同文件数 if test $# -ne 1 then echo “Usage:dircmp dirname” exit 1 else if test !-d $1 then echo “”$1” is not a directory” exit 1 else this = `ls –l |grep ‘^-’ | wc –l ` that = `ls –l $1 |grep ‘^-’ | wc –l ` if test $this –ne $that then echo “Current directory and ”$1” do not match” elseecho “Current directory and ”$1” have same number of files” fififi#dircmp abc“abc” is not a directory