一、条件测试与比较 1、test 测试表达式 常用 test -f file && echo true||echo false 2、[ 测试表达式 ] 特别常用 [ -f file ]&& echo true||echo false 3、[[ 测试表达式 ]] 二、流程控制

1、流控制语句 if 实例1 #!/bin/bash #获取uid=0(root)中的0; id=id | awk -F '[=(]' '{print $2}' echo "your user id is:$id" if [ $id -eq 0 ] then echo "root" else echo "not root" fi 实例2:判断登录的用户 #!/bin/bash #$#是添加到shell 参数个数 if [ $# -eq 1 ] #或 [[ $#==1 ]] 或 (($#==1)) then if who|grep $1 >/dev/null then echo $1 is active. else echo $1 is not active. fi else echo "Usage: $0 <username>" exit 1 fi ~
执行后的结果 [root@localhost shell]# sh if-if.sh root root is active. [root@localhost shell]# sh if-if.sh zabbix zabbix is not active. [root@localhost shell]# sh if-if.sh Usage: if-if.sh <username> [root@localhost shell]# 实例3 if-elif..else-fi #!/bin/bash ##if-elif..else-fi read -p "how lod are you? " age #使用shell算数运算符(())进行条件测试 if ((age<0||age>120));then #[[ age < 0 || age > 120 ]] echo "out of range !" exit 1 fi if ((age>=0&&age<13));then echo "child!" elif ((age>=13&&age<20));then echo "callan!" elif ((age>=20&&age<30));then echo "P iii" elif ((age>=30&&age<40));then echo "P IV I" else echo "Sorry I asked." fi 实例4 #!/bin/bash ##if 语句可以嵌套使用 file=$1 [ $# -ne 1 ] && echo "Usage: $0 <filename>" && exit 1 #错误的写法 [ $# -ne 1 ] && echo "Usage: $0 <filename>" ; exit 1 这样";" 不管前面的判断是否正确都会执 行 if [ -d $file ] then echo "$file is a directory" elif [ -f $file ] then if [ -r $file -a -w $file -a -x $file ];then echo "you have (rwx) permissioon on $file." else echo "$file is file." fi else echo "$fles is neither a file nor a directory." fi 执行结果 [root@localhost shell]# vim if-elif-if-else.sh [root@localhost shell]# sh if-elif-if-else.sh liu you have (rwx) permissioon on liu. [root@localhost shell]# sh if-elif-if-else.sh liub liub is a directory [root@localhost shell]# touch qq [root@localhost shell]# sh if-elif-if-else.sh qq qq is file. [root@localhost shell]#