第二章 条件测试

第二章 条件测试

条件测试语句

1,文件测试:

#test命令格式:
test <测试表达式>
[root@localhost ~]# test -f file && echo true || echo false

#[]测试格式(中括号前后都有空格)
[<测试表达式>]
[root@localhost ~]# [ -f file ] && echo true || echo false

image.png

2,整数测试

#格式:
[整数1  操作符  整数2]
test 整数1  操作符  整数2

image.png

#测试主机是否正常
[root@localhost scripts]# vim ping001.sh
#!/bin/bash
ip=192.168.88.120
i=1
while [ $i -lt 5 ]
do
        ping -c1 $ip>/dev/null
        if [ $? -eq 0 ];then
                echo "$ip is up"
        fi
        let i++
done

3,关系测试

image.png

[root@localhost scripts]# ((1<2));echo $?
0
[root@localhost scripts]# ((1==2));echo $?
1

4,字符串测试

作用:比较字符串是否相同,测试字符串的长度是否为0。

#格式:
[ 字符串1 = 字符串2 ][ 字符串1 != 字符串2 ][ -z 字符串 ]

image.png

#字符串测试(安装服务器)
[root@localhost scripts]# vim install.sh
#!/bin/bash
if [ $user != root ];then
        echo "你没有权限"
        exit
fi
yum -y install httpd

5,逻辑测试

#格式:
[ 表达式1 ] 操作符 [ 表达式2 ]
或
命令1 操作符 命令2

image.png

if条件语句

1,if单分支:如果…那么…

if [条件表达式]
	then
		代码块
fi

或者:
if [条件表达式];then
	代码块
fi


#案例:判断文件是否存在
[root@localhost scripts]# vim ping002.sh
#!/bin/bash
if [ -f /etc/hosts ];then
        echo "1"
fi

2,if双分支:如果…那么…否则…

if [条件表达式]
	then
		代码块1
else
		代码块2
fi

#判断定义的名字是否为空
[root@localhost scripts]# vim name.sh
#!/bin/bash
name=yang
if [ -z "$name" ]
   then
        echo yes
else
        echo no
fi

3,if多分支:如果…就…否则…就…否则…

if [条件表达式1];then
		代码块1
elif [条件表达式2];then
		代码块2
elif [条件表达式3];then
		代码块3
else
		代码块4
fi

#安装Apache服务,检查DNS,网关,IP地址
[root@localhost scripts]# vim Apache.sh
#!/bin/bash
#install apache
#v1.0 by tianyue 2024-03-17
gateway=192.168.88.1

ping -c1 www.baidu.com &>/dev/null
if [ $? -eq 0 ];then
        yum -y install httpd
        systemctl start httpd
        systemctl enable httpd
        firewall-cmd --permanent --add-service=http
        firewall-cmd --permanent --add-service=https
        firewall-cmd -reload
        sed -ri '/^SELINUX=/cSELINUX=disabled' /etc/selinux/config
        setenforce 0
elif ping -c1 $gatway &/dev/null;then
        echo "check dns"
else
        echo "check ip address"
fi

case条件语句

case	变量值 in
条件表达式1)
	代码块1
	;;
条件表达式2)
	代码块2
	;;
条件表达式3)
	代码块3
	;;
   *)
	无匹配后代码块
esac

image.png

case条件语句案例实战

#case条件语句删除用户
[root@localhost scripts]# vim del_user.sh
#!/bin/bash
#v1.0 by tianyue 2024-03-17
read -p "please input a username:"user
id $user &>/dev/null
if [ $? -ne 0 ];then
        echo "no such user: $user"
        exit 1
fi
read -p "are you sure?[y/n]:" action
case "$action" in
Y|y|yes|YES)
        userdel -r $user
        echo "$user is deleted!"
        ;;
*)
        echo "error"
esac
  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值