Day 7

1.shell中的流程控制 用if 判断文件、目录属性 [ -f file ]判断是否是普通文件,且存在 [ -d file ] 判断是否是目录,且存在 [ -e file ] 判断文件或目录是否存在 [ -r file ] 判断文件是否可读 [ -w file ] 判断文件是否可写 [ -x file ] 判断文件是否可执行 例:[ -f 1.txt ] 判断1.txt是否是一个普通文件 [ -d /tmp ] && rm -rf /tmp 等同于 if [ -d 1.txt ] then rm -rf /tmp fi

if 特殊用法 if [ -z "$a" ]:表示当变量a的值为空时 if [ -n "$a" ]:表示当变量a的值不为空时 if [ ! -e file ]; then 表示文件不存在时会怎么样 [ ] 中不能使用<,>,==,!=,>=,<=这样的符号 例: #!/bin/bash n=wc -l /tmp/test.txt if [ -z $n ] then echo "error" exit elif [ $n -lt 20 ] then echo 1 else echo 0 fi

2.shell中的case判断 格式case 变量名 in value1) command ;; value2) command ;; value*) command ;; esac 在case程序中,可以在条件中使用|,表示或的意思 例:2|3) command ;;

case实例: [root@localhost root]# vim 1.sh #!/bin/bash read -p "Please input a number: " n if [ -z "$n" ] then echo "Please input a number." exit 1 #“exit 1”表示执行该部分命令后的返回值 #即,命令执行完后使用echo $?的值 fi

n1=echo $n|sed 's/[0-9]//g' #判断用户输入的字符是否为纯数字 #如果是数字,则将其替换为空,赋值给$n1 if [ -n "$n1" ] then echo "Please input a number." exit 1 #判断$n1不为空时(即$n不是纯数字)再次提示用户输入数字并退出 fi

#如果用户输入的是纯数字则执行以下命令: if [ $n -lt 60 ] && [ $n -ge 0 ] then tag=1 elif [ $n -ge 60 ] && [ $n -lt 80 ] then tag=2 elif [ $n -ge 80 ] && [ $n -lt 90 ] then tag=3 elif [ $n -ge 90 ] && [ $n -le 100 ] then tag=4 else tag=0 fi #tag的作用是为判断条件设定标签,方便后面引用 case $tag in 1) echo "not ok" ;; 2) echo "ok" ;; 3) echo "ook" ;; 4) echo "oook" ;; *) echo "The number range is 0-100." ;; esac

3.for循环 一般格式:

for var in item1 item2 ... itemN do command1 command2 ... commandN done 也可以写成一行,要用分号隔开:

for var in item1 item2 ... itemN; do command1; command2… done; 例: [root@localhost root]# touch 1.txt [root@localhost root]# touch 1\ 2.txt //这里的\是转义的意思,创建的是一个 1 2.txt文件 [root@localhost root]# ls 1 2.txt 1.txt [root@localhost root]# for i in ls ./ ; do echo $i ; done 1 2.txt 1.txt //可见for循环已经把1 2.txt 循环分割成了1 , 2.txt 注意:for默认情况下把空格或换行符(回车)作为分隔符