Shell脚本(二)
一、条件测试
测试/boot/是不是目录 如果是返回0 不是的话返回非0
[root@centos01 ~]# test -d /boot/
[root@centos01 ~]# echo $?
0
测试/boot/是不是目录 如果是返回Yes
[root@centos01 ~]# test -d /boot/ && echo "Yes"
Yes
二、比较运算符
10大于5 如果为真 显示yes
[root@centos01 ~]# [ 10 -gt 5 ] && echo "Yes"
Yes
10大于11 是错误的 所以不显示yes
[root@centos01 ~]# [ 10 -gt 11 ] && echo "Yes"
[root@centos01 ~]# echo $?
1
history显示历史代码
| wc -l 计数
`` 只记结果
abc=赋值
[root@centos01 ~]# abc=`history | wc -l`
[root@centos01 ~]# echo $abc
48
三、字符串比较
判断aaa字符串是否等于aaa字符串
[root@centos01 ~]# [ "aaa" = "aaa" ] && echo "Yes"
Yes
校验系统是否支持中文
[root@centos01 ~]# [ $LANG = "zh_CN.UTF-8" ] && echo "系统支持中文!!"
系统支持中文!!
[root@centos01 ~]# [ @LANG != "en.US" ] && echo "不支持中文!"
不支持中文!
四、逻辑测试
&&两个结果全部为真 显示“是目录”
[root@centos01 ~]# [ -d /etc ] && [ -d /boot ] && echo "是目录!"
是目录!
另一种写法
[root@centos01 ~]# [ -d /etc/ -a /boot/ ] && echo "yes"
yes
||两个结果一个为真就可以显示是目录
[root@centos01 ~]# [ -d /etc ] || [ -d /bot ] && echo "是目录!"
是目录!
五、if判断
[root@centos01 ~]# vim mkdir.sh
#!/bin/bash
mkdir_test=/mnt/test
if [ ! -d $mkdir_test ]
then
mkdir -p $mkdir_test
fi
给变量mkdir_test赋值 /mnt/test
判断/mnt/test是不是目录 是目录返回真 !取反 返回假 不执行任何命令
如果不是目录返回假 取反 返回真 执行then下的创建/mnt/test命令
添加执行权限
[root@centos01 ~]# chmod +x mkdir.sh
执行sehll
[root@centos01 ~]# ./mkdir.sh
查看结果
[root@centos01 ~]# ls /mnt/
测试磁盘空间
aa=`df -TH | grep "/$" | awk '{print $5}'`
六、双分支if判断
测试ping
[root@centos01 ~]# vim ping.sh
#!/bin/bash
read -p "请输入指定的ip地址:" insert
ping -c 3 -i 0.2 -w 3 $insert &> /dev/null
if [ $? -eq 0 ]
then
echo "host is $insert UP!!!"
else
echo "host is $insert DOWN!!!"
fi
测试正常地址
[root@centos01 ~]# ./ping.sh
请输入指定的ip地址:192.168.100.10
host is 192.168.100.10 UP!!!
测试错误地址
[root@centos01 ~]# ./ping.sh
请输入指定的ip地址:12312312123
host is 12312312123 DOWN!!!
七、多分支if判断
[root@centos01 ~]# vim test.sh
#!/bin/bash
read -p "输入考试成绩1~100分:" test
if [ $test -ge 80 ] && [ $test -le 100 ]
then
echo "$test 分,成绩优秀!"
elif [ $test -ge 60 ] && [ $test -lt 80 ]
then
echo "$test 分,成绩合格"
elif [ $test -ge 1 ] && [ $test -lt 60 ]
then
echo "$test 分,成绩不合格"
elif [ $test -gt 100 ] || [$test -lt 1 ]
then
echo "$test 分,成绩无效,请输入有效成绩"
else
echo "系统错误,请输入有效成绩"
fi