1. Expression of conditional judgment:
[ 表达式 ] 或者 [[ 表达式 ]] 或者 test 表达式,要注意的是[ ]或者[[ ]]中括号内要与表达式之间用空格隔开,否则会报错。
2.if Else FI conditional statement
格式: if 条件 ;then 如果条件为真则执行这里的语句 else 条件为假则执行这里语句(else可以省略) fi
3. The logical relationship between commands
逻辑与:符号 && 只有两个条件同时为真时,结果为真,如果第一个为真,就继续判断第二个条件,如果第一个条件为假,就结束判断,因为结果已经确定为假 逻辑或:符号 || 只要有一个为真,结果为真,如果判断第一个条件为真时,就不需要判断后面的条件了,因为结果已经出来了,为真,否则就继续判断
4. Conditional judgment between integers
-eq :用来判断两个整数之间是否相等,如果相等返回的状态为0(真) -ne :用来判断两个整数之间是否不等,如果不等返回的状态为真,否则为假 -gt :用来判断前一个数是否大于后一个数,如果大于返回真,否则为假,如:7 -gt 5 返回为真 -lt :用来判断前一个数是否小于后一个数,如果小于返回真,否则为假,如:5 -lt 7 返回为真 -ge :用来判断前一个数是否大于等于后一个数,如果大于等于返回真,否则为假,如:7 -gt 5或者7 -gt 7 返回为真 -le :用来判断前一个数是否小于等于后一个数,如果小于等于返回真,否则为假,如:5 -le 7或者5 -le 5 返回为真
5. Practice
判断一个用户,如果用户存在,则打印一条语句“user is exits。”,否则创建此用户,并答应一条语句“useradd success。”: #!/bin/bash username="zzyyoo" (id $username &> /dev/null && echo "user is exist.") || (useradd $username &>/dev/null && echo "useradd success.") ###/dev/null是一个类似黑洞的设备,把数据重定向到这里,都会被回收。 给定一个用户,如果uid为0,则打印“root user。”,否则打印“common user。”: #!/bin/bash#user=‘wwzzyy‘user=‘root‘if [ `id -u $user` -eq 0 ];then echo "root user."else echo "common user."fi
6. Variable naming rules
由数字,字母和下划线组成 不能以数字开头,如3ab 变量名最好不要和系统中已有的环境变量重名,避免覆盖
Shell Programming II Conditional judgment