一、语法
if [ condition ]; then # 当 condition 成立时,执行内容; fi # 将 if 反过来写,fi 结束 if 之意
if [ condition ]; then # 当 condition 成立时,执行内容; else # 当 condition 成立时,执行内容; fi
if [ condition1 ]; then # 当 condition1 成立时,执行内容; elif [ condition2 ]; then # 当 condition2 成立时,执行内容; else # 当 condition1 与 condition2 均不成立时,执行内容; fi
二、练习
- 通过端口号判断 ssh 是否正在运行
status=`netstat -tunap | egrep '<0.0.0.0:22>|<:::22>'` if [ "$status" != "" ]; then echo "SSH is running!" fi
user@ae01:~$ sudo sh ./test.sh SSH is running! user@ae01:~$
- 判断 user 的 home 目录是否存在
if [ -d /home/user ];then echo "/home/user is exists." else echo "/home/user is not exists." fi
user@ae01:~$ sh ./test.sh /home/user is exists. user@ae01:~$
- 判断当前系统日期是不是在国庆假期内
DATE=`date +%m%d` if [ $DATE -lt 1001 ]; then echo "National Day holiday hasn't arrived yet." elif [ $DATE -gt 1007 ]; then echo "National Day holiday is over." else echo "Happy Holiday!" fi
user@ae01:~$ sh ./test.sh National Day holiday is over. user@ae01:~$
三、相关判别式详细
| 运算符 | 描述 | 示例 |
| 字符串判断 | ||
| str1 | 当字符串非空时为真 | [ "$str1"] |
| str1 = str2 | 当两个字符串相同时为真 | [ "$str1" = "$str2"] |
| str1 != str2 | 当两个字符串不相等时为真 | [ "$str1" != "$str2"] |
| -n str1 | 当字符串的长度不为0时为真 | [ -n "$str1" ] |
| -z str1 | 当字符串的长度为0时为真 | [ -z "$str1" ] |
| 数字判段 | ||
| int1 -eq int2 | 当两数相等时为真 | [ "$int1" -eq "$int2"] |
| int1 -ne int2 | 当两数不相等时为真 | [ "$int1" -ne "$int2"] |
| int1 -gt int2 | int1 大于 int2 时为真 | [ "$int1" -gt "$int2"] |
| int1 -ge int2 | int1 大于等于 int2 时为真 | [ "$int1" -ge "$int2"] |
| int1 -lt int2 | int1 小于 int2 时为真 | [ "$int1" -lt "$int2"] |
| int1 -le int2 | int1 小于等于 int2 时为真 | [ "$int1" -le "$int2"] |
| 文件判段 | ||
| -e filename | filename 存在则为真 | [ -e "$filename" ] |
| -d filename | filename 为目录则为真 | [ -d "$filename" ] |
| -f filename | filename 为常规文件则为真 | [ -f "$filename" ] |
| -L filename | filename 为链接文件则为真 | [ -L "$filename" ] |
| -c filename | filename 为特殊字符文件则为真 | [ -c "$filename" ] |
| -b filename | filename 为块文件则为真 | [ -b "$filename" ] |
| -s filename | filename 大小不为0时则为真 | [ -s "$filename" ] |
| -r filename | filename 可读则为真 | [ -r "$filename" ] |
| -w filename | filename 可写则为真 | [ -w "$filename" ] |
| -x filename | filename 可执行则为真 | [ -x "$filename" ] |
| filename1 -nt filename2 | filename1 比 filename2新则为真 | [ "$filename1" -nt "$filename2" ] |
| filename2 -ot filename2 | filename1 比 filename2旧则为真 | [ "$filename1" -ot "$filename2" ] |
| 逻辑判断 | ||
| -a | 逻辑与 | [ 3 -gt 1 -a 1 -lt 3 ] |
| -o | 逻辑或 | [ 3 -gt 1 -o 1 -ge 3 ] |
| ! | 非真 | |